@qitqode/qitqode-android-arm64 0.2.2 → 0.2.4

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 (427) hide show
  1. package/bun +2 -2
  2. package/bundle/{chunk-2hv2c8d5.js → chunk-0428v6mw.js} +1 -1
  3. package/bundle/{chunk-0f3ft9dh.js → chunk-05ck7acg.js} +1 -1
  4. package/bundle/{chunk-xmjntwjc.js → chunk-09geev0j.js} +2 -2
  5. package/bundle/{chunk-j5ymkhry.js → chunk-0cnwsf8p.js} +1 -1
  6. package/bundle/chunk-0ppnq3a4.js +2 -0
  7. package/bundle/{chunk-6kf4vw2g.js → chunk-0qd3567w.js} +1 -1
  8. package/bundle/{chunk-jw114bbt.js → chunk-0smnwqk6.js} +2 -2
  9. package/bundle/chunk-0te0vcdn.js +2 -0
  10. package/bundle/{chunk-q4fn41ex.js → chunk-0xrb12s8.js} +2 -2
  11. package/bundle/chunk-11h06z17.js +2 -0
  12. package/bundle/{chunk-vyh300ac.js → chunk-1rtx2zsc.js} +2 -2
  13. package/bundle/{chunk-3jms025t.js → chunk-1t0c86bz.js} +1 -1
  14. package/bundle/{chunk-6dfjtzqb.js → chunk-21rq4592.js} +2 -2
  15. package/bundle/{chunk-y3dfk6n5.js → chunk-24rkf2gk.js} +1 -1
  16. package/bundle/{chunk-rdwma0de.js → chunk-24ygjbpf.js} +2 -2
  17. package/bundle/{chunk-q46pzk9z.js → chunk-25ganjcn.js} +2 -2
  18. package/bundle/chunk-28yv4fqe.js +2 -0
  19. package/bundle/{chunk-3tmq81kq.js → chunk-2drzgtv3.js} +2 -2
  20. package/bundle/{chunk-xd3xc1vv.js → chunk-2md6sx8d.js} +1 -1
  21. package/bundle/chunk-2mm37s1w.js +2 -0
  22. package/bundle/chunk-2prf30p3.js +2 -0
  23. package/bundle/{chunk-v9rg0a8g.js → chunk-313zqzc1.js} +1 -1
  24. package/bundle/{chunk-zfd70p01.js → chunk-32j0q58h.js} +1 -1
  25. package/bundle/chunk-34a52hyr.js +2 -0
  26. package/bundle/{chunk-86jsqc7d.js → chunk-39z96pc6.js} +3 -3
  27. package/bundle/chunk-3hcr2bzt.js +2 -0
  28. package/bundle/{chunk-e6wp96vm.js → chunk-3jf3jhrs.js} +1 -1
  29. package/bundle/{chunk-4sxg9cgr.js → chunk-3kpse7zy.js} +1 -1
  30. package/bundle/chunk-3n3gb3vd.js +2 -0
  31. package/bundle/chunk-3sq60y9f.js +2 -0
  32. package/bundle/{chunk-2qwmrp16.js → chunk-3vvd7j14.js} +1 -1
  33. package/bundle/{chunk-h10wjk96.js → chunk-3zrr4n6k.js} +2 -2
  34. package/bundle/{chunk-rcyzqa3g.js → chunk-450fef7h.js} +2 -2
  35. package/bundle/{chunk-kxjrrdj0.js → chunk-45a4n21f.js} +1 -1
  36. package/bundle/{chunk-xny5ecn0.js → chunk-47k5jy1p.js} +2 -2
  37. package/bundle/{chunk-0gab4v98.js → chunk-48r70n4s.js} +1 -1
  38. package/bundle/chunk-49mbnqvc.js +2 -0
  39. package/bundle/{chunk-t9zbp2qw.js → chunk-4agaj51z.js} +1 -1
  40. package/bundle/chunk-4fr6kae9.js +2 -0
  41. package/bundle/chunk-4v2pzx22.js +2 -0
  42. package/bundle/chunk-516w1nc4.js +2 -0
  43. package/bundle/chunk-535nm66j.js +2 -0
  44. package/bundle/{chunk-1p6jjrea.js → chunk-55fcmswd.js} +2 -2
  45. package/bundle/{chunk-n7kqdqkh.js → chunk-55ykn8nz.js} +4 -4
  46. package/bundle/chunk-58dpxf8r.js +2 -0
  47. package/bundle/chunk-58w8c6c2.js +2 -0
  48. package/bundle/{chunk-as845ya4.js → chunk-5c2438af.js} +1 -1
  49. package/bundle/chunk-5kpxpm8e.js +2 -0
  50. package/bundle/chunk-5nm5s0h2.js +2 -0
  51. package/bundle/{chunk-07s30fpb.js → chunk-5nrc5rhh.js} +1 -1
  52. package/bundle/{chunk-jwph7tpc.js → chunk-5pwv2p3s.js} +1 -1
  53. package/bundle/{chunk-q5abwn50.js → chunk-5pzs51sp.js} +1 -1
  54. package/bundle/{chunk-r0s28gnb.js → chunk-5tky3csh.js} +1 -1
  55. package/bundle/{chunk-yajd975f.js → chunk-5w76kdjr.js} +1 -1
  56. package/bundle/{chunk-wcqfr8vr.js → chunk-5ysbwr4x.js} +1 -1
  57. package/bundle/{chunk-85xh72hk.js → chunk-5zkj5xv9.js} +2 -2
  58. package/bundle/chunk-620dpezx.js +5 -0
  59. package/bundle/{chunk-fgn83bs7.js → chunk-65bmsp2t.js} +1 -1
  60. package/bundle/{chunk-9jrxrjzt.js → chunk-68v3b6ns.js} +2 -2
  61. package/bundle/{chunk-7ntw4rrn.js → chunk-6ar91jvd.js} +1 -1
  62. package/bundle/{chunk-bbbh69ys.js → chunk-6evh2ke8.js} +1 -1
  63. package/bundle/{chunk-9bm9z52r.js → chunk-6fc3gw3e.js} +1 -1
  64. package/bundle/chunk-6gpf2bjs.js +2 -0
  65. package/bundle/{chunk-a2dz9nqh.js → chunk-6m9jb0s9.js} +2 -2
  66. package/bundle/{chunk-e374shb8.js → chunk-6pe60dsw.js} +2 -2
  67. package/bundle/{chunk-yvjke593.js → chunk-6scf311w.js} +1 -1
  68. package/bundle/{chunk-epa576pa.js → chunk-6v5867cy.js} +3 -3
  69. package/bundle/{chunk-5wwd40t3.js → chunk-70q8qcb2.js} +1 -1
  70. package/bundle/{chunk-pfkm3j8g.js → chunk-73r8bjjz.js} +2 -2
  71. package/bundle/{chunk-hs3vfhar.js → chunk-7bcm7gg1.js} +1 -1
  72. package/bundle/chunk-7bgzcpdw.js +2 -0
  73. package/bundle/{chunk-ezfzb8qc.js → chunk-7g66qc1v.js} +2 -2
  74. package/bundle/{chunk-fd7fmvyw.js → chunk-7hvf9dgx.js} +1 -1
  75. package/bundle/{chunk-7zc04q43.js → chunk-7j4qne3q.js} +2 -2
  76. package/bundle/chunk-7kjvcbwa.js +2 -0
  77. package/bundle/{chunk-6j339s7a.js → chunk-7mppvhv9.js} +2 -2
  78. package/bundle/{chunk-7z884mz2.js → chunk-7msfwk15.js} +2 -2
  79. package/bundle/{chunk-kmwy6c9g.js → chunk-7vmx8bg9.js} +2 -2
  80. package/bundle/{chunk-7njz51r4.js → chunk-7x6yrtzn.js} +1 -1
  81. package/bundle/{chunk-yhsnmpzv.js → chunk-7zx1ve4w.js} +1 -1
  82. package/bundle/{chunk-skv9ww0s.js → chunk-804vmbcd.js} +1 -1
  83. package/bundle/chunk-8jma2btf.js +2 -0
  84. package/bundle/{chunk-543pt030.js → chunk-8q38721t.js} +2 -2
  85. package/bundle/{chunk-kdcnder5.js → chunk-8wwdrwf2.js} +1 -1
  86. package/bundle/{chunk-4fk46ngj.js → chunk-920z7g7j.js} +1 -1
  87. package/bundle/chunk-93e0w75z.js +2 -0
  88. package/bundle/{chunk-pzefsndd.js → chunk-953pqp3w.js} +1 -1
  89. package/bundle/chunk-97gp818s.js +2 -0
  90. package/bundle/chunk-9epf2zbh.js +2 -0
  91. package/bundle/{chunk-4hd3v58j.js → chunk-9hz56z6a.js} +1 -1
  92. package/bundle/chunk-9pmmf4k1.js +2 -0
  93. package/bundle/chunk-9y03z65a.js +2 -0
  94. package/bundle/{chunk-rk2bk4s7.js → chunk-9zm6r55d.js} +2 -2
  95. package/bundle/{chunk-t1475j9f.js → chunk-a3edstpn.js} +1 -1
  96. package/bundle/{chunk-8d6e4jg7.js → chunk-ab4dq1bn.js} +2 -2
  97. package/bundle/{chunk-w7em72p8.js → chunk-ac7482n2.js} +2 -2
  98. package/bundle/chunk-agv04nt7.js +2 -0
  99. package/bundle/{chunk-sjreby6e.js → chunk-aj1sgq1d.js} +1 -1
  100. package/bundle/chunk-ak8e1nrf.js +2 -0
  101. package/bundle/{chunk-cbmwhvxw.js → chunk-at22twxx.js} +2 -2
  102. package/bundle/{chunk-frsd6e1h.js → chunk-avefgbjg.js} +2 -2
  103. package/bundle/chunk-b034nf8g.js +2 -0
  104. package/bundle/chunk-b2p54yka.js +2 -0
  105. package/bundle/{chunk-z2h1gxyx.js → chunk-bbng1cea.js} +1 -1
  106. package/bundle/{chunk-5az84brc.js → chunk-bd21p9zz.js} +2 -2
  107. package/bundle/chunk-be7smmar.js +2 -0
  108. package/bundle/chunk-bghqsh7r.js +2 -0
  109. package/bundle/{chunk-y4e7e42x.js → chunk-bne5w117.js} +4 -4
  110. package/bundle/{chunk-j3jqk62r.js → chunk-bqn6bqws.js} +1 -1
  111. package/bundle/chunk-bryx5cx9.js +2 -0
  112. package/bundle/{chunk-tge53d52.js → chunk-bwbqkfv0.js} +1 -1
  113. package/bundle/chunk-c13rrw41.js +2 -0
  114. package/bundle/chunk-c2kkv619.js +2 -0
  115. package/bundle/{chunk-64c8q9zg.js → chunk-c36p881g.js} +3 -3
  116. package/bundle/chunk-c5xj1y5v.js +2 -0
  117. package/bundle/{chunk-91z7azf7.js → chunk-cdja76vj.js} +1 -1
  118. package/bundle/{chunk-7ab3yw9j.js → chunk-ckb1y6gv.js} +2 -2
  119. package/bundle/chunk-ckpm4dvv.js +2 -0
  120. package/bundle/{chunk-732yr6qq.js → chunk-cmb62jkt.js} +2 -2
  121. package/bundle/chunk-ct8twng1.js +2 -0
  122. package/bundle/{chunk-s77qktcn.js → chunk-cx78hhbx.js} +2 -2
  123. package/bundle/{chunk-1q1cddy4.js → chunk-cz5vta94.js} +1 -1
  124. package/bundle/{chunk-fpm2vgz6.js → chunk-d0x5pbkm.js} +1 -1
  125. package/bundle/chunk-d38y7bvh.js +2 -0
  126. package/bundle/chunk-d5qgc18n.js +2 -0
  127. package/bundle/chunk-d6hxsfm6.js +2 -0
  128. package/bundle/{chunk-29zm623f.js → chunk-d6jhs818.js} +2 -2
  129. package/bundle/chunk-descb9jz.js +2 -0
  130. package/bundle/{chunk-ssdw9zre.js → chunk-dj1jen1p.js} +1 -1
  131. package/bundle/{chunk-mswx4k75.js → chunk-dnnkq5y4.js} +2 -2
  132. package/bundle/{chunk-6pcmv8vs.js → chunk-dnsh1v42.js} +2 -2
  133. package/bundle/chunk-dvr2b9r1.js +2 -0
  134. package/bundle/chunk-dwhjgd8j.js +2 -0
  135. package/bundle/{chunk-s0ty36qg.js → chunk-dxdggn90.js} +1 -1
  136. package/bundle/chunk-dypdyrmy.js +2 -0
  137. package/bundle/{chunk-w30b563s.js → chunk-e8p92vz4.js} +2 -2
  138. package/bundle/chunk-ea5fktnn.js +2 -0
  139. package/bundle/{chunk-t1jgx17a.js → chunk-eg3syjtv.js} +2 -2
  140. package/bundle/{chunk-2a9rzgk6.js → chunk-ehb4hd9c.js} +1 -1
  141. package/bundle/{chunk-9jsgs71h.js → chunk-ejqzcdcx.js} +1 -1
  142. package/bundle/{chunk-5t0w9ecw.js → chunk-et3804wr.js} +1 -1
  143. package/bundle/{chunk-yd8bzhv6.js → chunk-ezrqhqkp.js} +1 -1
  144. package/bundle/chunk-f0t7rryn.js +3 -0
  145. package/bundle/{chunk-p635phfw.js → chunk-f31yvp20.js} +1 -1
  146. package/bundle/chunk-f4mf6tpp.js +2 -0
  147. package/bundle/chunk-f97k17t8.js +2 -0
  148. package/bundle/{chunk-yx1h0b5v.js → chunk-faee8zgc.js} +1 -1
  149. package/bundle/{chunk-p9mj4zyk.js → chunk-ff548b0j.js} +2 -2
  150. package/bundle/{chunk-bgng3rdj.js → chunk-fhqfqd5v.js} +2 -2
  151. package/bundle/{chunk-zek5c15t.js → chunk-fjbv3jht.js} +1 -1
  152. package/bundle/{chunk-hq9bgnqb.js → chunk-g22e4gw7.js} +1 -1
  153. package/bundle/chunk-g26tersc.js +2 -0
  154. package/bundle/{chunk-s0ptrw0z.js → chunk-g3wvtyw3.js} +1 -1
  155. package/bundle/{chunk-x4pdpka8.js → chunk-g42krp0z.js} +1 -1
  156. package/bundle/chunk-g4ehhdzp.js +2 -0
  157. package/bundle/{chunk-a9y27zd2.js → chunk-gbkz04ke.js} +1 -1
  158. package/bundle/chunk-gd6qpdjw.js +2 -0
  159. package/bundle/chunk-gehn9fd9.js +2 -0
  160. package/bundle/{chunk-0zxwjsvz.js → chunk-ggxzf22k.js} +1 -1
  161. package/bundle/{chunk-45fyv9f1.js → chunk-grnjm8ev.js} +2 -2
  162. package/bundle/{chunk-kzvvvj79.js → chunk-gszvgz76.js} +2 -2
  163. package/bundle/{chunk-g3kd4957.js → chunk-gy21fw82.js} +2 -2
  164. package/bundle/{chunk-cbf1y12x.js → chunk-h62chdmw.js} +1 -1
  165. package/bundle/{chunk-c1g8n10t.js → chunk-ha1w0xzh.js} +1 -1
  166. package/bundle/{chunk-rpfhgncs.js → chunk-has2rz35.js} +1 -1
  167. package/bundle/{chunk-6f8qqbac.js → chunk-hg4039nz.js} +166 -205
  168. package/bundle/chunk-hhax4mxw.js +2 -0
  169. package/bundle/{chunk-087tnr8a.js → chunk-hwrrrbqd.js} +1 -1
  170. package/bundle/chunk-hz3h6e19.js +2 -0
  171. package/bundle/{chunk-yd2emszh.js → chunk-j0bwa5dk.js} +2 -2
  172. package/bundle/{chunk-9b4aqcde.js → chunk-j164q40b.js} +2 -2
  173. package/bundle/{chunk-et5dnymk.js → chunk-j4ad3mde.js} +2 -2
  174. package/bundle/{chunk-qhnpq5gb.js → chunk-j8fcfhr2.js} +2 -2
  175. package/bundle/chunk-j8nkz81m.js +7 -0
  176. package/bundle/{chunk-9ea1n338.js → chunk-j9h1sp4g.js} +2 -2
  177. package/bundle/{chunk-zcp0wx4j.js → chunk-jdx3jshm.js} +2 -2
  178. package/bundle/chunk-jebss7x8.js +2 -0
  179. package/bundle/{chunk-yrfq22a5.js → chunk-jg1ccs3j.js} +1 -1
  180. package/bundle/chunk-jqekpprn.js +3 -0
  181. package/bundle/{chunk-d307vb2d.js → chunk-jqk3v8d6.js} +1 -1
  182. package/bundle/chunk-jvkzdap1.js +2 -0
  183. package/bundle/{chunk-pp9neaaz.js → chunk-jww55nk9.js} +1 -1
  184. package/bundle/{chunk-fvy24yhq.js → chunk-k1nh5sd2.js} +1 -1
  185. package/bundle/chunk-k2g8346v.js +3 -0
  186. package/bundle/chunk-k2vsezeb.js +2 -0
  187. package/bundle/{chunk-wfggztm4.js → chunk-k4gsktts.js} +1 -1
  188. package/bundle/{chunk-qaz100ht.js → chunk-k5q9px67.js} +1 -1
  189. package/bundle/{chunk-mrn44msr.js → chunk-k6y2vw0d.js} +2 -2
  190. package/bundle/chunk-kg8fcv91.js +2 -0
  191. package/bundle/chunk-kgptyf7n.js +3 -0
  192. package/bundle/{chunk-b50t4jc5.js → chunk-khzzmyk2.js} +1 -1
  193. package/bundle/chunk-kjjjrjnb.js +2 -0
  194. package/bundle/{chunk-dbztxdea.js → chunk-kp6gh35c.js} +2 -2
  195. package/bundle/{chunk-g7k6ecb2.js → chunk-kqhczjf6.js} +1 -1
  196. package/bundle/{chunk-jvjq554f.js → chunk-ksme3gj1.js} +1 -1
  197. package/bundle/chunk-m5cfmhwh.js +2 -0
  198. package/bundle/{chunk-4v61ysex.js → chunk-m5dm7a1t.js} +1 -1
  199. package/bundle/{chunk-yr35q7q1.js → chunk-m7ganre7.js} +1 -1
  200. package/bundle/chunk-m7qxxbns.js +2 -0
  201. package/bundle/{chunk-y287zwkr.js → chunk-mh19kwzw.js} +1 -1
  202. package/bundle/{chunk-7my2231h.js → chunk-mhhtf0v3.js} +1 -1
  203. package/bundle/{chunk-grw4gg9j.js → chunk-mjjaezwq.js} +2 -2
  204. package/bundle/{chunk-03mbn7nj.js → chunk-mmjgf680.js} +2 -2
  205. package/bundle/{chunk-jv4th87b.js → chunk-mn9end71.js} +1 -1
  206. package/bundle/{chunk-3h49k2ck.js → chunk-n23d0q00.js} +1 -1
  207. package/bundle/{chunk-mpe8zxc0.js → chunk-n78f8hfk.js} +1 -1
  208. package/bundle/chunk-n8wg5h5p.js +2 -0
  209. package/bundle/{chunk-gr4bctqj.js → chunk-nj1ntakd.js} +2 -2
  210. package/bundle/{chunk-wdaf713t.js → chunk-nrat6ncm.js} +1 -1
  211. package/bundle/{chunk-rm5ntsvn.js → chunk-nty5z2cj.js} +1 -1
  212. package/bundle/{chunk-rp8asmq7.js → chunk-p169ee92.js} +1 -1
  213. package/bundle/{chunk-fbm6qczy.js → chunk-p4027t94.js} +1 -1
  214. package/bundle/{chunk-94qhpkfx.js → chunk-p54bzjtv.js} +1 -1
  215. package/bundle/{chunk-cp39f96a.js → chunk-p5be5ddp.js} +1 -1
  216. package/bundle/{chunk-ngvp6zc2.js → chunk-p6crzjtf.js} +2 -2
  217. package/bundle/chunk-p6hcj3kv.js +2 -0
  218. package/bundle/{chunk-p4ewy9xh.js → chunk-pb30kkbs.js} +6 -6
  219. package/bundle/chunk-pdjafjry.js +3 -0
  220. package/bundle/chunk-pexmns0j.js +2 -0
  221. package/bundle/{chunk-my3cswnp.js → chunk-ph8hn1wt.js} +2 -2
  222. package/bundle/chunk-pkn85169.js +2 -0
  223. package/bundle/{chunk-99148b1k.js → chunk-pmg53fdd.js} +1 -1
  224. package/bundle/{chunk-wf4x5cjc.js → chunk-pr7z5dj8.js} +1 -1
  225. package/bundle/chunk-pt603np4.js +2 -0
  226. package/bundle/{chunk-4mvg7jt1.js → chunk-ptqk1j2r.js} +1 -1
  227. package/bundle/{chunk-a92hh67a.js → chunk-pxm4qvqk.js} +2 -2
  228. package/bundle/{chunk-3qfpw8f6.js → chunk-qey1efpx.js} +1 -1
  229. package/bundle/chunk-qk5bfcv8.js +2 -0
  230. package/bundle/{chunk-9s785py4.js → chunk-qk9x8j8d.js} +1 -1
  231. package/bundle/chunk-qnaw8k98.js +2 -0
  232. package/bundle/{chunk-ks1cs80p.js → chunk-qnvsqnz5.js} +2 -2
  233. package/bundle/{chunk-bcx2vkv4.js → chunk-qp1n7kwe.js} +1 -1
  234. package/bundle/chunk-qr06byhp.js +2 -0
  235. package/bundle/{chunk-gtjn3yc4.js → chunk-qxcyz5hc.js} +2 -2
  236. package/bundle/{chunk-tj3rem3q.js → chunk-r5zy4za0.js} +2 -2
  237. package/bundle/chunk-r6p0bd2w.js +8251 -0
  238. package/bundle/chunk-r7sq3maz.js +2 -0
  239. package/bundle/{chunk-f83wv08n.js → chunk-r9w0thdk.js} +1 -1
  240. package/bundle/chunk-rmgs9nmj.js +2 -0
  241. package/bundle/{chunk-p887g1xj.js → chunk-rn83r0js.js} +1 -1
  242. package/bundle/{chunk-n90eh3e7.js → chunk-rrv0n73b.js} +1 -1
  243. package/bundle/chunk-rv08wm9j.js +2 -0
  244. package/bundle/chunk-rytavefg.js +2 -0
  245. package/bundle/{chunk-yz0pwv2m.js → chunk-s4vx9x1v.js} +1 -1
  246. package/bundle/{chunk-x2cavpa9.js → chunk-sfw5qddj.js} +1 -1
  247. package/bundle/chunk-sh9vjnsh.js +2 -0
  248. package/bundle/{chunk-6avjq7my.js → chunk-smznrv7k.js} +1 -1
  249. package/bundle/{chunk-vtw0wwch.js → chunk-snqa3zsm.js} +3 -3
  250. package/bundle/chunk-st0c5wwc.js +2 -0
  251. package/bundle/{chunk-vqss3e48.js → chunk-t0761rhq.js} +2 -2
  252. package/bundle/{chunk-vqpfpmha.js → chunk-t239rvej.js} +2 -2
  253. package/bundle/{chunk-5js6a6gf.js → chunk-t2n7vgsq.js} +1 -1
  254. package/bundle/chunk-t6yzrmww.js +2 -0
  255. package/bundle/{chunk-bggybm9k.js → chunk-t8c4cs6z.js} +1 -1
  256. package/bundle/chunk-teb3k2sf.js +2 -0
  257. package/bundle/{chunk-ve3np791.js → chunk-tg226j37.js} +1 -1
  258. package/bundle/chunk-thrfabyv.js +35 -0
  259. package/bundle/{chunk-73fz0cf4.js → chunk-tkrwcjkr.js} +2 -2
  260. package/bundle/{chunk-v5z6sx6j.js → chunk-tm34qp8j.js} +1 -1
  261. package/bundle/chunk-tr6rdr6h.js +4 -0
  262. package/bundle/chunk-ts798jvf.js +2 -0
  263. package/bundle/{chunk-a550vst5.js → chunk-twp3mjj0.js} +9 -9
  264. package/bundle/chunk-tx5aj02v.js +2 -0
  265. package/bundle/chunk-v1t51rrq.js +2 -0
  266. package/bundle/{chunk-vk88jj60.js → chunk-v3arcn10.js} +1 -1
  267. package/bundle/{chunk-e586sjb0.js → chunk-vcygx6hs.js} +2 -2
  268. package/bundle/{chunk-86yk21g4.js → chunk-venprxdp.js} +1 -1
  269. package/bundle/{chunk-ywkvq7zb.js → chunk-vf492zs6.js} +1 -1
  270. package/bundle/chunk-vh9ptqn0.js +2 -0
  271. package/bundle/{chunk-w79jzf8w.js → chunk-vnrjk2be.js} +1 -1
  272. package/bundle/{chunk-8q5ns61h.js → chunk-vshycswk.js} +1 -1
  273. package/bundle/{chunk-8e6gx3gg.js → chunk-vsz4s6zt.js} +1 -1
  274. package/bundle/{chunk-vhe92p7a.js → chunk-vygkwwjd.js} +2 -2
  275. package/bundle/{chunk-9rxyq6f9.js → chunk-w46g7kdq.js} +2 -2
  276. package/bundle/{chunk-q128vfc6.js → chunk-w4brava0.js} +1 -1
  277. package/bundle/{chunk-drwqag0f.js → chunk-w4synhfg.js} +1 -1
  278. package/bundle/chunk-w72rctxz.js +2 -0
  279. package/bundle/{chunk-h2bmss2m.js → chunk-w88ve2pm.js} +1 -1
  280. package/bundle/{chunk-mxhb5adq.js → chunk-w9gzfsy7.js} +2 -2
  281. package/bundle/chunk-wbw9zv3h.js +2 -0
  282. package/bundle/{chunk-1sfcxdbw.js → chunk-wkg3c643.js} +2 -2
  283. package/bundle/{chunk-2bgqy6z7.js → chunk-wwdpw27v.js} +1 -1
  284. package/bundle/{chunk-km1n4ttr.js → chunk-wy3a4cab.js} +1 -1
  285. package/bundle/{chunk-tczbhj0e.js → chunk-wyj8cpx5.js} +1 -1
  286. package/bundle/{chunk-3888asr7.js → chunk-x65xbskr.js} +1 -1
  287. package/bundle/chunk-x6mw98c2.js +2 -0
  288. package/bundle/chunk-x749e61j.js +2 -0
  289. package/bundle/{chunk-8rh0femq.js → chunk-xdd3553a.js} +1 -1
  290. package/bundle/{chunk-2jpmxt4v.js → chunk-xdteq9bd.js} +1 -1
  291. package/bundle/{chunk-9y15zjxa.js → chunk-xe69cnsk.js} +1 -1
  292. package/bundle/chunk-xpjhe9gz.js +2 -0
  293. package/bundle/{chunk-8v6x712g.js → chunk-xv5z1bj6.js} +2 -2
  294. package/bundle/{chunk-bk3z400e.js → chunk-y0527cg0.js} +1 -1
  295. package/bundle/{chunk-hrw5rmj1.js → chunk-y29ejqg2.js} +1 -1
  296. package/bundle/{chunk-42r7z6sq.js → chunk-y67kaj0b.js} +1 -1
  297. package/bundle/chunk-y6p57wgh.js +2 -0
  298. package/bundle/chunk-y6xs8v17.js +2 -0
  299. package/bundle/{chunk-zdzxsyxs.js → chunk-y7hgevfv.js} +2 -2
  300. package/bundle/{chunk-k1gddnkm.js → chunk-ybane1en.js} +1 -1
  301. package/bundle/{chunk-k6cbfrzc.js → chunk-yhj01dz9.js} +2 -2
  302. package/bundle/chunk-ym09zrxe.js +3 -0
  303. package/bundle/{chunk-2xqqkf86.js → chunk-ypdt9mmr.js} +2 -2
  304. package/bundle/chunk-ytetprwr.js +2 -0
  305. package/bundle/{chunk-vm1ek7yf.js → chunk-yz25607t.js} +1 -1
  306. package/bundle/{chunk-ypcc3cnb.js → chunk-z1932c3f.js} +1 -1
  307. package/bundle/chunk-z3xsfpc6.js +2 -0
  308. package/bundle/{chunk-6ypafpg8.js → chunk-z6sbjvtv.js} +1 -1
  309. package/bundle/{chunk-ta7mfkms.js → chunk-zc0cdvcv.js} +2 -2
  310. package/bundle/chunk-zn5pw733.js +2 -0
  311. package/bundle/chunk-ztn9e8g1.js +2 -0
  312. package/bundle/{chunk-ywdtp534.js → chunk-ztyy3ga3.js} +2 -2
  313. package/bundle/chunk-zxwvnmea.js +2 -0
  314. package/bundle/chunk-zzznad30.js +2 -0
  315. package/bundle/index.js +18 -18
  316. package/bundle/parser.worker.js +2 -2
  317. package/bundle/qffi-compat.so +0 -0
  318. package/bundle/qffi.node +0 -0
  319. package/bundle/worker.js +1 -1
  320. package/package.json +1 -1
  321. package/bundle/chunk-0cdtq1r3.js +0 -2
  322. package/bundle/chunk-0ych0f5w.js +0 -2
  323. package/bundle/chunk-0yjdatm6.js +0 -3
  324. package/bundle/chunk-0ykeedfm.js +0 -2
  325. package/bundle/chunk-22hr3ndh.js +0 -2
  326. package/bundle/chunk-23tyxyyj.js +0 -2
  327. package/bundle/chunk-2517cev8.js +0 -2
  328. package/bundle/chunk-28g1ndpx.js +0 -2
  329. package/bundle/chunk-2avxtbv3.js +0 -2
  330. package/bundle/chunk-2faah8w1.js +0 -2
  331. package/bundle/chunk-2qk0k2eb.js +0 -2
  332. package/bundle/chunk-3c3xzz0g.js +0 -3
  333. package/bundle/chunk-42wdfks8.js +0 -2
  334. package/bundle/chunk-44y6dffe.js +0 -2
  335. package/bundle/chunk-4f19vqxf.js +0 -2
  336. package/bundle/chunk-4m3k1atq.js +0 -2
  337. package/bundle/chunk-4n2ytddp.js +0 -2
  338. package/bundle/chunk-4yg42p6y.js +0 -2
  339. package/bundle/chunk-4zx3ze68.js +0 -2
  340. package/bundle/chunk-637sjdzq.js +0 -2
  341. package/bundle/chunk-6h8f89tt.js +0 -2
  342. package/bundle/chunk-6sjj203r.js +0 -2
  343. package/bundle/chunk-79aka9xe.js +0 -2
  344. package/bundle/chunk-7nqdhe7x.js +0 -2
  345. package/bundle/chunk-7q003wdd.js +0 -4
  346. package/bundle/chunk-7x88b2n2.js +0 -2
  347. package/bundle/chunk-8apeexas.js +0 -3
  348. package/bundle/chunk-8mthftwc.js +0 -2
  349. package/bundle/chunk-8wdara3b.js +0 -2
  350. package/bundle/chunk-8xhzpnph.js +0 -2
  351. package/bundle/chunk-96sqbyvf.js +0 -2
  352. package/bundle/chunk-9akz8w0d.js +0 -2
  353. package/bundle/chunk-9etpppyv.js +0 -3
  354. package/bundle/chunk-9pnpmtb2.js +0 -2
  355. package/bundle/chunk-a5pbvp1f.js +0 -7
  356. package/bundle/chunk-a7p0x4sw.js +0 -2
  357. package/bundle/chunk-ae0a496j.js +0 -2
  358. package/bundle/chunk-aq1j9y18.js +0 -2
  359. package/bundle/chunk-aq8nz9hp.js +0 -2
  360. package/bundle/chunk-b4zy78be.js +0 -2
  361. package/bundle/chunk-basjzwqp.js +0 -2
  362. package/bundle/chunk-bhetpmgq.js +0 -3
  363. package/bundle/chunk-bm7xpjh6.js +0 -2
  364. package/bundle/chunk-c1bw1q75.js +0 -2
  365. package/bundle/chunk-c2k556rk.js +0 -2
  366. package/bundle/chunk-c47vp7ne.js +0 -2
  367. package/bundle/chunk-cbhgf058.js +0 -2
  368. package/bundle/chunk-d41mg7at.js +0 -2
  369. package/bundle/chunk-d50kpss6.js +0 -2
  370. package/bundle/chunk-day0rb5p.js +0 -2
  371. package/bundle/chunk-dp7cww4v.js +0 -2
  372. package/bundle/chunk-dy31mchw.js +0 -3
  373. package/bundle/chunk-e5rda9mx.js +0 -2
  374. package/bundle/chunk-e999xtfj.js +0 -2
  375. package/bundle/chunk-ehfxypks.js +0 -7610
  376. package/bundle/chunk-eyr0vf92.js +0 -2
  377. package/bundle/chunk-gbmmbhy4.js +0 -2
  378. package/bundle/chunk-gp877cq5.js +0 -2
  379. package/bundle/chunk-h4f582d6.js +0 -2
  380. package/bundle/chunk-h57c6ne3.js +0 -2
  381. package/bundle/chunk-hk8vvc10.js +0 -2
  382. package/bundle/chunk-hnrqhcgq.js +0 -2
  383. package/bundle/chunk-hwavzxdm.js +0 -2
  384. package/bundle/chunk-hwnc2sa5.js +0 -2
  385. package/bundle/chunk-hy86wfad.js +0 -2
  386. package/bundle/chunk-j17421hz.js +0 -2
  387. package/bundle/chunk-j2gvpa15.js +0 -2
  388. package/bundle/chunk-j7n8khk7.js +0 -2
  389. package/bundle/chunk-jkh98wby.js +0 -2
  390. package/bundle/chunk-k5a652s4.js +0 -2
  391. package/bundle/chunk-k6w32q2p.js +0 -2
  392. package/bundle/chunk-kghwk0yh.js +0 -2
  393. package/bundle/chunk-kh8de8re.js +0 -2
  394. package/bundle/chunk-mce8aa9y.js +0 -2
  395. package/bundle/chunk-me1ja46g.js +0 -2
  396. package/bundle/chunk-mgadsp7r.js +0 -2
  397. package/bundle/chunk-n0k0pp4k.js +0 -2
  398. package/bundle/chunk-n393nnh5.js +0 -2
  399. package/bundle/chunk-n5vyed7w.js +0 -2
  400. package/bundle/chunk-pasm65wq.js +0 -2
  401. package/bundle/chunk-phpmxjf8.js +0 -2
  402. package/bundle/chunk-q2q3dmg3.js +0 -2
  403. package/bundle/chunk-qvzvxsjw.js +0 -2
  404. package/bundle/chunk-racrb1b3.js +0 -2
  405. package/bundle/chunk-s0c0t6qr.js +0 -5
  406. package/bundle/chunk-sghy9s7m.js +0 -2
  407. package/bundle/chunk-skpkjnyy.js +0 -2
  408. package/bundle/chunk-skxhg212.js +0 -2
  409. package/bundle/chunk-snt4kwab.js +0 -2
  410. package/bundle/chunk-sq47t8f1.js +0 -2
  411. package/bundle/chunk-sqhgnvvs.js +0 -2
  412. package/bundle/chunk-t114r59h.js +0 -2
  413. package/bundle/chunk-t1f56k0j.js +0 -2
  414. package/bundle/chunk-t69jx6fz.js +0 -2
  415. package/bundle/chunk-tsb3jsx4.js +0 -2
  416. package/bundle/chunk-ttpbpzbh.js +0 -2
  417. package/bundle/chunk-v667egp5.js +0 -2
  418. package/bundle/chunk-vrv67tt0.js +0 -2
  419. package/bundle/chunk-wcx7hc2p.js +0 -635
  420. package/bundle/chunk-wv8qx8sa.js +0 -2
  421. package/bundle/chunk-xxrtr6sd.js +0 -2
  422. package/bundle/chunk-y2ptjam9.js +0 -3
  423. package/bundle/chunk-y6h35v4a.js +0 -2
  424. package/bundle/chunk-y72p79v2.js +0 -2
  425. package/bundle/chunk-y8eggnrr.js +0 -2
  426. package/bundle/chunk-y9q0f9qz.js +0 -2
  427. package/bundle/chunk-yck5h49c.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Cl,vl as KN}from"./chunk-e374shb8.js";import{Hl as L7,Jl as l$,Kl as xY,Ll as AY,Ml as I1,Nl as w$,Ol as I8,Ql as MA,Ul as W1,Wl as KX,Xl as aA,Yl as $9,cm as S8,dm as B0,fm as T7}from"./chunk-zcp0wx4j.js";import{im as xU,jm as hU,km as gw,mm as uw,om as L1}from"./chunk-epa576pa.js";import{Em as Jd,Lm as j8,Mm as w1,Nm as K9,Om as g6,Pm as k9,Rm as m0,Tm as O$,Um as wL,Xm as oA,Ym as WX,Zm as Yd,_m as k5,an as iK,gn as sA,on as o6}from"./chunk-y287zwkr.js";import{vn as r8,wn as $U,xn as s8,yn as Kw}from"./chunk-7zc04q43.js";import{Cn as AN,Dn as ON,Fn as aD,Hn as q6,In as Nm,Jn as Em,Kn as Mm,Nn as Dm,On as wm,Qn as Lm,Sn as CA,Tn as bm,Un as _m,Zn as JX,zn as Mw}from"./chunk-vtw0wwch.js";import{$n as u0,ao as Jm,bo as F$,co as tD,do as w0}from"./chunk-e586sjb0.js";import{eo as Tm}from"./chunk-b50t4jc5.js";import{fo as d0}from"./chunk-zdzxsyxs.js";import{ho as pL,oo as cL}from"./chunk-xny5ecn0.js";import{To as vl,Uo as yl,po as k7,qo as u2,vo as SA,xo as Ol,yo as ql}from"./chunk-8d6e4jg7.js";import{$o as Q8,Bp as v8,Cp as qX,Dp as A4,Ep as y8,Gp as G8,Qp as QH,Yp as dL,_o as xL,bp as FJ,cp as HX,gp as z4,hp as hL,ip as gL,jp as aU,lp as a6,np as AX,op as N4,pp as uL,rp as OX,tp as mL,up as lL,zp as M4}from"./chunk-my3cswnp.js";import{Zp as p0,_p as FX,aq as r6,cq as yZ,eq as JH,fq as YH,hq as XH,jq as C8,kq as g5,lq as rU,mq as UX}from"./chunk-4mvg7jt1.js";import{vq as mu}from"./chunk-vqpfpmha.js";import{yq as BA,zq as _u}from"./chunk-fd7fmvyw.js";import{Mq as Ww,Oq as AO,Sq as VO}from"./chunk-s77qktcn.js";import{Uq as G2}from"./chunk-8v6x712g.js";import{br as GN,ir as V$,jr as PZ,pr as h9,qr as WN}from"./chunk-pfkm3j8g.js";import{Or as D8,Zr as qA}from"./chunk-h2bmss2m.js";import{_r as n8,cs as f1}from"./chunk-ywdtp534.js";import{ds as V00}from"./chunk-03mbn7nj.js";import{ks as Q30}from"./chunk-gr4bctqj.js";import{rs as j1}from"./chunk-73fz0cf4.js";import{ts as F8}from"./chunk-0cdtq1r3.js";import{Cs as Gl,Ds as bK,Es as N1,Fs as _K,Gs as v6,Ps as eQ,us as E$,ys as DN,zs as vm}from"./chunk-xmjntwjc.js";import{Vs as J8,Xs as UY,Ys as V6}from"./chunk-tj3rem3q.js";import{et as b0,nt as E0}from"./chunk-7q003wdd.js";import{At as mV,Dt as F0,tt as $4,ut as D$,yt as o0,zt as V4}from"./chunk-cbmwhvxw.js";import{Et as P}from"./chunk-9etpppyv.js";import{au as D}from"./chunk-9ea1n338.js";import{Uy as oV}from"./chunk-1p6jjrea.js";import{$I as hw,EB as O1,FI as Nw,GE as PY,HC as ul,NH as nV,OI as h6,SB as S1,TC as Z8,WE as T0,aC as v7,bF as n7,cE as xw,jE as B9,kO as O,oK as I$,pF as W4,qE as f6,rC as y7,xH as T}from"./chunk-ks1cs80p.js";import{KO as yL}from"./chunk-qhnpq5gb.js";import{LO as m6,MO as S,NO as F1,PO as Y0,QO as CK,RO as EK}from"./chunk-f83wv08n.js";var R7=S((MO)=>{Object.defineProperty(MO,"__esModule",{value:!0});MO.stringArray=MO.array=MO.func=MO.error=MO.number=MO.string=MO.boolean=void 0;function ed($){return $===!0||$===!1}MO.boolean=ed;function jO($){return typeof $==="string"||$ instanceof String}MO.string=jO;function $p($){return typeof $==="number"||$ instanceof Number}MO.number=$p;function Zp($){return $ instanceof Error}MO.error=Zp;function Jp($){return typeof $==="function"}MO.func=Jp;function NO($){return Array.isArray($)}MO.array=NO;function Yp($){return NO($)&&$.every((Z)=>jO(Z))}MO.stringArray=Yp});var HV=S((cO)=>{Object.defineProperty(cO,"__esModule",{value:!0});cO.Message=cO.NotificationType9=cO.NotificationType8=cO.NotificationType7=cO.NotificationType6=cO.NotificationType5=cO.NotificationType4=cO.NotificationType3=cO.NotificationType2=cO.NotificationType1=cO.NotificationType0=cO.NotificationType=cO.RequestType9=cO.RequestType8=cO.RequestType7=cO.RequestType6=cO.RequestType5=cO.RequestType4=cO.RequestType3=cO.RequestType2=cO.RequestType1=cO.RequestType=cO.RequestType0=cO.AbstractMessageSignature=cO.ParameterStructures=cO.ResponseError=cO.ErrorCodes=void 0;var z5=R7(),VV;(function($){$.ParseError=-32700,$.InvalidRequest=-32600,$.MethodNotFound=-32601,$.InvalidParams=-32602,$.InternalError=-32603,$.jsonrpcReservedErrorRangeStart=-32099,$.serverErrorStart=-32099,$.MessageWriteError=-32099,$.MessageReadError=-32098,$.PendingResponseRejected=-32097,$.ConnectionInactive=-32096,$.ServerNotInitialized=-32002,$.UnknownErrorCode=-32001,$.jsonrpcReservedErrorRangeEnd=-32000,$.serverErrorEnd=-32000})(VV||(cO.ErrorCodes=VV={}));class UV extends Error{constructor($,Z,J){super(Z);this.code=z5.number($)?$:VV.UnknownErrorCode,this.data=J,Object.setPrototypeOf(this,UV.prototype)}toJson(){let $={code:this.code,message:this.message};if(this.data!==void 0)$.data=this.data;return $}}cO.ResponseError=UV;class h${constructor($){this.kind=$}static is($){return $===h$.auto||$===h$.byName||$===h$.byPosition}toString(){return this.kind}}cO.ParameterStructures=h$;h$.auto=new h$("auto");h$.byPosition=new h$("byPosition");h$.byName=new h$("byName");class n1{constructor($,Z){this.method=$,this.numberOfParams=Z}get parameterStructures(){return h$.auto}}cO.AbstractMessageSignature=n1;class LO extends n1{constructor($){super($,0)}}cO.RequestType0=LO;class TO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType=TO;class RO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType1=RO;class PO extends n1{constructor($){super($,2)}}cO.RequestType2=PO;class IO extends n1{constructor($){super($,3)}}cO.RequestType3=IO;class CO extends n1{constructor($){super($,4)}}cO.RequestType4=CO;class EO extends n1{constructor($){super($,5)}}cO.RequestType5=EO;class bO extends n1{constructor($){super($,6)}}cO.RequestType6=bO;class _O extends n1{constructor($){super($,7)}}cO.RequestType7=_O;class SO extends n1{constructor($){super($,8)}}cO.RequestType8=SO;class fO extends n1{constructor($){super($,9)}}cO.RequestType9=fO;class kO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType=kO;class vO extends n1{constructor($){super($,0)}}cO.NotificationType0=vO;class yO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType1=yO;class xO extends n1{constructor($){super($,2)}}cO.NotificationType2=xO;class hO extends n1{constructor($){super($,3)}}cO.NotificationType3=hO;class gO extends n1{constructor($){super($,4)}}cO.NotificationType4=gO;class uO extends n1{constructor($){super($,5)}}cO.NotificationType5=uO;class mO extends n1{constructor($){super($,6)}}cO.NotificationType6=mO;class lO extends n1{constructor($){super($,7)}}cO.NotificationType7=lO;class dO extends n1{constructor($){super($,8)}}cO.NotificationType8=dO;class pO extends n1{constructor($){super($,9)}}cO.NotificationType9=pO;var wO;(function($){function Z(X){let Q=X;return Q&&z5.string(Q.method)&&(z5.string(Q.id)||z5.number(Q.id))}$.isRequest=Z;function J(X){let Q=X;return Q&&z5.string(Q.method)&&X.id===void 0}$.isNotification=J;function Y(X){let Q=X;return Q&&(Q.result!==void 0||!!Q.error)&&(z5.string(Q.id)||z5.number(Q.id)||Q.id===null)}$.isResponse=Y})(wO||(cO.Message=wO={}))});var zV=S((sO)=>{var nO;Object.defineProperty(sO,"__esModule",{value:!0});sO.LRUCache=sO.LinkedMap=sO.Touch=void 0;var g$;(function($){$.None=0,$.First=1,$.AsOld=$.First,$.Last=2,$.AsNew=$.Last})(g$||(sO.Touch=g$={}));class BV{constructor(){this[nO]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has($){return this._map.has($)}get($,Z=g$.None){let J=this._map.get($);if(!J)return;if(Z!==g$.None)this.touch(J,Z);return J.value}set($,Z,J=g$.None){let Y=this._map.get($);if(Y){if(Y.value=Z,J!==g$.None)this.touch(Y,J)}else{switch(Y={key:$,value:Z,next:void 0,previous:void 0},J){case g$.None:this.addItemLast(Y);break;case g$.First:this.addItemFirst(Y);break;case g$.Last:this.addItemLast(Y);break;default:this.addItemLast(Y);break}this._map.set($,Y),this._size++}return this}delete($){return!!this.remove($)}remove($){let Z=this._map.get($);if(!Z)return;return this._map.delete($),this.removeItem(Z),this._size--,Z.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error("Invalid list");let $=this._head;return this._map.delete($.key),this.removeItem($),this._size--,$.value}forEach($,Z){let J=this._state,Y=this._head;while(Y){if(Z)$.bind(Z)(Y.value,Y.key,this);else $(Y.value,Y.key,this);if(this._state!==J)throw Error("LinkedMap got modified during iteration.");Y=Y.next}}keys(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.key,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}values(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.value,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}entries(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:[Z.key,Z.value],done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}[(nO=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld($){if($>=this.size)return;if($===0){this.clear();return}let Z=this._head,J=this.size;while(Z&&J>$)this._map.delete(Z.key),Z=Z.next,J--;if(this._head=Z,this._size=J,Z)Z.previous=void 0;this._state++}addItemFirst($){if(!this._head&&!this._tail)this._tail=$;else if(!this._head)throw Error("Invalid list");else $.next=this._head,this._head.previous=$;this._head=$,this._state++}addItemLast($){if(!this._head&&!this._tail)this._head=$;else if(!this._tail)throw Error("Invalid list");else $.previous=this._tail,this._tail.next=$;this._tail=$,this._state++}removeItem($){if($===this._head&&$===this._tail)this._head=void 0,this._tail=void 0;else if($===this._head){if(!$.next)throw Error("Invalid list");$.next.previous=void 0,this._head=$.next}else if($===this._tail){if(!$.previous)throw Error("Invalid list");$.previous.next=void 0,this._tail=$.previous}else{let{next:Z,previous:J}=$;if(!Z||!J)throw Error("Invalid list");Z.previous=J,J.next=Z}$.next=void 0,$.previous=void 0,this._state++}touch($,Z){if(!this._head||!this._tail)throw Error("Invalid list");if(Z!==g$.First&&Z!==g$.Last)return;if(Z===g$.First){if($===this._head)return;let{next:J,previous:Y}=$;if($===this._tail)Y.next=void 0,this._tail=Y;else J.previous=Y,Y.next=J;$.previous=void 0,$.next=this._head,this._head.previous=$,this._head=$,this._state++}else if(Z===g$.Last){if($===this._tail)return;let{next:J,previous:Y}=$;if($===this._head)J.previous=void 0,this._head=J;else J.previous=Y,Y.next=J;$.next=void 0,$.previous=this._tail,this._tail.next=$,this._tail=$,this._state++}}toJSON(){let $=[];return this.forEach((Z,J)=>{$.push([J,Z])}),$}fromJSON($){this.clear();for(let[Z,J]of $)this.set(Z,J)}}sO.LinkedMap=BV;class oO extends BV{constructor($,Z=1){super();this._limit=$,this._ratio=Math.min(Math.max(0,Z),1)}get limit(){return this._limit}set limit($){this._limit=$,this.checkTrim()}get ratio(){return this._ratio}set ratio($){this._ratio=Math.min(Math.max(0,$),1),this.checkTrim()}get($,Z=g$.AsNew){return super.get($,Z)}peek($){return super.get($,g$.None)}set($,Z){return super.set($,Z,g$.Last),this.checkTrim(),this}checkTrim(){if(this.size>this._limit)this.trimOld(Math.round(this._limit*this._ratio))}}sO.LRUCache=oO});var $q=S((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});tO.Disposable=void 0;var aO;(function($){function Z(J){return{dispose:J}}$.create=Z})(aO||(tO.Disposable=aO={}))});var DZ=S((Zq)=>{Object.defineProperty(Zq,"__esModule",{value:!0});var FV;function AV(){if(FV===void 0)throw Error("No runtime abstraction layer installed");return FV}(function($){function Z(J){if(J===void 0)throw Error("No runtime abstraction layer provided");FV=J}$.install=Z})(AV||(AV={}));Zq.default=AV});var P7=S((Xq)=>{Object.defineProperty(Xq,"__esModule",{value:!0});Xq.Emitter=Xq.Event=void 0;var gp=DZ(),Jq;(function($){let Z={dispose(){}};$.None=function(){return Z}})(Jq||(Xq.Event=Jq={}));class Yq{add($,Z=null,J){if(!this._callbacks)this._callbacks=[],this._contexts=[];if(this._callbacks.push($),this._contexts.push(Z),Array.isArray(J))J.push({dispose:()=>this.remove($,Z)})}remove($,Z=null){if(!this._callbacks)return;let J=!1;for(let Y=0,X=this._callbacks.length;Y<X;Y++)if(this._callbacks[Y]===$)if(this._contexts[Y]===Z){this._callbacks.splice(Y,1),this._contexts.splice(Y,1);return}else J=!0;if(J)throw Error("When adding a listener with a context, you should remove it with the same context")}invoke(...$){if(!this._callbacks)return[];let Z=[],J=this._callbacks.slice(0),Y=this._contexts.slice(0);for(let X=0,Q=J.length;X<Q;X++)try{Z.push(J[X].apply(Y[X],$))}catch(G){(0,gp.default)().console.error(G)}return Z}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}}class q9{constructor($){this._options=$}get event(){if(!this._event)this._event=($,Z,J)=>{if(!this._callbacks)this._callbacks=new Yq;if(this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty())this._options.onFirstListenerAdd(this);this._callbacks.add($,Z);let Y={dispose:()=>{if(!this._callbacks)return;if(this._callbacks.remove($,Z),Y.dispose=q9._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty())this._options.onLastListenerRemove(this)}};if(Array.isArray(J))J.push(Y);return Y};return this._event}fire($){if(this._callbacks)this._callbacks.invoke.call(this._callbacks,$)}dispose(){if(this._callbacks)this._callbacks.dispose(),this._callbacks=void 0}}Xq.Emitter=q9;q9._noop=function(){}});var N9=S((Wq)=>{Object.defineProperty(Wq,"__esModule",{value:!0});Wq.CancellationTokenSource=Wq.CancellationToken=void 0;var mp=DZ(),lp=R7(),OV=P7(),j9;(function($){$.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:OV.Event.None}),$.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:OV.Event.None});function Z(J){let Y=J;return Y&&(Y===$.None||Y===$.Cancelled||lp.boolean(Y.isCancellationRequested)&&!!Y.onCancellationRequested)}$.is=Z})(j9||(Wq.CancellationToken=j9={}));var dp=Object.freeze(function($,Z){let J=(0,mp.default)().timer.setTimeout($.bind(Z),0);return{dispose(){J.dispose()}}});class qV{constructor(){this._isCancelled=!1}cancel(){if(!this._isCancelled){if(this._isCancelled=!0,this._emitter)this._emitter.fire(void 0),this.dispose()}}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){if(this._isCancelled)return dp;if(!this._emitter)this._emitter=new OV.Emitter;return this._emitter.event}dispose(){if(this._emitter)this._emitter.dispose(),this._emitter=void 0}}class Gq{get token(){if(!this._token)this._token=new qV;return this._token}cancel(){if(!this._token)this._token=j9.Cancelled;else this._token.cancel()}dispose(){if(!this._token)this._token=j9.None;else if(this._token instanceof qV)this._token.dispose()}}Wq.CancellationTokenSource=Gq});var Aq=S((zq)=>{Object.defineProperty(zq,"__esModule",{value:!0});zq.SharedArrayReceiverStrategy=zq.SharedArraySenderStrategy=void 0;var cp=N9(),bY;(function($){$.Continue=0,$.Cancelled=1})(bY||(bY={}));class Vq{constructor(){this.buffers=new Map}enableCancellation($){if($.id===null)return;let Z=new SharedArrayBuffer(4),J=new Int32Array(Z,0,1);J[0]=bY.Continue,this.buffers.set($.id,Z),$.$cancellationData=Z}async sendCancellation($,Z){let J=this.buffers.get(Z);if(J===void 0)return;let Y=new Int32Array(J,0,1);Atomics.store(Y,0,bY.Cancelled)}cleanup($){this.buffers.delete($)}dispose(){this.buffers.clear()}}zq.SharedArraySenderStrategy=Vq;class Uq{constructor($){this.data=new Int32Array($,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===bY.Cancelled}get onCancellationRequested(){throw Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class Hq{constructor($){this.token=new Uq($)}cancel(){}dispose(){}}class Bq{constructor(){this.kind="request"}createCancellationTokenSource($){let Z=$.$cancellationData;if(Z===void 0)return new cp.CancellationTokenSource;return new Hq(Z)}}zq.SharedArrayReceiverStrategy=Bq});var jV=S((qq)=>{Object.defineProperty(qq,"__esModule",{value:!0});qq.Semaphore=void 0;var np=DZ();class Oq{constructor($=1){if($<=0)throw Error("Capacity must be greater than 0");this._capacity=$,this._active=0,this._waiting=[]}lock($){return new Promise((Z,J)=>{this._waiting.push({thunk:$,resolve:Z,reject:J}),this.runNext()})}get active(){return this._active}runNext(){if(this._waiting.length===0||this._active===this._capacity)return;(0,np.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let $=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error("To many thunks active");try{let Z=$.thunk();if(Z instanceof Promise)Z.then((J)=>{this._active--,$.resolve(J),this.runNext()},(J)=>{this._active--,$.reject(J),this.runNext()});else this._active--,$.resolve(Z),this.runNext()}catch(Z){this._active--,$.reject(Z),this.runNext()}}}qq.Semaphore=Oq});var Lq=S((Dq)=>{Object.defineProperty(Dq,"__esModule",{value:!0});Dq.ReadableStreamMessageReader=Dq.AbstractMessageReader=Dq.MessageReader=void 0;var MV=DZ(),I7=R7(),NV=P7(),op=jV(),Nq;(function($){function Z(J){let Y=J;return Y&&I7.func(Y.listen)&&I7.func(Y.dispose)&&I7.func(Y.onError)&&I7.func(Y.onClose)&&I7.func(Y.onPartialMessage)}$.is=Z})(Nq||(Dq.MessageReader=Nq={}));class wV{constructor(){this.errorEmitter=new NV.Emitter,this.closeEmitter=new NV.Emitter,this.partialMessageEmitter=new NV.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError($){this.errorEmitter.fire(this.asError($))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage($){this.partialMessageEmitter.fire($)}asError($){if($ instanceof Error)return $;else return Error(`Reader received error. Reason: ${I7.string($.message)?$.message:"unknown"}`)}}Dq.AbstractMessageReader=wV;var DV;(function($){function Z(J){let Y,X,Q,G=new Map,W,K=new Map;if(J===void 0||typeof J==="string")Y=J??"utf-8";else{if(Y=J.charset??"utf-8",J.contentDecoder!==void 0)Q=J.contentDecoder,G.set(Q.name,Q);if(J.contentDecoders!==void 0)for(let V of J.contentDecoders)G.set(V.name,V);if(J.contentTypeDecoder!==void 0)W=J.contentTypeDecoder,K.set(W.name,W);if(J.contentTypeDecoders!==void 0)for(let V of J.contentTypeDecoders)K.set(V.name,V)}if(W===void 0)W=(0,MV.default)().applicationJson.decoder,K.set(W.name,W);return{charset:Y,contentDecoder:Q,contentDecoders:G,contentTypeDecoder:W,contentTypeDecoders:K}}$.fromOptions=Z})(DV||(DV={}));class Mq extends wV{constructor($,Z){super();this.readable=$,this.options=DV.fromOptions(Z),this.buffer=(0,MV.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new op.Semaphore(1)}set partialMessageTimeout($){this._partialMessageTimeout=$}get partialMessageTimeout(){return this._partialMessageTimeout}listen($){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=$;let Z=this.readable.onData((J)=>{this.onData(J)});return this.readable.onError((J)=>this.fireError(J)),this.readable.onClose(()=>this.fireClose()),Z}onData($){try{this.buffer.append($);while(!0){if(this.nextMessageLength===-1){let J=this.buffer.tryReadHeaders(!0);if(!J)return;let Y=J.get("content-length");if(!Y){this.fireError(Error(`Header must provide a Content-Length property.
2
+ import{el as KN,ll as Cl}from"./chunk-6pe60dsw.js";import{Dl as W1,Fl as KX,Gl as aA,Hl as $9,Nl as S8,Ol as B0,Ql as T7,ql as L7,sl as l$,tl as xY,ul as AY,vl as I1,wl as w$,xl as I8,zl as MA}from"./chunk-jdx3jshm.js";import{Tl as xU,Ul as hU,Vl as gw,Xl as uw,Zl as L1}from"./chunk-6v5867cy.js";import{Am as m0,Cm as O$,Dm as wL,Gm as oA,Hm as WX,Im as Yd,Jm as k5,Lm as iK,Rm as sA,Zm as o6,nm as Jd,um as j8,vm as w1,wm as K9,xm as g6,ym as k9}from"./chunk-mh19kwzw.js";import{en as r8,fn as $U,gn as s8,hn as Kw}from"./chunk-7j4qne3q.js";import{Bn as CA,Cn as bm,Dn as _m,In as JX,in as Mw,ln as AN,mn as ON,on as aD,qn as q6,rn as Nm,sn as Em,tn as Mm,wn as Dm,xn as wm,zn as Lm}from"./chunk-snqa3zsm.js";import{Kn as u0,Ln as Jm,Mn as F$,Nn as tD,On as w0}from"./chunk-vcygx6hs.js";import{Pn as Tm}from"./chunk-khzzmyk2.js";import{Qn as d0}from"./chunk-y7hgevfv.js";import{Sn as pL,Zn as cL}from"./chunk-47k5jy1p.js";import{$n as u2,Co as vl,Do as yl,_n as k7,eo as SA,go as Ol,ho as ql}from"./chunk-ab4dq1bn.js";import{Hp as dL,Jo as xL,Ko as Q8,Mo as FJ,No as HX,Ro as z4,So as hL,To as gL,Uo as aU,Wo as a6,Yo as AX,Zo as N4,_o as uL,ap as OX,cp as mL,dp as lL,ip as M4,kp as v8,lp as qX,mp as A4,np as y8,pp as G8,zp as QH}from"./chunk-ph8hn1wt.js";import{Ip as p0,Jp as FX,Lp as r6,Np as yZ,Pp as JH,Qp as YH,Sp as XH,Up as C8,Vp as g5,Wp as rU,Xp as UX}from"./chunk-ptqk1j2r.js";import{eq as mu}from"./chunk-t239rvej.js";import{hq as BA,iq as _u}from"./chunk-7hvf9dgx.js";import{Bq as VO,vq as Ww,xq as AO}from"./chunk-cx78hhbx.js";import{Dq as G2}from"./chunk-xv5z1bj6.js";import{$q as WN,Mq as GN,Tq as V$,Uq as PZ,_q as h9}from"./chunk-73r8bjjz.js";import{Ir as qA,xr as D8}from"./chunk-w88ve2pm.js";import{Jr as n8,Nr as f1}from"./chunk-ztyy3ga3.js";import{Or as V00}from"./chunk-mmjgf680.js";import{Vr as Q30}from"./chunk-nj1ntakd.js";import{as as j1}from"./chunk-tkrwcjkr.js";import{cs as F8}from"./chunk-ztn9e8g1.js";import{ds as E$,hs as DN,is as vm,ls as Gl,ms as bK,ns as N1,os as _K,ps as v6,ys as eQ}from"./chunk-09geev0j.js";import{Es as J8,Gs as UY,Hs as V6}from"./chunk-r5zy4za0.js";import{Ns as b0,Ws as E0}from"./chunk-tr6rdr6h.js";import{at as $4,bt as D$,ft as o0,gt as V4,ht as mV,kt as F0}from"./chunk-at22twxx.js";import{lt as P}from"./chunk-kgptyf7n.js";import{Jt as D}from"./chunk-j9h1sp4g.js";import{By as oV}from"./chunk-55fcmswd.js";import{AC as Z8,DE as T0,II as hw,JB as v7,KE as n7,LD as xw,SD as B9,TN as O,XJ as I$,YE as W4,ZD as f6,_B as y7,eH as T,lB as O1,mI as Nw,nE as PY,oC as ul,uH as nV,vI as h6,zB as S1}from"./chunk-qnvsqnz5.js";import{rO as yL}from"./chunk-j8fcfhr2.js";import{sO as m6,tO as S,uO as F1,wO as Y0,xO as CK,yO as EK}from"./chunk-r9w0thdk.js";var R7=S((MO)=>{Object.defineProperty(MO,"__esModule",{value:!0});MO.stringArray=MO.array=MO.func=MO.error=MO.number=MO.string=MO.boolean=void 0;function ed($){return $===!0||$===!1}MO.boolean=ed;function jO($){return typeof $==="string"||$ instanceof String}MO.string=jO;function $p($){return typeof $==="number"||$ instanceof Number}MO.number=$p;function Zp($){return $ instanceof Error}MO.error=Zp;function Jp($){return typeof $==="function"}MO.func=Jp;function NO($){return Array.isArray($)}MO.array=NO;function Yp($){return NO($)&&$.every((Z)=>jO(Z))}MO.stringArray=Yp});var HV=S((cO)=>{Object.defineProperty(cO,"__esModule",{value:!0});cO.Message=cO.NotificationType9=cO.NotificationType8=cO.NotificationType7=cO.NotificationType6=cO.NotificationType5=cO.NotificationType4=cO.NotificationType3=cO.NotificationType2=cO.NotificationType1=cO.NotificationType0=cO.NotificationType=cO.RequestType9=cO.RequestType8=cO.RequestType7=cO.RequestType6=cO.RequestType5=cO.RequestType4=cO.RequestType3=cO.RequestType2=cO.RequestType1=cO.RequestType=cO.RequestType0=cO.AbstractMessageSignature=cO.ParameterStructures=cO.ResponseError=cO.ErrorCodes=void 0;var z5=R7(),VV;(function($){$.ParseError=-32700,$.InvalidRequest=-32600,$.MethodNotFound=-32601,$.InvalidParams=-32602,$.InternalError=-32603,$.jsonrpcReservedErrorRangeStart=-32099,$.serverErrorStart=-32099,$.MessageWriteError=-32099,$.MessageReadError=-32098,$.PendingResponseRejected=-32097,$.ConnectionInactive=-32096,$.ServerNotInitialized=-32002,$.UnknownErrorCode=-32001,$.jsonrpcReservedErrorRangeEnd=-32000,$.serverErrorEnd=-32000})(VV||(cO.ErrorCodes=VV={}));class UV extends Error{constructor($,Z,J){super(Z);this.code=z5.number($)?$:VV.UnknownErrorCode,this.data=J,Object.setPrototypeOf(this,UV.prototype)}toJson(){let $={code:this.code,message:this.message};if(this.data!==void 0)$.data=this.data;return $}}cO.ResponseError=UV;class h${constructor($){this.kind=$}static is($){return $===h$.auto||$===h$.byName||$===h$.byPosition}toString(){return this.kind}}cO.ParameterStructures=h$;h$.auto=new h$("auto");h$.byPosition=new h$("byPosition");h$.byName=new h$("byName");class n1{constructor($,Z){this.method=$,this.numberOfParams=Z}get parameterStructures(){return h$.auto}}cO.AbstractMessageSignature=n1;class LO extends n1{constructor($){super($,0)}}cO.RequestType0=LO;class TO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType=TO;class RO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType1=RO;class PO extends n1{constructor($){super($,2)}}cO.RequestType2=PO;class IO extends n1{constructor($){super($,3)}}cO.RequestType3=IO;class CO extends n1{constructor($){super($,4)}}cO.RequestType4=CO;class EO extends n1{constructor($){super($,5)}}cO.RequestType5=EO;class bO extends n1{constructor($){super($,6)}}cO.RequestType6=bO;class _O extends n1{constructor($){super($,7)}}cO.RequestType7=_O;class SO extends n1{constructor($){super($,8)}}cO.RequestType8=SO;class fO extends n1{constructor($){super($,9)}}cO.RequestType9=fO;class kO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType=kO;class vO extends n1{constructor($){super($,0)}}cO.NotificationType0=vO;class yO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType1=yO;class xO extends n1{constructor($){super($,2)}}cO.NotificationType2=xO;class hO extends n1{constructor($){super($,3)}}cO.NotificationType3=hO;class gO extends n1{constructor($){super($,4)}}cO.NotificationType4=gO;class uO extends n1{constructor($){super($,5)}}cO.NotificationType5=uO;class mO extends n1{constructor($){super($,6)}}cO.NotificationType6=mO;class lO extends n1{constructor($){super($,7)}}cO.NotificationType7=lO;class dO extends n1{constructor($){super($,8)}}cO.NotificationType8=dO;class pO extends n1{constructor($){super($,9)}}cO.NotificationType9=pO;var wO;(function($){function Z(X){let Q=X;return Q&&z5.string(Q.method)&&(z5.string(Q.id)||z5.number(Q.id))}$.isRequest=Z;function J(X){let Q=X;return Q&&z5.string(Q.method)&&X.id===void 0}$.isNotification=J;function Y(X){let Q=X;return Q&&(Q.result!==void 0||!!Q.error)&&(z5.string(Q.id)||z5.number(Q.id)||Q.id===null)}$.isResponse=Y})(wO||(cO.Message=wO={}))});var zV=S((sO)=>{var nO;Object.defineProperty(sO,"__esModule",{value:!0});sO.LRUCache=sO.LinkedMap=sO.Touch=void 0;var g$;(function($){$.None=0,$.First=1,$.AsOld=$.First,$.Last=2,$.AsNew=$.Last})(g$||(sO.Touch=g$={}));class BV{constructor(){this[nO]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has($){return this._map.has($)}get($,Z=g$.None){let J=this._map.get($);if(!J)return;if(Z!==g$.None)this.touch(J,Z);return J.value}set($,Z,J=g$.None){let Y=this._map.get($);if(Y){if(Y.value=Z,J!==g$.None)this.touch(Y,J)}else{switch(Y={key:$,value:Z,next:void 0,previous:void 0},J){case g$.None:this.addItemLast(Y);break;case g$.First:this.addItemFirst(Y);break;case g$.Last:this.addItemLast(Y);break;default:this.addItemLast(Y);break}this._map.set($,Y),this._size++}return this}delete($){return!!this.remove($)}remove($){let Z=this._map.get($);if(!Z)return;return this._map.delete($),this.removeItem(Z),this._size--,Z.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error("Invalid list");let $=this._head;return this._map.delete($.key),this.removeItem($),this._size--,$.value}forEach($,Z){let J=this._state,Y=this._head;while(Y){if(Z)$.bind(Z)(Y.value,Y.key,this);else $(Y.value,Y.key,this);if(this._state!==J)throw Error("LinkedMap got modified during iteration.");Y=Y.next}}keys(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.key,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}values(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.value,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}entries(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:[Z.key,Z.value],done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}[(nO=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld($){if($>=this.size)return;if($===0){this.clear();return}let Z=this._head,J=this.size;while(Z&&J>$)this._map.delete(Z.key),Z=Z.next,J--;if(this._head=Z,this._size=J,Z)Z.previous=void 0;this._state++}addItemFirst($){if(!this._head&&!this._tail)this._tail=$;else if(!this._head)throw Error("Invalid list");else $.next=this._head,this._head.previous=$;this._head=$,this._state++}addItemLast($){if(!this._head&&!this._tail)this._head=$;else if(!this._tail)throw Error("Invalid list");else $.previous=this._tail,this._tail.next=$;this._tail=$,this._state++}removeItem($){if($===this._head&&$===this._tail)this._head=void 0,this._tail=void 0;else if($===this._head){if(!$.next)throw Error("Invalid list");$.next.previous=void 0,this._head=$.next}else if($===this._tail){if(!$.previous)throw Error("Invalid list");$.previous.next=void 0,this._tail=$.previous}else{let{next:Z,previous:J}=$;if(!Z||!J)throw Error("Invalid list");Z.previous=J,J.next=Z}$.next=void 0,$.previous=void 0,this._state++}touch($,Z){if(!this._head||!this._tail)throw Error("Invalid list");if(Z!==g$.First&&Z!==g$.Last)return;if(Z===g$.First){if($===this._head)return;let{next:J,previous:Y}=$;if($===this._tail)Y.next=void 0,this._tail=Y;else J.previous=Y,Y.next=J;$.previous=void 0,$.next=this._head,this._head.previous=$,this._head=$,this._state++}else if(Z===g$.Last){if($===this._tail)return;let{next:J,previous:Y}=$;if($===this._head)J.previous=void 0,this._head=J;else J.previous=Y,Y.next=J;$.next=void 0,$.previous=this._tail,this._tail.next=$,this._tail=$,this._state++}}toJSON(){let $=[];return this.forEach((Z,J)=>{$.push([J,Z])}),$}fromJSON($){this.clear();for(let[Z,J]of $)this.set(Z,J)}}sO.LinkedMap=BV;class oO extends BV{constructor($,Z=1){super();this._limit=$,this._ratio=Math.min(Math.max(0,Z),1)}get limit(){return this._limit}set limit($){this._limit=$,this.checkTrim()}get ratio(){return this._ratio}set ratio($){this._ratio=Math.min(Math.max(0,$),1),this.checkTrim()}get($,Z=g$.AsNew){return super.get($,Z)}peek($){return super.get($,g$.None)}set($,Z){return super.set($,Z,g$.Last),this.checkTrim(),this}checkTrim(){if(this.size>this._limit)this.trimOld(Math.round(this._limit*this._ratio))}}sO.LRUCache=oO});var $q=S((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});tO.Disposable=void 0;var aO;(function($){function Z(J){return{dispose:J}}$.create=Z})(aO||(tO.Disposable=aO={}))});var DZ=S((Zq)=>{Object.defineProperty(Zq,"__esModule",{value:!0});var FV;function AV(){if(FV===void 0)throw Error("No runtime abstraction layer installed");return FV}(function($){function Z(J){if(J===void 0)throw Error("No runtime abstraction layer provided");FV=J}$.install=Z})(AV||(AV={}));Zq.default=AV});var P7=S((Xq)=>{Object.defineProperty(Xq,"__esModule",{value:!0});Xq.Emitter=Xq.Event=void 0;var gp=DZ(),Jq;(function($){let Z={dispose(){}};$.None=function(){return Z}})(Jq||(Xq.Event=Jq={}));class Yq{add($,Z=null,J){if(!this._callbacks)this._callbacks=[],this._contexts=[];if(this._callbacks.push($),this._contexts.push(Z),Array.isArray(J))J.push({dispose:()=>this.remove($,Z)})}remove($,Z=null){if(!this._callbacks)return;let J=!1;for(let Y=0,X=this._callbacks.length;Y<X;Y++)if(this._callbacks[Y]===$)if(this._contexts[Y]===Z){this._callbacks.splice(Y,1),this._contexts.splice(Y,1);return}else J=!0;if(J)throw Error("When adding a listener with a context, you should remove it with the same context")}invoke(...$){if(!this._callbacks)return[];let Z=[],J=this._callbacks.slice(0),Y=this._contexts.slice(0);for(let X=0,Q=J.length;X<Q;X++)try{Z.push(J[X].apply(Y[X],$))}catch(G){(0,gp.default)().console.error(G)}return Z}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}}class q9{constructor($){this._options=$}get event(){if(!this._event)this._event=($,Z,J)=>{if(!this._callbacks)this._callbacks=new Yq;if(this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty())this._options.onFirstListenerAdd(this);this._callbacks.add($,Z);let Y={dispose:()=>{if(!this._callbacks)return;if(this._callbacks.remove($,Z),Y.dispose=q9._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty())this._options.onLastListenerRemove(this)}};if(Array.isArray(J))J.push(Y);return Y};return this._event}fire($){if(this._callbacks)this._callbacks.invoke.call(this._callbacks,$)}dispose(){if(this._callbacks)this._callbacks.dispose(),this._callbacks=void 0}}Xq.Emitter=q9;q9._noop=function(){}});var N9=S((Wq)=>{Object.defineProperty(Wq,"__esModule",{value:!0});Wq.CancellationTokenSource=Wq.CancellationToken=void 0;var mp=DZ(),lp=R7(),OV=P7(),j9;(function($){$.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:OV.Event.None}),$.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:OV.Event.None});function Z(J){let Y=J;return Y&&(Y===$.None||Y===$.Cancelled||lp.boolean(Y.isCancellationRequested)&&!!Y.onCancellationRequested)}$.is=Z})(j9||(Wq.CancellationToken=j9={}));var dp=Object.freeze(function($,Z){let J=(0,mp.default)().timer.setTimeout($.bind(Z),0);return{dispose(){J.dispose()}}});class qV{constructor(){this._isCancelled=!1}cancel(){if(!this._isCancelled){if(this._isCancelled=!0,this._emitter)this._emitter.fire(void 0),this.dispose()}}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){if(this._isCancelled)return dp;if(!this._emitter)this._emitter=new OV.Emitter;return this._emitter.event}dispose(){if(this._emitter)this._emitter.dispose(),this._emitter=void 0}}class Gq{get token(){if(!this._token)this._token=new qV;return this._token}cancel(){if(!this._token)this._token=j9.Cancelled;else this._token.cancel()}dispose(){if(!this._token)this._token=j9.None;else if(this._token instanceof qV)this._token.dispose()}}Wq.CancellationTokenSource=Gq});var Aq=S((zq)=>{Object.defineProperty(zq,"__esModule",{value:!0});zq.SharedArrayReceiverStrategy=zq.SharedArraySenderStrategy=void 0;var cp=N9(),bY;(function($){$.Continue=0,$.Cancelled=1})(bY||(bY={}));class Vq{constructor(){this.buffers=new Map}enableCancellation($){if($.id===null)return;let Z=new SharedArrayBuffer(4),J=new Int32Array(Z,0,1);J[0]=bY.Continue,this.buffers.set($.id,Z),$.$cancellationData=Z}async sendCancellation($,Z){let J=this.buffers.get(Z);if(J===void 0)return;let Y=new Int32Array(J,0,1);Atomics.store(Y,0,bY.Cancelled)}cleanup($){this.buffers.delete($)}dispose(){this.buffers.clear()}}zq.SharedArraySenderStrategy=Vq;class Uq{constructor($){this.data=new Int32Array($,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===bY.Cancelled}get onCancellationRequested(){throw Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class Hq{constructor($){this.token=new Uq($)}cancel(){}dispose(){}}class Bq{constructor(){this.kind="request"}createCancellationTokenSource($){let Z=$.$cancellationData;if(Z===void 0)return new cp.CancellationTokenSource;return new Hq(Z)}}zq.SharedArrayReceiverStrategy=Bq});var jV=S((qq)=>{Object.defineProperty(qq,"__esModule",{value:!0});qq.Semaphore=void 0;var np=DZ();class Oq{constructor($=1){if($<=0)throw Error("Capacity must be greater than 0");this._capacity=$,this._active=0,this._waiting=[]}lock($){return new Promise((Z,J)=>{this._waiting.push({thunk:$,resolve:Z,reject:J}),this.runNext()})}get active(){return this._active}runNext(){if(this._waiting.length===0||this._active===this._capacity)return;(0,np.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let $=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error("To many thunks active");try{let Z=$.thunk();if(Z instanceof Promise)Z.then((J)=>{this._active--,$.resolve(J),this.runNext()},(J)=>{this._active--,$.reject(J),this.runNext()});else this._active--,$.resolve(Z),this.runNext()}catch(Z){this._active--,$.reject(Z),this.runNext()}}}qq.Semaphore=Oq});var Lq=S((Dq)=>{Object.defineProperty(Dq,"__esModule",{value:!0});Dq.ReadableStreamMessageReader=Dq.AbstractMessageReader=Dq.MessageReader=void 0;var MV=DZ(),I7=R7(),NV=P7(),op=jV(),Nq;(function($){function Z(J){let Y=J;return Y&&I7.func(Y.listen)&&I7.func(Y.dispose)&&I7.func(Y.onError)&&I7.func(Y.onClose)&&I7.func(Y.onPartialMessage)}$.is=Z})(Nq||(Dq.MessageReader=Nq={}));class wV{constructor(){this.errorEmitter=new NV.Emitter,this.closeEmitter=new NV.Emitter,this.partialMessageEmitter=new NV.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError($){this.errorEmitter.fire(this.asError($))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage($){this.partialMessageEmitter.fire($)}asError($){if($ instanceof Error)return $;else return Error(`Reader received error. Reason: ${I7.string($.message)?$.message:"unknown"}`)}}Dq.AbstractMessageReader=wV;var DV;(function($){function Z(J){let Y,X,Q,G=new Map,W,K=new Map;if(J===void 0||typeof J==="string")Y=J??"utf-8";else{if(Y=J.charset??"utf-8",J.contentDecoder!==void 0)Q=J.contentDecoder,G.set(Q.name,Q);if(J.contentDecoders!==void 0)for(let V of J.contentDecoders)G.set(V.name,V);if(J.contentTypeDecoder!==void 0)W=J.contentTypeDecoder,K.set(W.name,W);if(J.contentTypeDecoders!==void 0)for(let V of J.contentTypeDecoders)K.set(V.name,V)}if(W===void 0)W=(0,MV.default)().applicationJson.decoder,K.set(W.name,W);return{charset:Y,contentDecoder:Q,contentDecoders:G,contentTypeDecoder:W,contentTypeDecoders:K}}$.fromOptions=Z})(DV||(DV={}));class Mq extends wV{constructor($,Z){super();this.readable=$,this.options=DV.fromOptions(Z),this.buffer=(0,MV.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new op.Semaphore(1)}set partialMessageTimeout($){this._partialMessageTimeout=$}get partialMessageTimeout(){return this._partialMessageTimeout}listen($){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=$;let Z=this.readable.onData((J)=>{this.onData(J)});return this.readable.onError((J)=>this.fireError(J)),this.readable.onClose(()=>this.fireClose()),Z}onData($){try{this.buffer.append($);while(!0){if(this.nextMessageLength===-1){let J=this.buffer.tryReadHeaders(!0);if(!J)return;let Y=J.get("content-length");if(!Y){this.fireError(Error(`Header must provide a Content-Length property.
3
3
  ${JSON.stringify(Object.fromEntries(J))}`));return}let X=parseInt(Y);if(isNaN(X)){this.fireError(Error(`Content-Length value must be a number. Got ${Y}`));return}this.nextMessageLength=X}let Z=this.buffer.tryReadBody(this.nextMessageLength);if(Z===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let J=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(Z):Z,Y=await this.options.contentTypeDecoder.decode(J,this.options);this.callback(Y)}).catch((J)=>{this.fireError(J)})}}catch(Z){this.fireError(Z)}}clearPartialMessageTimer(){if(this.partialMessageTimer)this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0}setPartialMessageTimer(){if(this.clearPartialMessageTimer(),this._partialMessageTimeout<=0)return;this.partialMessageTimer=(0,MV.default)().timer.setTimeout(($,Z)=>{if(this.partialMessageTimer=void 0,$===this.messageToken)this.firePartialMessage({messageToken:$,waitingTime:Z}),this.setPartialMessageTimer()},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout)}}Dq.ReadableStreamMessageReader=Mq});var _q=S((Eq)=>{Object.defineProperty(Eq,"__esModule",{value:!0});Eq.WriteableStreamMessageWriter=Eq.AbstractMessageWriter=Eq.MessageWriter=void 0;var Tq=DZ(),_Y=R7(),ap=jV(),Rq=P7(),tp="Content-Length: ",Pq=`\r
4
4
  `,Iq;(function($){function Z(J){let Y=J;return Y&&_Y.func(Y.dispose)&&_Y.func(Y.onClose)&&_Y.func(Y.onError)&&_Y.func(Y.write)}$.is=Z})(Iq||(Eq.MessageWriter=Iq={}));class TV{constructor(){this.errorEmitter=new Rq.Emitter,this.closeEmitter=new Rq.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError($,Z,J){this.errorEmitter.fire([this.asError($),Z,J])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError($){if($ instanceof Error)return $;else return Error(`Writer received error. Reason: ${_Y.string($.message)?$.message:"unknown"}`)}}Eq.AbstractMessageWriter=TV;var LV;(function($){function Z(J){if(J===void 0||typeof J==="string")return{charset:J??"utf-8",contentTypeEncoder:(0,Tq.default)().applicationJson.encoder};else return{charset:J.charset??"utf-8",contentEncoder:J.contentEncoder,contentTypeEncoder:J.contentTypeEncoder??(0,Tq.default)().applicationJson.encoder}}$.fromOptions=Z})(LV||(LV={}));class Cq extends TV{constructor($,Z){super();this.writable=$,this.options=LV.fromOptions(Z),this.errorCount=0,this.writeSemaphore=new ap.Semaphore(1),this.writable.onError((J)=>this.fireError(J)),this.writable.onClose(()=>this.fireClose())}async write($){return this.writeSemaphore.lock(async()=>{return this.options.contentTypeEncoder.encode($,this.options).then((J)=>{if(this.options.contentEncoder!==void 0)return this.options.contentEncoder.encode(J);else return J}).then((J)=>{let Y=[];return Y.push(tp,J.byteLength.toString(),Pq),Y.push(Pq),this.doWrite($,Y,J)},(J)=>{throw this.fireError(J),J})})}async doWrite($,Z,J){try{return await this.writable.write(Z.join(""),"ascii"),this.writable.write(J)}catch(Y){return this.handleError(Y,$),Promise.reject(Y)}}handleError($,Z){this.errorCount++,this.fireError($,Z,this.errorCount)}end(){this.writable.end()}}Eq.WriteableStreamMessageWriter=Cq});var vq=S((fq)=>{Object.defineProperty(fq,"__esModule",{value:!0});fq.AbstractMessageBuffer=void 0;var Zc=13,Jc=10,Yc=`\r
5
5
  `;class Sq{constructor($="utf-8"){this._encoding=$,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append($){let Z=typeof $==="string"?this.fromString($,this._encoding):$;this._chunks.push(Z),this._totalLength+=Z.byteLength}tryReadHeaders($=!1){if(this._chunks.length===0)return;let Z=0,J=0,Y=0,X=0;$:while(J<this._chunks.length){let K=this._chunks[J];Y=0;Z:while(Y<K.length){switch(K[Y]){case Zc:switch(Z){case 0:Z=1;break;case 2:Z=3;break;default:Z=0}break;case Jc:switch(Z){case 1:Z=2;break;case 3:Z=4,Y++;break $;default:Z=0}break;default:Z=0}Y++}X+=K.byteLength,J++}if(Z!==4)return;let Q=this._read(X+Y),G=new Map,W=this.toString(Q,"ascii").split(Yc);if(W.length<2)return G;for(let K=0;K<W.length-2;K++){let V=W[K],U=V.indexOf(":");if(U===-1)throw Error(`Message header must separate key and value using ':'
@@ -83,7 +83,7 @@ return `+str.trim()+`;
83
83
  `;for(let Q=0;Q<Y;++Q){let G=$.nodes[Q],W=Z+(Q===X?" ":"\u2502 ");J+=Z,J+=Q===X?"\u2514\u2500":"\u251C\u2500",J+=G.nodes.length===0?"\u2500 ":"\u252C ",J+=UR(G,W).slice(Z.length+2)}return J}HR.exports={TimeTree:VR}});var b4=S((qf0,zR)=>{var{debuglog:p00}=Y0("util"),c00=p00("avvio");zR.exports={debug:c00}});var AR=S((jf0,FR)=>{function i00(){let $={resolve:null,reject:null,promise:null};return $.promise=new Promise((Z,J)=>{$.resolve=Z,$.reject=J}),$}FR.exports={createPromise:i00}});var jR=S((Nf0,qR)=>{var{kPluginMeta:OR}=jJ();function n00($,Z){if($[OR]?.name)return $[OR].name;if(Z?.name)return Z.name;if($.name)return $.name;else return $.toString().split(`
84
84
  `).slice(0,2).map((J)=>J.trim()).join(" -- ")}qR.exports={getPluginName:n00}});var _4=S((Mf0,NR)=>{function o00($){return $!==null&&typeof $==="object"&&typeof $.then==="function"}NR.exports={isPromiseLike:o00}});var DR=S((Df0,MR)=>{var{EventEmitter:s00}=Y0("events"),{inherits:r00}=Y0("util"),{debug:_$}=b4(),{createPromise:a00}=AR(),{AVV_ERR_PLUGIN_EXEC_TIMEOUT:t00}=E4(),{getPluginName:e00}=jR(),{isPromiseLike:$10}=_4();function NJ($,Z,J,Y,X){this.queue=$,this.func=Z,this.options=J,this.isAfter=Y,this.timeout=X,this.started=!1,this.name=e00(Z,J),this.queue.pause(),this._error=null,this.loaded=!1,this._promise=null,this.startTime=null}r00(NJ,s00);NJ.prototype.exec=function($,Z){_$("exec",this.name),this.server=$;let J=this.func,Y=this.name,X=!1;this.options=typeof this.options==="function"?this.options(this.server):this.options;let Q=null,G=(K)=>{if(X){_$("loading complete",Y);return}if(this._error=K,K)_$("exec errored",Y);else _$("exec completed",Y);if(X=!0,Q)clearTimeout(Q);Z(K)};if(this.timeout>0)_$("setting up timeout",Y,this.timeout),Q=setTimeout(function(){_$("timed out",Y),Q=null;let K=new t00(Y);K.fn=J,G(K)},this.timeout);this.started=!0,this.startTime=Date.now(),this.emit("start",this.server?this.server.name:null,this.name,Date.now());let W=J(this.server,this.options,G);if($10(W))_$("exec: resolving promise",Y),W.then(()=>process.nextTick(G),(K)=>process.nextTick(G,K));else if(J.length<3)G()};NJ.prototype.loadedSoFar=function(){if(_$("loadedSoFar",this.name),this.loaded)return Promise.resolve();let $=()=>{this.server.after((J,Y)=>{if(this._error=J,this.queue.pause(),this._promise){if(J)_$("rejecting promise",this.name,J),this._promise.reject(J);else _$("resolving promise",this.name),this._promise.resolve();this._promise=null}process.nextTick(Y,J)}),this.queue.resume()},Z;if(!this._promise)if(this._promise=a00(),Z=this._promise.promise,!this.server)this.on("start",$);else $();else Z=Promise.resolve();return Z};NJ.prototype.enqueue=function($,Z){_$("enqueue",this.name,$.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.queue.push($,Z)};NJ.prototype.finish=function($,Z){_$("finish",this.name,$);let J=()=>{if(this.loaded)return;_$("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,Z($)};if($){if(this._promise)this._promise.reject($),this._promise=null;J();return}let Y=()=>{if(_$("check",this.name,this.queue.length(),this.queue.running(),this._promise),this.queue.length()===0&&this.queue.running()===0)if(this._promise){let X=()=>{_$("wrap"),queueMicrotask(Y)};this._promise.resolve(),this._promise.promise.then(X,X),this._promise=null}else J();else _$("delayed",this.name),this.queue.drain=()=>{_$("drain",this.name),this.queue.drain=Z10,queueMicrotask(Y)}};queueMicrotask(Y),this.queue.resume()};function Z10(){}MR.exports={Plugin:NJ}});var LR=S((wf0,wR)=>{var{AVV_ERR_PLUGIN_NOT_VALID:vH}=E4();function J10($){if(!($&&(typeof $==="function"||typeof $.then==="function")))if(Array.isArray($))throw new vH("array");else if($===null)throw new vH("null");else throw new vH(typeof $)}wR.exports={validatePlugin:J10}});var RR=S((Lf0,TR)=>{function Y10($){return $!==null&&typeof $==="object"&&typeof $.default==="function"}TR.exports={isBundledOrTypescriptPlugin:Y10}});var CR=S((Tf0,IR)=>{var{debug:PR}=b4(),{kThenifyDoNotWrap:yH}=jJ();function X10(){if(this.booted){PR("thenify returning undefined because we are already booted");return}if(this[yH]){this[yH]=!1;return}return PR("thenify"),($,Z)=>{return this._loadRegistered().then(()=>{return this[yH]=!0,$(this._server)},Z)}}IR.exports={thenify:X10}});var bR=S((Rf0,ER)=>{var{isPromiseLike:Q10}=_4(),{kAvvio:G10}=jJ();function W10($,Z,J){let Y;try{Y=$.apply($,Z)}catch(X){if(J)process.nextTick(J,X);return}if(Q10(Y)&&!Y[G10])Y.then(()=>process.nextTick(J),(X)=>process.nextTick(J,X));else if(J)process.nextTick(J)}ER.exports={executeWithThenable:W10}});var gR=S((Pf0,hR)=>{var S4=JR(),K10=Y0("events").EventEmitter,V10=Y0("util").inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:RX,AVV_ERR_CALLBACK_NOT_FN:MJ,AVV_ERR_ROOT_PLG_BOOTED:U10,AVV_ERR_READY_TIMEOUT:H10,AVV_ERR_ATTRIBUTE_ALREADY_DEFINED:B10}=E4(),{kAvvio:fR,kIsOnCloseHandler:kR}=jJ(),{TimeTree:z10}=BR(),{Plugin:vR}=DR(),{debug:DJ}=b4(),{validatePlugin:F10}=LR(),{isBundledOrTypescriptPlugin:A10}=RR(),{isPromiseLike:O10}=_4(),{thenify:yR}=CR(),{executeWithThenable:_R}=bR();function Q$($,Z,J){if(typeof $==="function"&&arguments.length===1)J=$,Z={},$=null;if(typeof Z==="function")J=Z,Z={};if(Z=Z||{},Z.autostart=Z.autostart!==!1,Z.timeout=Number(Z.timeout)||0,Z.expose=Z.expose||{},!new.target)return new Q$($,Z,J);if(this._server=$||this,this._opts=Z,$)this._expose();if(this._current=[],this._error=null,this._lastUsed=null,this.setMaxListeners(0),J)this.once("start",J);this.started=!1,this.booted=!1,this.pluginTree=new z10,this._readyQ=S4(this,xR,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=SR},this._closeQ=S4(this,j10,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=SR},this._doStart=null;let Y=this;this._root=new vR(S4(this,this._loadPluginNextTick,1),function(Q,G,W){Y._doStart=W,G.autostart&&Y.start()},Z,!1,0),this._trackPluginLoading(this._root),this._loadPlugin(this._root,(X)=>{DJ("root plugin ready");try{this.emit("preReady"),this._root=null}catch(Q){X=X||this._error||Q}if(X){if(this._error=X,this._readyQ.length()===0)throw X}else this.booted=!0;this._readyQ.resume()})}V10(Q$,K10);if("asyncDispose"in Symbol)Q$.prototype[Symbol.asyncDispose]=function(){return new Promise(($,Z)=>{this.close((J)=>{if(J)return Z(J);$()})})};Q$.prototype.start=function(){return this.started=!0,process.nextTick(this._doStart),this};Q$.prototype.override=function($,Z,J){return $};Q$.prototype[fR]=!0;Q$.prototype.use=function($,Z){return this._lastUsed=this._addPlugin($,Z,!1),this};Q$.prototype._loadRegistered=function(){let $=this._current[0];if(!this.started&&!this.booted)process.nextTick(()=>this._root.queue.resume());if(!$)return Promise.resolve();return $.loadedSoFar()};Object.defineProperty(Q$.prototype,"then",{get:yR});Q$.prototype._addPlugin=function($,Z,J){if(A10($))$=$.default;if(F10($),Z=Z||{},this.booted)throw new U10;let Y=this._current[0],X=this._opts.timeout;if(!Y.loaded&&Y.timeout>0){let G=Date.now()-Y.startTime;X=Y.timeout-(G+3)}let Q=new vR(S4(this,this._loadPluginNextTick,1),$,Z,J,X);if(this._trackPluginLoading(Q),Y.loaded)throw Error(Q.name,Y.name);return Y.enqueue(Q,(G)=>{G&&(this._error=G)}),Q};Q$.prototype._expose=function(){let Z=this,J=Z._server,{use:Y="use",after:X="after",ready:Q="ready",onClose:G="onClose",close:W="close"}=this._opts.expose;if(J[Y])throw new RX(Y,"use");if(J[Y]=function(K,V){return Z.use(K,V),this},J[X])throw new RX(X,"after");if(J[X]=function(K){if(typeof K!=="function")return Z._loadRegistered();return Z.after(xH(K,this)),this},J[Q])throw new RX(Q,"ready");if(J[Q]=function(K){if(K&&typeof K!=="function")throw new MJ(Q,typeof K);return Z.ready(K?xH(K,this):void 0)},J[G])throw new RX(G,"onClose");if(J[G]=function(K){if(typeof K!=="function")throw new MJ(G,typeof K);return Z.onClose(N10(K,this)),this},J[W])throw new RX(W,"close");if(J[W]=function(K){if(K&&typeof K!=="function")throw new MJ(W,typeof K);if(K)return Z.close(xH(K,this)),this;return Z.close()},J.then)throw new B10("then");Object.defineProperty(J,"then",{get:yR.bind(Z)}),J[fR]=!0};Q$.prototype.after=function($){if(!$)return this._loadRegistered();this._addPlugin(Z.bind(this),{},!0);function Z(J,Y,X){xR.call(this,$,X)}return this};Q$.prototype.onClose=function($){if(typeof $!=="function")throw new MJ("onClose",typeof $);return $[kR]=!0,this._closeQ.unshift($,(Z)=>{Z&&(this._error=Z)}),this};Q$.prototype.close=function($){let Z;if($){if(typeof $!=="function")throw new MJ("close",typeof $)}else Z=new Promise(function(J,Y){$=function(X){if(X)return Y(X);J()}});return this.ready(()=>{this._error=null,this._closeQ.push($),process.nextTick(this._closeQ.resume.bind(this._closeQ))}),Z};Q$.prototype.ready=function($){if($){if(typeof $!=="function")throw new MJ("ready",typeof $);this._readyQ.push($),queueMicrotask(this.start.bind(this));return}return new Promise((Z,J)=>{this._readyQ.push(X),this.start();let Y=this._current[0].server;function X(Q,G,W){if(Q)J(Q);else Z(Y);process.nextTick(W)}})};Q$.prototype._trackPluginLoading=function($){let Z=this._current[0]?.name||null;$.once("start",(J,Y,X)=>{let Q=this.pluginTree.start(Z||null,Y,X);$.once("loaded",(G,W,K)=>{this.pluginTree.stop(Q,K)})})};Q$.prototype.prettyPrint=function(){return this.pluginTree.prettyPrint()};Q$.prototype.toJSON=function(){return this.pluginTree.toJSON()};Q$.prototype._loadPlugin=function($,Z){let J=this;if(O10($.func)){$.func.then((G)=>{if(typeof G.default==="function")G=G.default;$.func=G,this._loadPlugin($,Z)},Z);return}let Y=J._current[0];if(J._current.unshift($),J._error&&!$.isAfter){DJ("skipping loading of plugin as instance errored and it is not an after",$.name),process.nextTick(Q);return}let X=Y?.server||J._server;if(!$.isAfter)try{X=J.override(X,$.func,$.options)}catch(G){return DJ("override errored",$.name),Q(G)}$.exec(X,Q);function Q(G){$.finish(G,(W)=>{J._current.shift(),Z(W)})}};Q$.prototype._loadPluginNextTick=function($,Z){process.nextTick(this._loadPlugin.bind(this),$,Z)};function SR(){}function xR($,Z){let J=this._server,Y=this._error;if(this._error=null,$.length===0)this._error=Y,_R($,[],Z);else if($.length===1)_R($,[Y],Z);else if(this._opts.timeout===0){let X=(Q)=>{this._error=Q,Z(this._error)};if($.length===2)$(Y,X);else $(Y,J,X)}else q10.call(this,$,Y,J,Z)}function q10($,Z,J,Y){let X=$.unwrappedName??$.name;DJ("setting up ready timeout",X,this._opts.timeout);let Q=setTimeout(()=>{DJ("timed out",X),Q=null;let W=new H10(X);W.fn=$,this._error=W,Y(W)},this._opts.timeout);if($.length===2)$(Z,G.bind(this));else $(Z,J,G.bind(this));function G(W){if(Q)clearTimeout(Q),this._error=W,Y(this._error)}}function j10($,Z){let J=this._server,Y=$[kR];if($.length===0||$.length===1){let X;if(Y)X=$(J);else X=$(this._error);if(X&&typeof X.then==="function")DJ("resolving close/onClose promise"),X.then(()=>process.nextTick(Z),(Q)=>process.nextTick(Z,Q));else process.nextTick(Z)}else if($.length===2)if(Y)$(J,Z);else $(this._error,Z);else if(Y)$(J,Z);else $(this._error,J,Z)}function N10($,Z){return J.bind(Z);function J(Y,X){let Q;if($.length===0)if(Q=$(),Q?.then)Q.then(function(){process.nextTick(X)},X);else process.nextTick(X);else if($.length===1)if(Q=$(this),Q?.then)Q.then(function(){process.nextTick(X)},X);else process.nextTick(X);else $(this,X)}}function xH($,Z){let J=Y.bind(Z);return J.unwrappedName=$.name,J;function Y(X,Q){let G;if(!$)process.nextTick(Q);else if($.length===0)if(G=$(),G?.then)G.then(function(){process.nextTick(Q,X)},Q);else process.nextTick(Q,X);else if($.length===1)if(G=$(X),G?.then)G.then(function(){process.nextTick(Q)},Q);else process.nextTick(Q);else if($.length===2)$(X,Q);else $(X,this,Q)}}hR.exports=Q$});var H$=S((If0,uR)=>{var M10={kAvvioBoot:Symbol("fastify.avvioBoot"),kChildren:Symbol("fastify.children"),kServerBindings:Symbol("fastify.serverBindings"),kBodyLimit:Symbol("fastify.bodyLimit"),kSupportedHTTPMethods:Symbol("fastify.acceptedHTTPMethods"),kRoutePrefix:Symbol("fastify.routePrefix"),kLogLevel:Symbol("fastify.logLevel"),kLogSerializers:Symbol("fastify.logSerializers"),kHooks:Symbol("fastify.hooks"),kContentTypeParser:Symbol("fastify.contentTypeParser"),kState:Symbol("fastify.state"),kOptions:Symbol("fastify.options"),kDisableRequestLogging:Symbol("fastify.disableRequestLogging"),kPluginNameChain:Symbol("fastify.pluginNameChain"),kRouteContext:Symbol("fastify.context"),kGenReqId:Symbol("fastify.genReqId"),kHttp2ServerSessions:Symbol("fastify.http2ServerSessions"),kSchemaController:Symbol("fastify.schemaController"),kSchemaHeaders:Symbol("headers-schema"),kSchemaParams:Symbol("params-schema"),kSchemaQuerystring:Symbol("querystring-schema"),kSchemaBody:Symbol("body-schema"),kSchemaResponse:Symbol("response-schema"),kSchemaErrorFormatter:Symbol("fastify.schemaErrorFormatter"),kSchemaVisited:Symbol("fastify.schemas.visited"),kRequest:Symbol("fastify.Request"),kRequestPayloadStream:Symbol("fastify.RequestPayloadStream"),kRequestAcceptVersion:Symbol("fastify.RequestAcceptVersion"),kRequestCacheValidateFns:Symbol("fastify.request.cache.validateFns"),kRequestOriginalUrl:Symbol("fastify.request.originalUrl"),kRequestSignal:Symbol("fastify.request.signal"),kHandlerTimeout:Symbol("fastify.handlerTimeout"),kTimeoutTimer:Symbol("fastify.request.timeoutTimer"),kOnAbort:Symbol("fastify.request.onAbort"),kFourOhFour:Symbol("fastify.404"),kCanSetNotFoundHandler:Symbol("fastify.canSetNotFoundHandler"),kFourOhFourLevelInstance:Symbol("fastify.404LogLevelInstance"),kFourOhFourContext:Symbol("fastify.404ContextKey"),kDefaultJsonParse:Symbol("fastify.defaultJSONParse"),kReply:Symbol("fastify.Reply"),kReplySerializer:Symbol("fastify.reply.serializer"),kReplyIsError:Symbol("fastify.reply.isError"),kReplyHeaders:Symbol("fastify.reply.headers"),kReplyTrailers:Symbol("fastify.reply.trailers"),kReplyHasStatusCode:Symbol("fastify.reply.hasStatusCode"),kReplyHijacked:Symbol("fastify.reply.hijacked"),kReplyStartTime:Symbol("fastify.reply.startTime"),kReplyNextErrorHandler:Symbol("fastify.reply.nextErrorHandler"),kReplyEndTime:Symbol("fastify.reply.endTime"),kReplyErrorHandlerCalled:Symbol("fastify.reply.errorHandlerCalled"),kReplyIsRunningOnErrorHook:Symbol("fastify.reply.isRunningOnErrorHook"),kReplySerializerDefault:Symbol("fastify.replySerializerDefault"),kReplyCacheSerializeFns:Symbol("fastify.reply.cache.serializeFns"),kTestInternals:Symbol("fastify.testInternals"),kErrorHandler:Symbol("fastify.errorHandler"),kErrorHandlerAlreadySet:Symbol("fastify.errorHandlerAlreadySet"),kChildLoggerFactory:Symbol("fastify.childLoggerFactory"),kHasBeenDecorated:Symbol("fastify.hasBeenDecorated"),kKeepAliveConnections:Symbol("fastify.keepAliveConnections"),kRouteByFastify:Symbol("fastify.routeByFastify")};uR.exports=M10});var lR=S((Cf0,f4)=>{var{format:hH}=Y0("util");function D10($){return mR({...$,name:"DeprecationWarning"})}function mR({name:$,code:Z,message:J,unlimited:Y=!1}={}){if(!$)throw Error("Warning name must not be empty");if(!Z)throw Error("Warning code must not be empty");if(!J)throw Error("Warning message must not be empty");if(typeof Y!=="boolean")throw Error("Warning opts.unlimited must be a boolean");Z=Z.toUpperCase();let X={[$]:function(G,W,K){if(Q.emitted===!0&&Q.unlimited!==!0)return;Q.emitted=!0,process.emitWarning(Q.format(G,W,K),Q.name,Q.code)}};if(Y)X={[$]:function(G,W,K){Q.emitted=!0,process.emitWarning(Q.format(G,W,K),Q.name,Q.code)}};let Q=X[$];return Q.emitted=!1,Q.message=J,Q.unlimited=Y,Q.code=Z,Q.format=function(G,W,K){let V;if(G&&W&&K)V=hH(J,G,W,K);else if(G&&W)V=hH(J,G,W);else if(G)V=hH(J,G);else V=J;return V},Q}var gH={createWarning:mR,createDeprecation:D10};f4.exports=gH;f4.exports.default=gH;f4.exports.processWarning=gH});var wJ=S((Ef0,dR)=>{var{createWarning:PX}=lR(),w10=PX({name:"FastifyWarning",code:"FSTWRN001",message:"The %s schema for %s: %s is missing. This may indicate the schema is not well specified.",unlimited:!0}),L10=PX({name:"FastifyWarning",code:"FSTWRN003",message:"The %s mixes async and callback styles that may lead to unhandled rejections. Please use only one of them.",unlimited:!0}),T10=PX({name:"FastifyWarning",code:"FSTWRN004",message:"It seems that you are overriding an errorHandler in the same scope, which can lead to subtle bugs.",unlimited:!0}),R10=PX({name:"FastifySecurity",code:"FSTSEC001",message:'You are using /%s/ Content-Type which may be vulnerable to CORS attack. Please make sure your RegExp start with "^" or include ";?" to proper detection of the essence MIME type.',unlimited:!0}),P10=PX({name:"FastifyWarning",code:"FSTDEP022",message:'The router options for %s property access is deprecated. Please use "options.routerOptions" instead for accessing router options. The router options will be removed in `fastify@6`.',unlimited:!0});dR.exports={FSTWRN001:w10,FSTWRN003:L10,FSTWRN004:T10,FSTSEC001:R10,FSTDEP022:P10}});var L$=S((bf0,k4)=>{var W0=fH(),d5={FST_ERR_NOT_FOUND:W0("FST_ERR_NOT_FOUND","Not Found",404),FST_ERR_OPTIONS_NOT_OBJ:W0("FST_ERR_OPTIONS_NOT_OBJ","Options must be an object",500,TypeError),FST_ERR_QSP_NOT_FN:W0("FST_ERR_QSP_NOT_FN","querystringParser option should be a function, instead got '%s'",500,TypeError),FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN:W0("FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN","schemaController.bucket option should be a function, instead got '%s'",500,TypeError),FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN:W0("FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN","schemaErrorFormatter option should be a non async function. Instead got '%s'.",500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ:W0("FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ","ajv.customOptions option should be an object, instead got '%s'",500,TypeError),FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR:W0("FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR","ajv.plugins option should be an array, instead got '%s'",500,TypeError),FST_ERR_VALIDATION:W0("FST_ERR_VALIDATION","%s",400),FST_ERR_LISTEN_OPTIONS_INVALID:W0("FST_ERR_LISTEN_OPTIONS_INVALID","Invalid listen options: '%s'",500,TypeError),FST_ERR_ERROR_HANDLER_NOT_FN:W0("FST_ERR_ERROR_HANDLER_NOT_FN","Error Handler must be a function",500,TypeError),FST_ERR_ERROR_HANDLER_ALREADY_SET:W0("FST_ERR_ERROR_HANDLER_ALREADY_SET","Error Handler already set in this scope. Set 'allowErrorHandlerOverride: true' to allow overriding.",500,TypeError),FST_ERR_CTP_ALREADY_PRESENT:W0("FST_ERR_CTP_ALREADY_PRESENT","Content type parser '%s' already present."),FST_ERR_CTP_INVALID_TYPE:W0("FST_ERR_CTP_INVALID_TYPE","The content type should be a string or a RegExp",500,TypeError),FST_ERR_CTP_EMPTY_TYPE:W0("FST_ERR_CTP_EMPTY_TYPE","The content type cannot be an empty string",500,TypeError),FST_ERR_CTP_INVALID_HANDLER:W0("FST_ERR_CTP_INVALID_HANDLER","The content type handler should be a function",500,TypeError),FST_ERR_CTP_INVALID_PARSE_TYPE:W0("FST_ERR_CTP_INVALID_PARSE_TYPE","The body parser can only parse your data as 'string' or 'buffer', you asked '%s' which is not supported.",500,TypeError),FST_ERR_CTP_BODY_TOO_LARGE:W0("FST_ERR_CTP_BODY_TOO_LARGE","Request body is too large",413,RangeError),FST_ERR_CTP_INVALID_MEDIA_TYPE:W0("FST_ERR_CTP_INVALID_MEDIA_TYPE","Unsupported Media Type",415),FST_ERR_CTP_INVALID_CONTENT_LENGTH:W0("FST_ERR_CTP_INVALID_CONTENT_LENGTH","Request body size did not match Content-Length",400,RangeError),FST_ERR_CTP_EMPTY_JSON_BODY:W0("FST_ERR_CTP_EMPTY_JSON_BODY","Body cannot be empty when content-type is set to 'application/json'",400),FST_ERR_CTP_INVALID_JSON_BODY:W0("FST_ERR_CTP_INVALID_JSON_BODY","Body is not valid JSON but content-type is set to 'application/json'",400),FST_ERR_CTP_INSTANCE_ALREADY_STARTED:W0("FST_ERR_CTP_INSTANCE_ALREADY_STARTED",'Cannot call "%s" when fastify instance is already started!',400),FST_ERR_DEC_ALREADY_PRESENT:W0("FST_ERR_DEC_ALREADY_PRESENT","The decorator '%s' has already been added!"),FST_ERR_DEC_DEPENDENCY_INVALID_TYPE:W0("FST_ERR_DEC_DEPENDENCY_INVALID_TYPE","The dependencies of decorator '%s' must be of type Array.",500,TypeError),FST_ERR_DEC_MISSING_DEPENDENCY:W0("FST_ERR_DEC_MISSING_DEPENDENCY","The decorator is missing dependency '%s'."),FST_ERR_DEC_AFTER_START:W0("FST_ERR_DEC_AFTER_START","The decorator '%s' has been added after start!"),FST_ERR_DEC_REFERENCE_TYPE:W0("FST_ERR_DEC_REFERENCE_TYPE","The decorator '%s' of type '%s' is a reference type. Use the { getter, setter } interface instead."),FST_ERR_DEC_UNDECLARED:W0("FST_ERR_DEC_UNDECLARED","No decorator '%s' has been declared on %s."),FST_ERR_HOOK_INVALID_TYPE:W0("FST_ERR_HOOK_INVALID_TYPE","The hook name must be a string",500,TypeError),FST_ERR_HOOK_INVALID_HANDLER:W0("FST_ERR_HOOK_INVALID_HANDLER","%s hook should be a function, instead got %s",500,TypeError),FST_ERR_HOOK_INVALID_ASYNC_HANDLER:W0("FST_ERR_HOOK_INVALID_ASYNC_HANDLER","Async function has too many arguments. Async hooks should not use the 'done' argument.",500,TypeError),FST_ERR_HOOK_NOT_SUPPORTED:W0("FST_ERR_HOOK_NOT_SUPPORTED","%s hook not supported!",500,TypeError),FST_ERR_MISSING_MIDDLEWARE:W0("FST_ERR_MISSING_MIDDLEWARE","You must register a plugin for handling middlewares, visit fastify.dev/docs/latest/Reference/Middleware/ for more info.",500),FST_ERR_HOOK_TIMEOUT:W0("FST_ERR_HOOK_TIMEOUT","A callback for '%s' hook%s timed out. You may have forgotten to call 'done' function or to resolve a Promise"),FST_ERR_LOG_INVALID_DESTINATION:W0("FST_ERR_LOG_INVALID_DESTINATION","Cannot specify both logger.stream and logger.file options"),FST_ERR_LOG_INVALID_LOGGER:W0("FST_ERR_LOG_INVALID_LOGGER","Invalid logger object provided. The logger instance should have these functions(s): '%s'.",500,TypeError),FST_ERR_LOG_INVALID_LOGGER_INSTANCE:W0("FST_ERR_LOG_INVALID_LOGGER_INSTANCE","loggerInstance only accepts a logger instance.",500,TypeError),FST_ERR_LOG_INVALID_LOGGER_CONFIG:W0("FST_ERR_LOG_INVALID_LOGGER_CONFIG","logger options only accepts a configuration object.",500,TypeError),FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED:W0("FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED","You cannot provide both logger and loggerInstance. Please provide only one.",500,TypeError),FST_ERR_REP_INVALID_PAYLOAD_TYPE:W0("FST_ERR_REP_INVALID_PAYLOAD_TYPE","Attempted to send payload of invalid type '%s'. Expected a string or Buffer.",500,TypeError),FST_ERR_REP_RESPONSE_BODY_CONSUMED:W0("FST_ERR_REP_RESPONSE_BODY_CONSUMED","Response.body is already consumed."),FST_ERR_REP_READABLE_STREAM_LOCKED:W0("FST_ERR_REP_READABLE_STREAM_LOCKED","ReadableStream was locked. You should call releaseLock() method on reader before sending."),FST_ERR_REP_ALREADY_SENT:W0("FST_ERR_REP_ALREADY_SENT",'Reply was already sent, did you forget to "return reply" in "%s" (%s)?'),FST_ERR_REP_SENT_VALUE:W0("FST_ERR_REP_SENT_VALUE","The only possible value for reply.sent is true.",500,TypeError),FST_ERR_SEND_INSIDE_ONERR:W0("FST_ERR_SEND_INSIDE_ONERR","You cannot use `send` inside the `onError` hook"),FST_ERR_SEND_UNDEFINED_ERR:W0("FST_ERR_SEND_UNDEFINED_ERR","Undefined error has occurred"),FST_ERR_BAD_STATUS_CODE:W0("FST_ERR_BAD_STATUS_CODE","Called reply with an invalid status code: %s"),FST_ERR_BAD_TRAILER_NAME:W0("FST_ERR_BAD_TRAILER_NAME","Called reply.trailer with an invalid header name: %s"),FST_ERR_BAD_TRAILER_VALUE:W0("FST_ERR_BAD_TRAILER_VALUE","Called reply.trailer('%s', fn) with an invalid type: %s. Expected a function."),FST_ERR_FAILED_ERROR_SERIALIZATION:W0("FST_ERR_FAILED_ERROR_SERIALIZATION","Failed to serialize an error. Error: %s. Original error: %s"),FST_ERR_MISSING_SERIALIZATION_FN:W0("FST_ERR_MISSING_SERIALIZATION_FN",'Missing serialization function. Key "%s"'),FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN:W0("FST_ERR_MISSING_CONTENTTYPE_SERIALIZATION_FN",'Missing serialization function. Key "%s:%s"'),FST_ERR_REQ_INVALID_VALIDATION_INVOCATION:W0("FST_ERR_REQ_INVALID_VALIDATION_INVOCATION",'Invalid validation invocation. Missing validation function for HTTP part "%s" nor schema provided.'),FST_ERR_SCH_MISSING_ID:W0("FST_ERR_SCH_MISSING_ID","Missing schema $id property"),FST_ERR_SCH_ALREADY_PRESENT:W0("FST_ERR_SCH_ALREADY_PRESENT","Schema with id '%s' already declared!"),FST_ERR_SCH_CONTENT_MISSING_SCHEMA:W0("FST_ERR_SCH_CONTENT_MISSING_SCHEMA","Schema is missing for the content type '%s'"),FST_ERR_SCH_DUPLICATE:W0("FST_ERR_SCH_DUPLICATE","Schema with '%s' already present!"),FST_ERR_SCH_VALIDATION_BUILD:W0("FST_ERR_SCH_VALIDATION_BUILD","Failed building the validation schema for %s: %s, due to error %s"),FST_ERR_SCH_SERIALIZATION_BUILD:W0("FST_ERR_SCH_SERIALIZATION_BUILD","Failed building the serialization schema for %s: %s, due to error %s"),FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:W0("FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX",'response schemas should be nested under a valid status code, e.g { 2xx: { type: "object" } }'),FST_ERR_INIT_OPTS_INVALID:W0("FST_ERR_INIT_OPTS_INVALID","Invalid initialization options: '%s'"),FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:W0("FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE","Cannot set forceCloseConnections to 'idle' as your HTTP server does not support closeIdleConnections method"),FST_ERR_DUPLICATED_ROUTE:W0("FST_ERR_DUPLICATED_ROUTE","Method '%s' already declared for route '%s'"),FST_ERR_BAD_URL:W0("FST_ERR_BAD_URL","'%s' is not a valid url component",400,URIError),FST_ERR_ASYNC_CONSTRAINT:W0("FST_ERR_ASYNC_CONSTRAINT","Unexpected error from async constraint",500),FST_ERR_INVALID_URL:W0("FST_ERR_INVALID_URL","URL must be a string. Received '%s'",400,TypeError),FST_ERR_ROUTE_OPTIONS_NOT_OBJ:W0("FST_ERR_ROUTE_OPTIONS_NOT_OBJ",'Options for "%s:%s" route must be an object',500,TypeError),FST_ERR_ROUTE_DUPLICATED_HANDLER:W0("FST_ERR_ROUTE_DUPLICATED_HANDLER",'Duplicate handler for "%s:%s" route is not allowed!',500),FST_ERR_ROUTE_HANDLER_NOT_FN:W0("FST_ERR_ROUTE_HANDLER_NOT_FN","Error Handler for %s:%s route, if defined, must be a function",500,TypeError),FST_ERR_ROUTE_MISSING_HANDLER:W0("FST_ERR_ROUTE_MISSING_HANDLER",'Missing handler function for "%s:%s" route.',500),FST_ERR_ROUTE_METHOD_INVALID:W0("FST_ERR_ROUTE_METHOD_INVALID","Provided method is invalid!",500,TypeError),FST_ERR_ROUTE_METHOD_NOT_SUPPORTED:W0("FST_ERR_ROUTE_METHOD_NOT_SUPPORTED","%s method is not supported.",500),FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED:W0("FST_ERR_ROUTE_BODY_VALIDATION_SCHEMA_NOT_SUPPORTED","Body validation schema for %s:%s route is not supported!",500),FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT:W0("FST_ERR_ROUTE_BODY_LIMIT_OPTION_NOT_INT","'bodyLimit' option must be an integer > 0. Got '%s'",500,TypeError),FST_ERR_HANDLER_TIMEOUT:W0("FST_ERR_HANDLER_TIMEOUT","Request timed out after %s ms on route '%s'",503),FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT:W0("FST_ERR_ROUTE_HANDLER_TIMEOUT_OPTION_NOT_INT","'handlerTimeout' option must be an integer > 0. Got '%s'",500,TypeError),FST_ERR_ROUTE_REWRITE_NOT_STR:W0("FST_ERR_ROUTE_REWRITE_NOT_STR",'Rewrite url for "%s" needs to be of type "string" but received "%s"',500,TypeError),FST_ERR_REOPENED_CLOSE_SERVER:W0("FST_ERR_REOPENED_CLOSE_SERVER","Fastify has already been closed and cannot be reopened"),FST_ERR_REOPENED_SERVER:W0("FST_ERR_REOPENED_SERVER","Fastify is already listening"),FST_ERR_INSTANCE_ALREADY_LISTENING:W0("FST_ERR_INSTANCE_ALREADY_LISTENING","Fastify instance is already listening. %s"),FST_ERR_PLUGIN_VERSION_MISMATCH:W0("FST_ERR_PLUGIN_VERSION_MISMATCH","fastify-plugin: %s - expected '%s' fastify version, '%s' is installed"),FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE:W0("FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE","The decorator '%s'%s is not present in %s"),FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER:W0("FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER","The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.",500,TypeError),FST_ERR_PLUGIN_CALLBACK_NOT_FN:W0("FST_ERR_PLUGIN_CALLBACK_NOT_FN","fastify-plugin: %s",500,TypeError),FST_ERR_PLUGIN_NOT_VALID:W0("FST_ERR_PLUGIN_NOT_VALID","fastify-plugin: %s"),FST_ERR_ROOT_PLG_BOOTED:W0("FST_ERR_ROOT_PLG_BOOTED","fastify-plugin: %s"),FST_ERR_PARENT_PLUGIN_BOOTED:W0("FST_ERR_PARENT_PLUGIN_BOOTED","fastify-plugin: %s"),FST_ERR_PLUGIN_TIMEOUT:W0("FST_ERR_PLUGIN_TIMEOUT","fastify-plugin: %s")};function I10($,Z){return Z.cause=$,Z}k4.exports=d5;k4.exports.appendStackTrace=I10;k4.exports.AVVIO_ERRORS_MAP={AVV_ERR_CALLBACK_NOT_FN:d5.FST_ERR_PLUGIN_CALLBACK_NOT_FN,AVV_ERR_PLUGIN_NOT_VALID:d5.FST_ERR_PLUGIN_NOT_VALID,AVV_ERR_ROOT_PLG_BOOTED:d5.FST_ERR_ROOT_PLG_BOOTED,AVV_ERR_PARENT_PLG_LOADED:d5.FST_ERR_PARENT_PLUGIN_BOOTED,AVV_ERR_READY_TIMEOUT:d5.FST_ERR_PLUGIN_TIMEOUT,AVV_ERR_PLUGIN_EXEC_TIMEOUT:d5.FST_ERR_PLUGIN_TIMEOUT}});var uZ=S((_f0,tR)=>{var C10=["onRoute","onRegister","onReady","onListen","preClose","onClose"],nR=["onTimeout","onRequest","preParsing","preValidation","preSerialization","preHandler","onSend","onResponse","onError","onRequestAbort"],E10=nR.concat(C10),{FST_ERR_HOOK_INVALID_TYPE:b10,FST_ERR_HOOK_INVALID_HANDLER:_10,FST_ERR_SEND_UNDEFINED_ERR:v4,FST_ERR_HOOK_TIMEOUT:S10,FST_ERR_HOOK_NOT_SUPPORTED:f10,AVVIO_ERRORS_MAP:pR,appendStackTrace:cR}=L$(),{kChildren:IX,kHooks:oR,kRequestPayloadStream:iR}=H$();function CX(){this.onRequest=[],this.preParsing=[],this.preValidation=[],this.preSerialization=[],this.preHandler=[],this.onResponse=[],this.onSend=[],this.onError=[],this.onRoute=[],this.onRegister=[],this.onReady=[],this.onListen=[],this.onTimeout=[],this.onRequestAbort=[],this.preClose=[]}CX.prototype=Object.create(null);CX.prototype.validate=function($,Z){if(typeof $!=="string")throw new b10;if(Array.isArray(this[$])===!1)throw new f10($);if(typeof Z!=="function")throw new _10($,Object.prototype.toString.call(Z))};CX.prototype.add=function($,Z){this.validate($,Z),this[$].push(Z)};function k10($){let Z=new CX;return Z.onRequest=$.onRequest.slice(),Z.preParsing=$.preParsing.slice(),Z.preValidation=$.preValidation.slice(),Z.preSerialization=$.preSerialization.slice(),Z.preHandler=$.preHandler.slice(),Z.onSend=$.onSend.slice(),Z.onResponse=$.onResponse.slice(),Z.onError=$.onError.slice(),Z.onRoute=$.onRoute.slice(),Z.onRegister=$.onRegister.slice(),Z.onTimeout=$.onTimeout.slice(),Z.onRequestAbort=$.onRequestAbort.slice(),Z.onReady=[],Z.onListen=[],Z.preClose=[],Z}function sR($,Z,J,Y){let X=J[oR][$],Q=0,G=0;K();function W(U){let H=X[Q-1]?.name,B=H?` "${H}"`:"";if(U){if(U.code==="AVV_ERR_READY_TIMEOUT")U=cR(U,new S10($,B));else U=pR[U.code]!=null?cR(U,new pR[U.code](U.message)):U;Y(U);return}Y()}function K(U){if(U){W(U);return}if(Q===X.length&&G===J[IX].length){if(Q===0&&G===0)W();else Z(function(B,z){W(B),z(B)});return}if(Q===X.length&&G<J[IX].length){let H=J[IX][G++];sR($,Z,H,K);return}Z(V(X[Q++],J)),K()}function V(U,H){return function(B,z){if(B){z(B);return}if(U.length===1){try{U.call(H,z)}catch(F){z(F)}return}try{let F=U.call(H);if(F&&typeof F.then==="function"){F.then(z,z);return}}catch(F){B=F}z(B)}}}function rR($){let Z=$[oR].onListen,J=Z.length,Y=0,X=0;Q();function Q(W){if(W&&$.log.error(W),Y===J){while(X<$[IX].length){let K=$[IX][X++];rR(K)}return}G(Z[Y++],$,Q)}async function G(W,K,V){if(W.length===1){try{W.call(K,V)}catch(U){V(U)}return}try{let U=W.call(K);if(U&&typeof U.then==="function"){U.then(V,V);return}V()}catch(U){V(U)}}}function LJ($){return function(J,Y,X,Q){let G=0;function W(U){if(U||G===J.length){Q(U,Y,X);return}let H;try{H=$(J[G++],Y,X,W)}catch(B){Q(B,Y,X);return}if(H&&typeof H.then==="function")H.then(K,V)}function K(){W()}function V(U){if(!U)U=new v4;Q(U,Y,X)}W()}}function v10($,Z,J,Y){return $(Z,J,Y)}var y10=LJ(v10),x10=LJ(EX),h10=LJ(EX),g10=LJ(EX),u10=LJ(EX);function aR($,Z,J,Y,X){let Q=0;function G(V,U){if(V){X(V,Z,J,Y);return}if(U!==void 0)Y=U;if(Q===$.length){X(null,Z,J,Y);return}let H;try{H=$[Q++](Z,J,Y,G)}catch(B){X(B,Z,J);return}if(H&&typeof H.then==="function")H.then(W,K)}function W(V){G(null,V)}function K(V){if(!V)V=new v4;X(V,Z,J,Y)}G()}var m10=aR;function l10($,Z,J,Y){let X=0;function Q(K,V){if(J.sent)return;if(V!==void 0)Z[iR]=V;if(K||X===$.length){Y(K,Z,J);return}let U;try{U=$[X++](Z,J,Z[iR],Q)}catch(H){Y(H,Z,J);return}if(U&&typeof U.then==="function")U.then(G,W)}function G(K){Q(null,K)}function W(K){if(!K)K=new v4;Y(K,Z,J)}Q()}function d10($,Z,J){let Y=0;function X(W){if(W||Y===$.length){J(W,Z);return}let K;try{K=$[Y++](Z,X)}catch(V){J(V,Z);return}if(K&&typeof K.then==="function")K.then(Q,G)}function Q(){X()}function G(W){if(!W)W=new v4;J(W,Z)}X()}function EX($,Z,J,Y){if(J.sent===!0)return;return $(Z,J,Y)}tR.exports={Hooks:CX,buildHooks:k10,hookRunnerGenerator:LJ,preParsingHookRunner:l10,onResponseHookRunner:y10,onSendHookRunner:aR,preSerializationHookRunner:m10,onRequestAbortHookRunner:d10,hookIterator:EX,hookRunnerApplication:sR,onListenHookRunner:rR,preHandlerHookRunner:h10,preValidationHookRunner:x10,onRequestHookRunner:u10,onTimeoutHookRunner:g10,lifecycleHooks:nR,supportedHooks:E10}});var $P=S((Sf0,eR)=>{eR.exports=function(){return{[Symbol.iterator]:function*(){},add(){},delete(){},has(){return!0}}}});var uH=S((ff0,JP)=>{var{kTestInternals:p10}=H$();function ZP(){let $,Z;return{promise:new Promise((Y,X)=>{$=Y,Z=X}),resolve:$,reject:Z}}JP.exports={withResolvers:typeof Promise.withResolvers==="function"?Promise.withResolvers.bind(Promise):ZP,[p10]:{withResolvers:ZP}}});var zP=S((Q$0,BP)=>{var c10=Y0("http"),i10=Y0("https"),YP=Y0("http2"),n10=Y0("dns"),o10=Y0("os"),{kState:G$,kOptions:s10,kServerBindings:r10,kHttp2ServerSessions:p5}=H$(),{FSTWRN003:a10}=wJ(),{onListenHookRunner:y4}=uZ(),{FST_ERR_REOPENED_CLOSE_SERVER:QP,FST_ERR_REOPENED_SERVER:GP,FST_ERR_LISTEN_OPTIONS_INVALID:t10,FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE:e10}=L$(),$$0=$P(),WP=uH();Q$0.createServer=Z$0;function KP($){return`Server listening at ${$}`}function Z$0($,Z){let J=UP($,Z);function Y(V={port:0,host:"localhost"},U=void 0){if(typeof U==="function"){if(U.constructor.name==="AsyncFunction")a10("listen method");V.cb=U}if(V.signal){if(typeof V.signal.on!=="function"&&typeof V.signal.addEventListener!=="function")throw new t10("Invalid options.signal");if(this[G$].aborted=V.signal.aborted,this[G$].aborted)return this.close();else{let B=()=>{this[G$].aborted=!0,this.close()};V.signal.addEventListener("abort",B,{once:!0})}}let H;if(V.path==null)H=V.host??"localhost";else H=V.host;if(!Object.hasOwn(V,"host")||V.host==null)V.host=H;if(H==="localhost")V.cb=(B,z)=>{if(B){U(B,z);return}XP.call(this,J,Z,$,V,()=>{this[G$].listening=!0,U(null,z),y4(this)})};else V.cb=(B,z)=>{if(B){U(B,z);return}this[G$].listening=!0,U(null,z),y4(this)};if(U===void 0)return J$0.call(this,J,V).then((z)=>{let{promise:F,resolve:A}=WP.withResolvers();if(H==="localhost")XP.call(this,J,Z,$,V,()=>{this[G$].listening=!0,A(z),y4(this)});else A(z),y4(this);return F});this.ready(VP.call(this,J,V))}let X=typeof J.closeAllConnections==="function",Q=typeof J.closeIdleConnections==="function",G=typeof J.closeHttp2Sessions==="function",W=$.forceCloseConnections;if(W==="idle"&&!Q)throw new e10;else if(typeof W!=="boolean")W=Q?"idle":!1;let K=!X&&W===!0?new Set:$$0();return{server:J,listen:Y,forceCloseConnections:W,serverHasCloseAllConnections:X,serverHasCloseHttp2Sessions:G,keepAliveConnections:K}}function XP($,Z,J,Y,X){this[G$].listening=!1,n10.lookup(Y.host,{all:!0},(Q,G)=>{if(Q||this[G$].aborted){X();return}let W=$.listening&&J.serverFactory,K=0,V=0;if(!W){let H=$.address();for(let B of G)if(B.address!==H.address){K++;let z=Object.assign({},Y,{host:B.address,port:H.port,cb:(j)=>{if(V++,!j)this[r10].push(F);if(V===K)X()}}),F=UP(J,Z),A=()=>{if(F.close(()=>{}),typeof F.closeAllConnections==="function"&&J.forceCloseConnections===!0)F.closeAllConnections();if(typeof F.closeHttp2Sessions==="function")F.closeHttp2Sessions()};F.on("upgrade",$.emit.bind($,"upgrade")),$.on("unref",A),$.on("close",A),$.on("error",A),this[G$].listening=!1,VP.call(this,F,z)()}}if(K===0){X();return}let U=$.unref;$.unref=function(){U.call($),$.emit("unref")}})}function VP($,Z){let J=(Y)=>{if($.removeListener("error",J),$.removeListener("listening",J),!Y){let X=HP.call(this,$,Z.listenTextResolver||KP);Z.cb(null,X)}else this[G$].listening=!1,Z.cb(Y,null)};return(Y)=>{if(Y!=null)return Z.cb(Y);if(this[G$].listening&&this[G$].closing)return Z.cb(new QP,null);if(this[G$].listening)return Z.cb(new GP,null);if($.once("error",J),!this[G$].closing)$.once("listening",J),$.listen(Z),this[G$].listening=!0}}function J$0($,Z){if(this[G$].listening&&this[G$].closing)return Promise.reject(new QP);if(this[G$].listening)return Promise.reject(new GP);return this.ready().then(()=>{if(this[G$].aborted)return;let{promise:J,resolve:Y,reject:X}=WP.withResolvers(),Q=(K)=>{W(),this[G$].listening=!1,X(K)},G=()=>{W(),this[G$].listening=!0,Y(HP.call(this,$,Z.listenTextResolver||KP))};function W(){$.removeListener("error",Q),$.removeListener("listening",G)}return $.once("error",Q),$.once("listening",G),$.listen(Z),J})}function UP($,Z){if($.serverFactory)return $.serverFactory(Z,$);let J=$.https===!0?{}:$.https;if($.http2){let X=typeof J==="object"?YP.createSecureServer(J,Z):YP.createServer($.http,Z);if(X.on("session",(Q)=>Q.setTimeout($.http2SessionTimeout,()=>{Q.close()})),$.forceCloseConnections===!0)X.closeHttp2Sessions=X$0(X);return X.setTimeout($.connectionTimeout),X}let Y=J?i10.createServer(J,Z):c10.createServer($.http,Z);if(Y.keepAliveTimeout=$.keepAliveTimeout,Y.requestTimeout=$.requestTimeout,Y.setTimeout($.connectionTimeout),$.maxRequestsPerSocket>0)Y.maxRequestsPerSocket=$.maxRequestsPerSocket;return Y}function Y$0($){if($.address==="0.0.0.0")return Object.values(o10.networkInterfaces()).flatMap((Z)=>{return Z.filter((J)=>J.family==="IPv4")}).sort((Z)=>{return Z.internal?-1:1}).map((Z)=>{return Z.address});return[$.address]}function HP($,Z){let J;if(typeof $.address()!=="string"){if($.address().address.indexOf(":")===-1)J=Y$0($.address()).map((X)=>X+":"+$.address().port);else J=["["+$.address().address+"]:"+$.address().port];J=J.map((X)=>"http"+(this[s10].https?"s":"")+"://"+X)}else J=[$.address()];for(let X of J)this.log.info(Z(X));return J[0]}function X$0($){return $[p5]=new Set,$.on("session",function(Z){Z.once("connect",function(){$[p5].add(Z)}),Z.once("close",function(){$[p5].delete(Z)}),Z.once("frameError",function(J,Y,X){if(X===0)$[p5].delete(Z)}),Z.once("goaway",function(){$[p5].delete(Z)})}),function(){if($[p5].size===0)return;for(let J of $[p5])J.close()}}});var lH=S((kf0,qP)=>{var mH=/(?:^|;)\s*([\w!#$%&'*+.^`|~-]+)=([^;]*)/gm,FP=/^[\w!#$%&'*+.^`|~-]+$/,AP=/^[\w!#$%&'*+.^`|~-]+\s*$/;class OP{#$=!1;#Z=!0;#J="";#Y="";#X=new Map;#Q;constructor($){if($==null||$===""||$==="undefined")return;let Z=$.indexOf(";");if(Z===-1){if(Z=$.indexOf("/"),Z===-1)return;let W=$.slice(0,Z).trimStart().toLowerCase(),K=$.slice(Z+1).trimEnd().toLowerCase();if(FP.test(W)===!0&&AP.test(K)===!0)this.#$=!0,this.#Z=!1,this.#J=W,this.#Y=K;return}let J=$.slice(0,Z).toLowerCase(),Y=$.slice(Z+1).trim();if(Z=J.indexOf("/"),Z===-1)return;let X=J.slice(0,Z).trimStart(),Q=J.slice(Z+1).trimEnd();if(FP.test(X)===!1||AP.test(Q)===!1)return;this.#J=X,this.#Y=Q,this.#$=!0,this.#Z=!1;let G=mH.exec(Y);while(G){let W=G[1],K=G[2];if(K[0]==='"'){if(K.at(-1)!=='"'){this.#X.set(W,"invalid quoted string"),G=mH.exec(Y);continue}this.#X.set(W,K.slice(1,K.length-1))}else this.#X.set(W,K);G=mH.exec(Y)}}get[Symbol.toStringTag](){return"ContentType"}get isEmpty(){return this.#Z}get isValid(){return this.#$}get mediaType(){return`${this.#J}/${this.#Y}`}get type(){return this.#J}get subtype(){return this.#Y}get parameters(){return this.#X}toString(){if(this.#Q)return this.#Q;let $=[];for(let[J,Y]of this.#X.entries())$.push(`${J}="${Y}"`);let Z=[this.#J,"/",this.#Y];if($.length>0)Z.push("; "),Z.push($.join("; "));return this.#Q=Z.join(""),this.#Q}}qP.exports=OP});var x4=S((vf0,jP)=>{var{kReplyHasStatusCode:W$0}=H$();function K$0($,Z){if(!$[W$0]||$.statusCode===200){let J=Z&&(Z.statusCode||Z.status);$.code(J>=400?J:500)}}jP.exports={setErrorStatusCode:K$0}});var dH=S((yf0,MP)=>{var{kReplyIsError:NP,kReplyHijacked:V$0}=H$(),{setErrorStatusCode:U$0}=x4(),H$0=Y0("diagnostics_channel"),bX=H$0.tracingChannel("fastify.request.handler");function B$0($,Z,J){if(J)J.async=!0;$.then(function(Y){if(Z[V$0]===!0)return;if(J)bX.asyncStart.publish(J);try{if(Y!==void 0||Z.sent===!1&&Z.raw.headersSent===!1&&Z.request.raw.aborted===!1&&Z.request.socket&&!Z.request.socket.destroyed)try{Z.send(Y)}catch(X){Z[NP]=!0,Z.send(X)}}finally{if(J)bX.asyncEnd.publish(J)}},function(Y){if(J)J.error=Y,U$0(Z,Y),bX.error.publish(J),bX.asyncStart.publish(J);try{if(Z.sent===!0){Z.log.error({err:Y},"Promise errored, but reply.sent = true was set");return}Z[NP]=!0,Z.send(Y)}catch(X){Z.send(X)}finally{if(J)bX.asyncEnd.publish(J)}})}MP.exports=B$0});var iH=S((xf0,wP)=>{var{kSchemaHeaders:u4,kSchemaParams:pH,kSchemaQuerystring:cH,kSchemaBody:c5,kSchemaResponse:DP}=H$(),z$0=/^[1-5](?:\d{2}|xx)$|^default$/,{FST_ERR_SCH_RESPONSE_SCHEMA_NOT_NESTED_2XX:F$0}=L$(),{FSTWRN001:h4}=wJ();function A$0($,Z){if(!$.schema||!$.schema.response)return;let{method:J,url:Y}=$.config||{};$[DP]=Object.keys($.schema.response).reduce(function(X,Q){let G=$.schema.response[Q];if(Q=Q.toLowerCase(),!z$0.test(Q))throw new F$0;if(G.content){let W={};for(let K of Object.keys(G.content)){let V=G.content[K].schema;W[K]=Z({schema:V,url:Y,method:J,httpStatus:Q,contentType:K})}X[Q]=W}else X[Q]=Z({schema:G,url:Y,method:J,httpStatus:Q});return X},{})}function O$0($,Z,J){let{schema:Y}=$;if(!Y)return;let{method:X,url:Q}=$.config||{},G=Y.headers;if(G&&(J||Object.getPrototypeOf(G)!==Object.prototype))$[u4]=Z({schema:G,method:X,url:Q,httpPart:"headers"});else if(G){let W={};if(Object.keys(G).forEach((K)=>{W[K]=G[K]}),W.required instanceof Array)W.required=W.required.map((K)=>K.toLowerCase());if(G.properties)W.properties={},Object.keys(G.properties).forEach((K)=>{W.properties[K.toLowerCase()]=G.properties[K]});$[u4]=Z({schema:W,method:X,url:Q,httpPart:"headers"})}else if(Object.hasOwn(Y,"headers"))h4("headers",X,Q);if(Y.body){let W=Y.body.content;if(W){let K={};for(let V of Object.keys(W)){let U=W[V].schema;K[V]=Z({schema:U,method:X,url:Q,httpPart:"body",contentType:V})}$[c5]=K}else $[c5]=Z({schema:Y.body,method:X,url:Q,httpPart:"body"})}else if(Object.hasOwn(Y,"body"))h4("body",X,Q);if(Y.querystring)$[cH]=Z({schema:Y.querystring,method:X,url:Q,httpPart:"querystring"});else if(Object.hasOwn(Y,"querystring"))h4("querystring",X,Q);if(Y.params)$[pH]=Z({schema:Y.params,method:X,url:Q,httpPart:"params"});else if(Object.hasOwn(Y,"params"))h4("params",X,Q)}function g4($,Z,J){let Y=Z[J]===void 0,X;try{X=$?.(Y?null:Z[J])}catch(G){return G.statusCode=500,G}if(X&&typeof X.then==="function")return X.then((G)=>{return Q(G)}).catch((G)=>{return G});return Q(X);function Q(G){if(G===!1)return $.errors;if(G&&G.error)return G.error;if(G&&G.value)Z[J]=G.value;return!1}}function m4($,Z,J){let Y=J===void 0;if(Y||!J.skipParams){let Q=g4($[pH],Z,"params");if(Q)if(typeof Q.then!=="function")return mZ(Q,"params",$.schemaErrorFormatter);else return q$0(Q,$,Z)}if(Y||!J.skipBody){let Q=null;if(typeof $[c5]==="function")Q=$[c5];else if($[c5]){let W=D$0(Z.headers["content-type"]),K=$[c5][W];if(K)Q=K}let G=g4(Q,Z,"body");if(G)if(typeof G.then!=="function")return mZ(G,"body",$.schemaErrorFormatter);else return j$0(G,$,Z)}if(Y||!J.skipQuery){let Q=g4($[cH],Z,"query");if(Q)if(typeof Q.then!=="function")return mZ(Q,"querystring",$.schemaErrorFormatter);else return N$0(Q,$,Z)}let X=g4($[u4],Z,"headers");if(X)if(typeof X.then!=="function")return mZ(X,"headers",$.schemaErrorFormatter);else return M$0(X,$,Z);return!1}function q$0($,Z,J){return $.then((Y)=>{if(Y)return mZ(Y,"params",Z.schemaErrorFormatter);return m4(Z,J,{skipParams:!0})})}function j$0($,Z,J){return $.then((Y)=>{if(Y)return mZ(Y,"body",Z.schemaErrorFormatter);return m4(Z,J,{skipParams:!0,skipBody:!0})})}function N$0($,Z,J){return $.then((Y)=>{if(Y)return mZ(Y,"querystring",Z.schemaErrorFormatter);return m4(Z,J,{skipParams:!0,skipBody:!0,skipQuery:!0})})}function M$0($,Z,J){return $.then((Y)=>{if(Y)return mZ(Y,"headers",Z.schemaErrorFormatter);return!1})}function mZ($,Z,J){if($ instanceof Error)return $.statusCode=$.statusCode||400,$.code=$.code||"FST_ERR_VALIDATION",$.validationContext=$.validationContext||Z,$;let Y=J($,Z);return Y.statusCode=Y.statusCode||400,Y.code=Y.code||"FST_ERR_VALIDATION",Y.validation=$,Y.validationContext=Z,Y}function D$0($){if(!$)return"";return $.trimStart().split(/[ ;]/,1)[0].trim().toLowerCase()}wP.exports={symbols:{bodySchema:c5,querystringSchema:cH,responseSchema:DP,paramsSchema:pH,headersSchema:u4},compileSchemasForValidation:O$0,compileSchemasForSerialization:A$0,validate:m4}});var rH=S((hf0,sH)=>{var w$0=Y0("diagnostics_channel"),L$0=lH(),T$0=dH(),{validate:R$0}=iH(),{preValidationHookRunner:P$0,preHandlerHookRunner:I$0}=uZ(),{FST_ERR_CTP_INVALID_MEDIA_TYPE:C$0}=L$(),{setErrorStatusCode:LP}=x4(),{kReplyIsError:SX,kRouteContext:R6,kFourOhFourContext:E$0,kSupportedHTTPMethods:TP}=H$(),_X=w$0.tracingChannel("fastify.request.handler");function b$0($,Z,J){if(J.sent===!0)return;if($!=null){J[SX]=!0,J.send($);return}let Y=Z.method;if(this[TP].bodyless.has(Y)){TJ(Z,J);return}if(this[TP].bodywith.has(Y)){let X=Z.headers,Q=X["content-type"];if(Q===void 0){let W=X["content-length"];if(X["transfer-encoding"]===void 0&&(W===void 0||W==="0")){TJ(Z,J);return}Z[R6].contentTypeParser.run("",TJ,Z,J);return}let G=new L$0(Q);if(G.isValid===!1){J[SX]=!0,J.status(415).send(new C$0);return}Z[R6].contentTypeParser.run(G.toString(),TJ,Z,J);return}TJ(Z,J)}function TJ($,Z){try{if($[R6].preValidation!==null)P$0($[R6].preValidation,$,Z,nH);else nH(null,$,Z)}catch(J){nH(J,$,Z)}}function nH($,Z,J){if(J.sent===!0)return;if($!=null){J[SX]=!0,J.send($);return}let Y=R$0(J[R6],Z);if(Y&&typeof Y.then==="function"||!1){let Q=RP.bind(null,Z,J);Y.then(Q,Q)}else RP(Z,J,Y)}function RP($,Z,J){if(J){if(Z[R6].attachValidation===!1){Z.send(J);return}Z.request.validationError=J}if($[R6].preHandler!==null)I$0($[R6].preHandler,$,Z,oH);else oH(null,$,Z)}function oH($,Z,J){if(J.sent)return;let Y=Z[R6];if(!_X.hasSubscribers||Y[E$0]===null)PP($,Z,J);else{let X={request:Z,reply:J,async:!1,route:{url:Y.config.url,method:Y.config.method}};_X.start.runStores(X,PP,void 0,$,Z,J,X)}}function PP($,Z,J,Y){let X=Z[R6];try{if($!=null){if(J[SX]=!0,Y)Y.error=$,LP(J,$),_X.error.publish(Y);J.send($);return}let Q;try{Q=X.handler(Z,J)}catch(G){if(Y)Y.error=G,LP(J,G),_X.error.publish(Y);J[SX]=!0,J.send(G);return}if(Q!==void 0)if(Q!==null&&typeof Q.then==="function")T$0(Q,J,Y);else J.send(Q)}finally{if(Y)_X.end.publish(Y)}}sH.exports=b$0;sH.exports[Symbol.for("internals")]={handler:TJ,preHandlerCallback:oH}});var CP=S((gf0,IP)=>{function RJ(){}var _$0={fatal:RJ,error:RJ,warn:RJ,info:RJ,debug:RJ,trace:RJ};Object.defineProperty(IP,"exports",{get(){return Object.create(_$0)}})});var tH=S((uf0,_P)=>{var fX=($)=>{return $&&typeof $.message==="string"},aH=($)=>{if(!$)return;let Z=$.cause;if(typeof Z==="function"){let J=$.cause();return fX(J)?J:void 0}else return fX(Z)?Z:void 0},EP=($,Z)=>{if(!fX($))return"";let J=$.stack||"";if(Z.has($))return J+`
85
85
  causes have become circular...`;let Y=aH($);if(Y)return Z.add($),J+`
86
- caused by: `+EP(Y,Z);else return J},S$0=($)=>EP($,new Set),bP=($,Z,J)=>{if(!fX($))return"";let Y=J?"":$.message||"";if(Z.has($))return Y+": ...";let X=aH($);if(X){Z.add($);let Q=typeof $.cause==="function";return Y+(Q?"":": ")+bP(X,Z,Q)}else return Y},f$0=($)=>bP($,new Set);_P.exports={isErrorLike:fX,getErrorCause:aH,stackWithCauses:S$0,messageWithCauses:f$0}});var eH=S((mf0,fP)=>{var k$0=Symbol("circular-ref-tag"),l4=Symbol("pino-raw-err-ref"),SP=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[l4]},set:function($){this[l4]=$}}});Object.defineProperty(SP,l4,{writable:!0,value:{}});fP.exports={pinoErrProto:SP,pinoErrorSymbols:{seen:k$0,rawSymbol:l4}}});var yP=S((lf0,vP)=>{vP.exports=ZB;var{messageWithCauses:v$0,stackWithCauses:y$0,isErrorLike:kP}=tH(),{pinoErrProto:x$0,pinoErrorSymbols:h$0}=eH(),{seen:$B}=h$0,{toString:g$0}=Object.prototype;function ZB($){if(!kP($))return $;$[$B]=void 0;let Z=Object.create(x$0);if(Z.type=g$0.call($.constructor)==="[object Function]"?$.constructor.name:$.name,Z.message=v$0($),Z.stack=y$0($),Array.isArray($.errors))Z.aggregateErrors=$.errors.map((J)=>ZB(J));for(let J in $)if(Z[J]===void 0){let Y=$[J];if(kP(Y)){if(J!=="cause"&&!Object.prototype.hasOwnProperty.call(Y,$B))Z[J]=ZB(Y)}else Z[J]=Y}return delete $[$B],Z.raw=$,Z}});var hP=S((df0,xP)=>{xP.exports=p4;var{isErrorLike:JB}=tH(),{pinoErrProto:u$0,pinoErrorSymbols:m$0}=eH(),{seen:d4}=m$0,{toString:l$0}=Object.prototype;function p4($){if(!JB($))return $;$[d4]=void 0;let Z=Object.create(u$0);if(Z.type=l$0.call($.constructor)==="[object Function]"?$.constructor.name:$.name,Z.message=$.message,Z.stack=$.stack,Array.isArray($.errors))Z.aggregateErrors=$.errors.map((J)=>p4(J));if(JB($.cause)&&!Object.prototype.hasOwnProperty.call($.cause,d4))Z.cause=p4($.cause);for(let J in $)if(Z[J]===void 0){let Y=$[J];if(JB(Y)){if(!Object.prototype.hasOwnProperty.call(Y,d4))Z[J]=p4(Y)}else Z[J]=Y}return delete $[d4],Z.raw=$,Z}});var lP=S((pf0,mP)=>{mP.exports={mapHttpRequest:d$0,reqSerializer:uP};var YB=Symbol("pino-raw-req-ref"),gP=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[YB]},set:function($){this[YB]=$}}});Object.defineProperty(gP,YB,{writable:!0,value:{}});function uP($){let Z=$.info||$.socket,J=Object.create(gP);if(J.id=typeof $.id==="function"?$.id():$.id||($.info?$.info.id:void 0),J.method=$.method,$.originalUrl)J.url=$.originalUrl;else{let Y=$.path;J.url=typeof Y==="string"?Y:$.url?$.url.path||$.url:void 0}if($.query)J.query=$.query;if($.params)J.params=$.params;return J.headers=$.headers,J.remoteAddress=Z&&Z.remoteAddress,J.remotePort=Z&&Z.remotePort,J.raw=$.raw||$,J}function d$0($){return{req:uP($)}}});var iP=S((cf0,cP)=>{cP.exports={mapHttpResponse:p$0,resSerializer:pP};var XB=Symbol("pino-raw-res-ref"),dP=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[XB]},set:function($){this[XB]=$}}});Object.defineProperty(dP,XB,{writable:!0,value:{}});function pP($){let Z=Object.create(dP);return Z.statusCode=$.headersSent?$.statusCode:null,Z.headers=$.getHeaders?$.getHeaders():$._headers,Z.raw=$,Z}function p$0($){return{res:pP($)}}});var GB=S((if0,nP)=>{var QB=yP(),c$0=hP(),c4=lP(),i4=iP();nP.exports={err:QB,errWithCause:c$0,mapHttpRequest:c4.mapHttpRequest,mapHttpResponse:i4.mapHttpResponse,req:c4.reqSerializer,res:i4.resSerializer,wrapErrorSerializer:function(Z){if(Z===QB)return Z;return function(Y){return Z(QB(Y))}},wrapRequestSerializer:function(Z){if(Z===c4.reqSerializer)return Z;return function(Y){return Z(c4.reqSerializer(Y))}},wrapResponseSerializer:function(Z){if(Z===i4.resSerializer)return Z;return function(Y){return Z(i4.resSerializer(Y))}}}});var WB=S((nf0,oP)=>{function i$0($,Z){return Z}oP.exports=function(){let Z=Error.prepareStackTrace;Error.prepareStackTrace=i$0;let J=Error().stack;if(Error.prepareStackTrace=Z,!Array.isArray(J))return;let Y=J.slice(2),X=[];for(let Q of Y){if(!Q)continue;X.push(Q.getFileName())}return X}});var $I=S((of0,eP)=>{function KB($){if($===null||typeof $!=="object")return $;if($ instanceof Date)return new Date($.getTime());if($ instanceof Array){let Z=[];for(let J=0;J<$.length;J++)Z[J]=KB($[J]);return Z}if(typeof $==="object"){let Z=Object.create(Object.getPrototypeOf($));for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))Z[J]=KB($[J]);return Z}return $}function sP($){let Z=[],J="",Y=!1,X=!1,Q="";for(let G=0;G<$.length;G++){let W=$[G];if(!Y&&W==="."){if(J)Z.push(J),J=""}else if(W==="["){if(J)Z.push(J),J="";Y=!0}else if(W==="]"&&Y)Z.push(J),J="",Y=!1,X=!1;else if((W==='"'||W==="'")&&Y)if(!X)X=!0,Q=W;else if(W===Q)X=!1,Q="";else J+=W;else J+=W}if(J)Z.push(J);return Z}function rP($,Z,J){let Y=$;for(let Q=0;Q<Z.length-1;Q++){let G=Z[Q];if(typeof Y!=="object"||Y===null||!(G in Y))return!1;if(typeof Y[G]!=="object"||Y[G]===null)return!1;Y=Y[G]}let X=Z[Z.length-1];if(X==="*"){if(Array.isArray(Y))for(let Q=0;Q<Y.length;Q++)Y[Q]=J;else if(typeof Y==="object"&&Y!==null){for(let Q in Y)if(Object.prototype.hasOwnProperty.call(Y,Q))Y[Q]=J}}else if(typeof Y==="object"&&Y!==null&&X in Y&&Object.prototype.hasOwnProperty.call(Y,X))Y[X]=J;return!0}function aP($,Z){let J=$;for(let X=0;X<Z.length-1;X++){let Q=Z[X];if(typeof J!=="object"||J===null||!(Q in J))return!1;if(typeof J[Q]!=="object"||J[Q]===null)return!1;J=J[Q]}let Y=Z[Z.length-1];if(Y==="*"){if(Array.isArray(J))for(let X=0;X<J.length;X++)J[X]=void 0;else if(typeof J==="object"&&J!==null){for(let X in J)if(Object.prototype.hasOwnProperty.call(J,X))delete J[X]}}else if(typeof J==="object"&&J!==null&&Y in J&&Object.prototype.hasOwnProperty.call(J,Y))delete J[Y];return!0}var n4=Symbol("PATH_NOT_FOUND");function n$0($,Z){let J=$;for(let Y of Z){if(J===null||J===void 0)return n4;if(typeof J!=="object"||J===null)return n4;if(!(Y in J))return n4;J=J[Y]}return J}function o$0($,Z){let J=$;for(let Y of Z){if(J===null||J===void 0)return;if(typeof J!=="object"||J===null)return;J=J[Y]}return J}function s$0($,Z,J,Y=!1){for(let X of Z){let Q=sP(X);if(Q.includes("*"))tP($,Q,J,X,Y);else if(Y)aP($,Q);else{let G=n$0($,Q);if(G===n4)continue;let W=typeof J==="function"?J(G,Q):J;rP($,Q,W)}}}function tP($,Z,J,Y,X=!1){let Q=Z.indexOf("*");if(Q===Z.length-1){let G=Z.slice(0,-1),W=$;for(let K of G){if(W===null||W===void 0)return;if(typeof W!=="object"||W===null)return;W=W[K]}if(Array.isArray(W))if(X)for(let K=0;K<W.length;K++)W[K]=void 0;else for(let K=0;K<W.length;K++){let V=[...G,K.toString()],U=typeof J==="function"?J(W[K],V):J;W[K]=U}else if(typeof W==="object"&&W!==null)if(X){let K=[];for(let V in W)if(Object.prototype.hasOwnProperty.call(W,V))K.push(V);for(let V of K)delete W[V]}else for(let K in W){let V=[...G,K],U=typeof J==="function"?J(W[K],V):J;W[K]=U}}else r$0($,Z,J,Q,Y,X)}function r$0($,Z,J,Y,X,Q=!1){let G=Z.slice(0,Y),W=Z.slice(Y+1),K=[];function V(U,H){if(H===G.length){if(Array.isArray(U))for(let B=0;B<U.length;B++)K[H]=B.toString(),V(U[B],H+1);else if(typeof U==="object"&&U!==null)for(let B in U)K[H]=B,V(U[B],H+1)}else if(H<G.length){let B=G[H];if(U&&typeof U==="object"&&U!==null&&B in U)K[H]=B,V(U[B],H+1)}else if(W.includes("*"))tP(U,W,typeof J==="function"?(z,F)=>{let A=[...K.slice(0,H),...F];return J(z,A)}:J,X,Q);else if(Q)aP(U,W);else{let B=typeof J==="function"?J(o$0(U,W),[...K.slice(0,H),...W]):J;rP(U,W,B)}}if(G.length===0)V($,0);else{let U=$;for(let H=0;H<G.length;H++){let B=G[H];if(U===null||U===void 0)return;if(typeof U!=="object"||U===null)return;U=U[B],K[H]=B}if(U!==null&&U!==void 0)V(U,G.length)}}function a$0($){if($.length===0)return null;let Z=new Map;for(let J of $){let Y=sP(J),X=Z;for(let Q=0;Q<Y.length;Q++){let G=Y[Q];if(!X.has(G))X.set(G,new Map);X=X.get(G)}}return Z}function t$0($,Z){if(!Z)return $;function J(Y,X,Q=0){if(!X||X.size===0)return Y;if(Y===null||typeof Y!=="object")return Y;if(Y instanceof Date)return new Date(Y.getTime());if(Array.isArray(Y)){let W=[];for(let K=0;K<Y.length;K++){let V=K.toString();if(X.has(V)||X.has("*"))W[K]=J(Y[K],X.get(V)||X.get("*"));else W[K]=Y[K]}return W}let G=Object.create(Object.getPrototypeOf(Y));for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))if(X.has(W)||X.has("*"))G[W]=J(Y[W],X.get(W)||X.get("*"));else G[W]=Y[W];return G}return J($,Z)}function e$0($){if(typeof $!=="string")throw Error("Paths must be (non-empty) strings");if($==="")throw Error("Invalid redaction path ()");if($.includes(".."))throw Error(`Invalid redaction path (${$})`);if($.includes(","))throw Error(`Invalid redaction path (${$})`);let Z=0,J=!1,Y="";for(let X=0;X<$.length;X++){let Q=$[X];if((Q==='"'||Q==="'")&&Z>0){if(!J)J=!0,Y=Q;else if(Q===Y)J=!1,Y=""}else if(Q==="["&&!J)Z++;else if(Q==="]"&&!J){if(Z--,Z<0)throw Error(`Invalid redaction path (${$})`)}}if(Z!==0)throw Error(`Invalid redaction path (${$})`)}function $80($){if(!Array.isArray($))throw TypeError("paths must be an array");for(let Z of $)e$0(Z)}function Z80($={}){let{paths:Z=[],censor:J="[REDACTED]",serialize:Y=JSON.stringify,strict:X=!0,remove:Q=!1}=$;$80(Z);let G=a$0(Z);return function(K){if(X&&(K===null||typeof K!=="object")){if(K===null||K===void 0)return Y?Y(K):K;if(typeof K!=="object")return Y?Y(K):K}let V=t$0(K,G),U=K,H=J;if(typeof J==="function")H=J;if(s$0(V,Z,H,Q),Y===!1)return V.restore=function(){return KB(U)},V;if(typeof Y==="function")return Y(V);return JSON.stringify(V)}}eP.exports=Z80});var PJ=S((sf0,ZI)=>{var J80=Symbol("pino.setLevel"),Y80=Symbol("pino.getLevel"),X80=Symbol("pino.levelVal"),Q80=Symbol("pino.levelComp"),G80=Symbol("pino.useLevelLabels"),W80=Symbol("pino.useOnlyCustomLevels"),K80=Symbol("pino.mixin"),V80=Symbol("pino.lsCache"),U80=Symbol("pino.chindings"),H80=Symbol("pino.asJson"),B80=Symbol("pino.write"),z80=Symbol("pino.redactFmt"),F80=Symbol("pino.time"),A80=Symbol("pino.timeSliceIndex"),O80=Symbol("pino.stream"),q80=Symbol("pino.stringify"),j80=Symbol("pino.stringifySafe"),N80=Symbol("pino.stringifiers"),M80=Symbol("pino.end"),D80=Symbol("pino.formatOpts"),w80=Symbol("pino.messageKey"),L80=Symbol("pino.errorKey"),T80=Symbol("pino.nestedKey"),R80=Symbol("pino.nestedKeyStr"),P80=Symbol("pino.mixinMergeStrategy"),I80=Symbol("pino.msgPrefix"),C80=Symbol("pino.wildcardFirst"),E80=Symbol.for("pino.serializers"),b80=Symbol.for("pino.formatters"),_80=Symbol.for("pino.hooks"),S80=Symbol.for("pino.metadata");ZI.exports={setLevelSym:J80,getLevelSym:Y80,levelValSym:X80,levelCompSym:Q80,useLevelLabelsSym:G80,mixinSym:K80,lsCacheSym:V80,chindingsSym:U80,asJsonSym:H80,writeSym:B80,serializersSym:E80,redactFmtSym:z80,timeSym:F80,timeSliceIndexSym:A80,streamSym:O80,stringifySym:q80,stringifySafeSym:j80,stringifiersSym:N80,endSym:M80,formatOptsSym:D80,messageKeySym:w80,errorKeySym:L80,nestedKeySym:T80,wildcardFirstSym:C80,needsMetadataGsym:S80,useOnlyCustomLevelsSym:W80,formattersSym:b80,hooksSym:_80,nestedKeyStrSym:R80,mixinMergeStrategySym:P80,msgPrefixSym:I80}});var UB=S((rf0,YI)=>{var JI=$I(),{redactFmtSym:f80,wildcardFirstSym:o4}=PJ(),VB=/[^.[\]]+|\[([^[\]]*?)\]/g;function k80($,Z){let{paths:J,censor:Y,remove:X}=v80($),Q=J.reduce((K,V)=>{VB.lastIndex=0;let U=VB.exec(V),H=VB.exec(V),B=U[1]!==void 0?U[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):U[0];if(B==="*")B=o4;if(H===null)return K[B]=null,K;if(K[B]===null)return K;let{index:z}=H,F=`${V.substr(z,V.length-1)}`;if(K[B]=K[B]||[],B!==o4&&K[B].length===0)K[B].push(...K[o4]||[]);if(B===o4)Object.keys(K).forEach(function(A){if(K[A])K[A].push(F)});return K[B].push(F),K},{}),G={[f80]:JI({paths:J,censor:Y,serialize:Z,strict:!1,remove:X})},W=(...K)=>{return typeof Y==="function"?Z(Y(...K)):Z(Y)};return[...Object.keys(Q),...Object.getOwnPropertySymbols(Q)].reduce((K,V)=>{if(Q[V]===null)K[V]=(U)=>W(U,[V]);else{let U=typeof Y==="function"?(H,B)=>{return Y(H,[V,...B])}:Y;K[V]=JI({paths:Q[V],censor:U,serialize:Z,strict:!1,remove:X})}return K},G)}function v80($){if(Array.isArray($))return $={paths:$,censor:"[Redacted]"},$;let{paths:Z,censor:J="[Redacted]",remove:Y}=$;if(Array.isArray(Z)===!1)throw Error("pino \u2013 redact must contain an array of strings");if(Y===!0)J=void 0;return{paths:Z,censor:J,remove:Y}}YI.exports=k80});var GI=S((af0,QI)=>{var y80=()=>"",x80=()=>`,"time":${Date.now()}`,h80=()=>`,"time":${Math.round(Date.now()/1000)}`,g80=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,u80=1000000n,XI=1000000000n,m80=BigInt(Date.now())*u80,l80=process.hrtime.bigint(),d80=()=>{let $=process.hrtime.bigint()-l80,Z=m80+$,J=Z/XI,Y=Z%XI,X=Number(J*1000n+Y/1000000n),Q=new Date(X),G=Q.getUTCFullYear(),W=(Q.getUTCMonth()+1).toString().padStart(2,"0"),K=Q.getUTCDate().toString().padStart(2,"0"),V=Q.getUTCHours().toString().padStart(2,"0"),U=Q.getUTCMinutes().toString().padStart(2,"0"),H=Q.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${G}-${W}-${K}T${V}:${U}:${H}.${Y.toString().padStart(9,"0")}Z"`};QI.exports={nullTime:y80,epochTime:x80,unixTime:h80,isoTime:g80,isoTimeNano:d80}});var KI=S((tf0,WI)=>{function p80($){try{return JSON.stringify($)}catch(Z){return'"[Circular]"'}}WI.exports=c80;function c80($,Z,J){var Y=J&&J.stringify||p80,X=1;if(typeof $==="object"&&$!==null){var Q=Z.length+X;if(Q===1)return $;var G=Array(Q);G[0]=Y($);for(var W=1;W<Q;W++)G[W]=Y(Z[W]);return G.join(" ")}if(typeof $!=="string")return $;var K=Z.length;if(K===0)return $;var V="",U=1-X,H=-1,B=$&&$.length||0;for(var z=0;z<B;){if($.charCodeAt(z)===37&&z+1<B){switch(H=H>-1?H:0,$.charCodeAt(z+1)){case 100:case 102:if(U>=K)break;if(Z[U]==null)break;if(H<z)V+=$.slice(H,z);V+=Number(Z[U]),H=z+2,z++;break;case 105:if(U>=K)break;if(Z[U]==null)break;if(H<z)V+=$.slice(H,z);V+=Math.floor(Number(Z[U])),H=z+2,z++;break;case 79:case 111:case 106:if(U>=K)break;if(Z[U]===void 0)break;if(H<z)V+=$.slice(H,z);var F=typeof Z[U];if(F==="string"){V+="'"+Z[U]+"'",H=z+2,z++;break}if(F==="function"){V+=Z[U].name||"<anonymous>",H=z+2,z++;break}V+=Y(Z[U]),H=z+2,z++;break;case 115:if(U>=K)break;if(H<z)V+=$.slice(H,z);V+=String(Z[U]),H=z+2,z++;break;case 37:if(H<z)V+=$.slice(H,z);V+="%",H=z+2,z++,U--;break}++U}++z}if(H===-1)return $;else if(H<B)V+=$.slice(H);return V}});var BB=S((ef0,HB)=>{if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let Z=function(J){if((J>0&&J<1/0)===!1){if(typeof J!=="number"&&typeof J!=="bigint")throw TypeError("sleep: ms must be a number");throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity")}Atomics.wait($,0,0,Number(J))},$=new Int32Array(new SharedArrayBuffer(4));HB.exports=Z}else{let $=function(Z){if((Z>0&&Z<1/0)===!1){if(typeof Z!=="number"&&typeof Z!=="bigint")throw TypeError("sleep: ms must be a number");throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity")}let Y=Date.now()+Number(Z);while(Y>Date.now());};HB.exports=$}});var FI=S(($k0,zI)=>{var p1=Y0("fs"),i80=Y0("events"),n80=Y0("util").inherits,VI=Y0("path"),FB=BB(),o80=Y0("assert"),s4=Buffer.allocUnsafe(0),[s80,r80]=(process.versions.node||"0.0").split(".").map(Number),a80=s80>=22&&r80>=7;function UI($,Z){Z._opening=!0,Z._writing=!0,Z._asyncDrainScheduled=!1;function J(Q,G){if(Q){if(Z._reopening=!1,Z._writing=!1,Z._opening=!1,Z.sync)process.nextTick(()=>{if(Z.listenerCount("error")>0)Z.emit("error",Q)});else Z.emit("error",Q);return}let W=Z._reopening;if(Z.fd=G,Z.file=$,Z._reopening=!1,Z._opening=!1,Z._writing=!1,Z.sync)process.nextTick(()=>Z.emit("ready"));else Z.emit("ready");if(Z.destroyed)return;if(!Z._writing&&Z._len>Z.minLength||Z._flushPending)Z._actualWrite();else if(W)process.nextTick(()=>Z.emit("drain"))}let Y=Z.append?"a":"w",X=Z.mode;if(Z.sync)try{if(Z.mkdir)p1.mkdirSync(VI.dirname($),{recursive:!0});let Q=p1.openSync($,Y,X);J(null,Q)}catch(Q){throw J(Q),Q}else if(Z.mkdir)p1.mkdir(VI.dirname($),{recursive:!0},(Q)=>{if(Q)return J(Q);p1.open($,Y,X,J)});else p1.open($,Y,X,J)}function e8($){if(!(this instanceof e8))return new e8($);let{fd:Z,dest:J,minLength:Y,maxLength:X,maxWrite:Q,periodicFlush:G,sync:W,append:K=!0,mkdir:V,retryEAGAIN:U,fsync:H,contentMode:B,mode:z}=$||{};Z=Z||J,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(Y||0,16387),this.file=null,this.destroyed=!1,this.minLength=Y||0,this.maxLength=X||0,this.maxWrite=Q||16384,this._periodicFlush=G||0,this._periodicFlushTimer=void 0,this.sync=W||!1,this.writable=!0,this._fsync=H||!1,this.append=K||!1,this.mode=z,this.retryEAGAIN=U||(()=>!0),this.mkdir=V||!1;let F,A;if(B==="buffer")this._writingBuf=s4,this.write=$60,this.flush=J60,this.flushSync=X60,this._actualWrite=G60,F=()=>p1.writeSync(this.fd,this._writingBuf),A=()=>p1.write(this.fd,this._writingBuf,this.release);else if(B===void 0||B==="utf8")this._writingBuf="",this.write=e80,this.flush=Z60,this.flushSync=Y60,this._actualWrite=Q60,F=()=>{if(Buffer.isBuffer(this._writingBuf))return p1.writeSync(this.fd,this._writingBuf);return p1.writeSync(this.fd,this._writingBuf,"utf8")},A=()=>{if(Buffer.isBuffer(this._writingBuf))return p1.write(this.fd,this._writingBuf,this.release);return p1.write(this.fd,this._writingBuf,"utf8",this.release)};else throw Error(`SonicBoom supports "utf8" and "buffer", but passed ${B}`);if(typeof Z==="number")this.fd=Z,process.nextTick(()=>this.emit("ready"));else if(typeof Z==="string")UI(Z,this);else throw Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);if(this.release=(j,N)=>{if(j){if((j.code==="EAGAIN"||j.code==="EBUSY")&&this.retryEAGAIN(j,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{FB(100),this.release(void 0,0)}catch(M){this.release(M)}else setTimeout(A,100);else this._writing=!1,this.emit("error",j);return}this.emit("write",N);let L=zB(this._writingBuf,this._len,N);if(this._len=L.len,this._writingBuf=L.writingBuf,this._writingBuf.length){if(!this.sync){A();return}try{do{let M=F(),C=zB(this._writingBuf,this._len,M);this._len=C.len,this._writingBuf=C.writingBuf}while(this._writingBuf.length)}catch(M){this.release(M);return}}if(this._fsync)p1.fsyncSync(this.fd);let q=this._len;if(this._reopening)this._writing=!1,this._reopening=!1,this.reopen();else if(q>this.minLength)this._actualWrite();else if(this._ending)if(q>0)this._actualWrite();else this._writing=!1,r4(this);else if(this._writing=!1,this.sync){if(!this._asyncDrainScheduled)this._asyncDrainScheduled=!0,process.nextTick(t80,this)}else this.emit("drain")},this.on("newListener",function(j){if(j==="drain")this._asyncDrainScheduled=!1}),this._periodicFlush!==0)this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref()}function zB($,Z,J){if(typeof $==="string")$=Buffer.from($);return Z=Math.max(Z-J,0),$=$.subarray(J),{writingBuf:$,len:Z}}function t80($){if(!($.listenerCount("drain")>0))return;$._asyncDrainScheduled=!1,$.emit("drain")}n80(e8,i80);function HI($,Z){if($.length===0)return s4;if($.length===1)return $[0];return Buffer.concat($,Z)}function e80($){if(this.destroyed)throw Error("SonicBoom destroyed");$=""+$;let Z=Buffer.byteLength($),J=this._len+Z,Y=this._bufs;if(this.maxLength&&J>this.maxLength)return this.emit("drop",$),this._len<this._hwm;if(Y.length===0||Buffer.byteLength(Y[Y.length-1])+Z>this.maxWrite)Y.push($);else Y[Y.length-1]+=$;if(this._len=J,!this._writing&&this._len>=this.minLength)this._actualWrite();return this._len<this._hwm}function $60($){if(this.destroyed)throw Error("SonicBoom destroyed");let Z=this._len+$.length,J=this._bufs,Y=this._lens;if(this.maxLength&&Z>this.maxLength)return this.emit("drop",$),this._len<this._hwm;if(J.length===0||Y[Y.length-1]+$.length>this.maxWrite)J.push([$]),Y.push($.length);else J[J.length-1].push($),Y[Y.length-1]+=$.length;if(this._len=Z,!this._writing&&this._len>=this.minLength)this._actualWrite();return this._len<this._hwm}function BI($){this._flushPending=!0;let Z=()=>{if(!this._fsync)try{p1.fsync(this.fd,(Y)=>{this._flushPending=!1,$(Y)})}catch(Y){$(Y)}else this._flushPending=!1,$();this.off("error",J)},J=(Y)=>{this._flushPending=!1,$(Y),this.off("drain",Z)};this.once("drain",Z),this.once("error",J)}function Z60($){if($!=null&&typeof $!=="function")throw Error("flush cb must be a function");if(this.destroyed){let Z=Error("SonicBoom destroyed");if($){$(Z);return}throw Z}if(this.minLength<=0){$?.();return}if($)BI.call(this,$);if(this._writing)return;if(this._bufs.length===0)this._bufs.push("");this._actualWrite()}function J60($){if($!=null&&typeof $!=="function")throw Error("flush cb must be a function");if(this.destroyed){let Z=Error("SonicBoom destroyed");if($){$(Z);return}throw Z}if(this.minLength<=0){$?.();return}if($)BI.call(this,$);if(this._writing)return;if(this._bufs.length===0)this._bufs.push([]),this._lens.push(0);this._actualWrite()}e8.prototype.reopen=function($){if(this.destroyed)throw Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen($)});return}if(this._ending)return;if(!this.file)throw Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if($)this.file=$;if(this._reopening=!0,this._writing)return;let Z=this.fd;this.once("ready",()=>{if(Z!==this.fd)p1.close(Z,(J)=>{if(J)return this.emit("error",J)})}),UI(this.file,this)};e8.prototype.end=function(){if(this.destroyed)throw Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}if(this._ending)return;if(this._ending=!0,this._writing)return;if(this._len>0&&this.fd>=0)this._actualWrite();else r4(this)};function Y60(){if(this.destroyed)throw Error("SonicBoom destroyed");if(this.fd<0)throw Error("sonic boom is not ready yet");if(!this._writing&&this._writingBuf.length>0)this._bufs.unshift(this._writingBuf),this._writingBuf="";let $="";while(this._bufs.length||$.length){if($.length<=0)$=this._bufs[0];try{let Z=Buffer.isBuffer($)?p1.writeSync(this.fd,$):p1.writeSync(this.fd,$,"utf8"),J=zB($,this._len,Z);if($=J.writingBuf,this._len=J.len,$.length<=0)this._bufs.shift()}catch(Z){if((Z.code==="EAGAIN"||Z.code==="EBUSY")&&!this.retryEAGAIN(Z,$.length,this._len-$.length))throw Z;FB(100)}}try{p1.fsyncSync(this.fd)}catch{}}function X60(){if(this.destroyed)throw Error("SonicBoom destroyed");if(this.fd<0)throw Error("sonic boom is not ready yet");if(!this._writing&&this._writingBuf.length>0)this._bufs.unshift([this._writingBuf]),this._writingBuf=s4;let $=s4;while(this._bufs.length||$.length){if($.length<=0)$=HI(this._bufs[0],this._lens[0]);try{let Z=p1.writeSync(this.fd,$);if($=$.subarray(Z),this._len=Math.max(this._len-Z,0),$.length<=0)this._bufs.shift(),this._lens.shift()}catch(Z){if((Z.code==="EAGAIN"||Z.code==="EBUSY")&&!this.retryEAGAIN(Z,$.length,this._len-$.length))throw Z;FB(100)}}}e8.prototype.destroy=function(){if(this.destroyed)return;r4(this)};function Q60(){let $=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let Z=Buffer.isBuffer(this._writingBuf)?p1.writeSync(this.fd,this._writingBuf):p1.writeSync(this.fd,this._writingBuf,"utf8");$(null,Z)}catch(Z){$(Z)}else p1.write(this.fd,this._writingBuf,$)}function G60(){let $=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:HI(this._bufs.shift(),this._lens.shift()),this.sync)try{let Z=p1.writeSync(this.fd,this._writingBuf);$(null,Z)}catch(Z){$(Z)}else{if(a80)this._writingBuf=Buffer.from(this._writingBuf);p1.write(this.fd,this._writingBuf,$)}}function r4($){if($.fd===-1){$.once("ready",r4.bind(null,$));return}if($._periodicFlushTimer!==void 0)clearInterval($._periodicFlushTimer);$.destroyed=!0,$._bufs=[],$._lens=[],o80(typeof $.fd==="number",`sonic.fd must be a number, got ${typeof $.fd}`);try{p1.fsync($.fd,Z)}catch{}function Z(){if($.fd!==1&&$.fd!==2)p1.close($.fd,J);else J()}function J(Y){if(Y){$.emit("error",Y);return}if($._ending&&!$._writing)$.emit("finish");$.emit("close")}}e8.SonicBoom=e8;e8.default=e8;zI.exports=e8});var AB=S((Zk0,NI)=>{var $6={exit:[],beforeExit:[]},AI={exit:V60,beforeExit:U60},IJ;function W60(){if(IJ===void 0)IJ=new FinalizationRegistry(H60)}function K60($){if($6[$].length>0)return;process.on($,AI[$])}function OI($){if($6[$].length>0)return;if(process.removeListener($,AI[$]),$6.exit.length===0&&$6.beforeExit.length===0)IJ=void 0}function V60(){qI("exit")}function U60(){qI("beforeExit")}function qI($){for(let Z of $6[$]){let J=Z.deref(),Y=Z.fn;if(J!==void 0)Y(J,$)}$6[$]=[]}function H60($){for(let Z of["exit","beforeExit"]){let J=$6[Z].indexOf($);$6[Z].splice(J,J+1),OI(Z)}}function jI($,Z,J){if(Z===void 0)throw Error("the object can't be undefined");K60($);let Y=new WeakRef(Z);Y.fn=J,W60(),IJ.register(Z,Y),$6[$].push(Y)}function B60($,Z){jI("exit",$,Z)}function z60($,Z){jI("beforeExit",$,Z)}function F60($){if(IJ===void 0)return;IJ.unregister($);for(let Z of["exit","beforeExit"])$6[Z]=$6[Z].filter((J)=>{let Y=J.deref();return Y&&Y!==$}),OI(Z)}NI.exports={register:B60,registerBeforeExit:z60,unregister:F60}});var MI=S((Jk0,A60)=>{A60.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var wI=S((Yk0,DI)=>{function O60($,Z,J,Y,X){let Q=Y===1/0?1/0:Date.now()+Y,G=()=>{let W=Atomics.load($,Z);if(W===J){X(null,"ok");return}if(Q!==1/0&&Date.now()>Q){X(null,"timed-out");return}let K=Q===1/0?1e4:Math.min(1e4,Math.max(1,Q-Date.now())),V=Atomics.waitAsync($,Z,W,K);if(V.async)V.value.then(G);else setImmediate(G)};G()}function q60($,Z,J,Y,X){let Q=Y===1/0?1/0:Date.now()+Y,G=()=>{if(Atomics.load($,Z)!==J){X(null,"ok");return}if(Q!==1/0&&Date.now()>Q){X(null,"timed-out");return}let K=Q===1/0?1e4:Math.min(1e4,Math.max(1,Q-Date.now())),V=Atomics.waitAsync($,Z,J,K);if(V.async)V.value.then((U)=>{if(U==="ok"){X(null,"ok");return}G()});else setImmediate(G)};G()}DI.exports={wait:O60,waitDiff:q60}});var TI=S((Xk0,LI)=>{LI.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var xI=S((Qk0,yI)=>{var __dirname="/home/runner/workspace/qode/node_modules/.bun/thread-stream@4.2.0/node_modules/thread-stream",{version:j60}=MI(),{EventEmitter:N60}=Y0("events"),{Worker:M60}=Y0("worker_threads"),{join:D60}=Y0("path"),{pathToFileURL:w60}=Y0("url"),{wait:L60}=wI(),{WRITE_INDEX:t6,READ_INDEX:i5,SEQ_INDEX:OB}=TI(),T60=Y0("buffer"),R60=Y0("assert"),s=Symbol("kImpl"),P60=T60.constants.MAX_STRING_LENGTH;function RI(){}function MB($,Z){Atomics.add($[s].state,OB,1),Z(),Atomics.add($[s].state,OB,1),Atomics.notify($[s].state,OB)}function PI($){MB($,()=>{Atomics.store($[s].state,i5,0),Atomics.store($[s].state,t6,0)})}class a4{constructor($){this._value=$}deref(){return this._value}}class jB{register(){}unregister(){}}var I60=process.env.NODE_V8_COVERAGE?jB:global.FinalizationRegistry||jB,C60=process.env.NODE_V8_COVERAGE?a4:global.WeakRef||a4,II=new I60(($)=>{if($.exited)return;$.terminate()});function E60($,Z){let{filename:J,workerData:Y}=Z,Q=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||D60(__dirname,"lib","worker.js"),G=new M60(Q,{...Z.workerOpts,name:Z.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:J.indexOf("file://")===0?J:w60(J).href,dataBuf:$[s].dataBuf,stateBuf:$[s].stateBuf,workerData:{$context:{threadStreamVersion:j60},...Y}}});return G.stream=new a4($),G.on("message",b60),G.on("exit",bI),II.register($,G),G}function CI($){if(R60(!$[s].sync),$[s].needDrain)$[s].needDrain=!1,$.emit("drain")}function EI($){while(!0){let Z=Atomics.load($[s].state,t6),J=$[s].data.length-Z;if(J>0){if($[s].bufLen===0){if($[s].flushing=!1,$[s].ending)DB($);else if($[s].needDrain)process.nextTick(CI,$);return}kI($,J,RI);continue}if(J===0){if(Z===0&&$[s].bufLen===0)return;t4($,()=>{if($.destroyed)return;PI($),EI($)});return}x8($,Error("overwritten"));return}}function b60($){let Z=this.stream.deref();if(Z===void 0){this.exited=!0,this.terminate();return}if($?.code==null)return;switch($.code){case"READY":this.stream=new C60(Z),t4(Z,()=>{Z[s].ready=!0,Z.emit("ready")});break;case"ERROR":x8(Z,$.err);break;case"EVENT":if(Array.isArray($.args))Z.emit($.name,...$.args);else Z.emit($.name,$.args);break;case"FLUSHED":{if($.context!=="thread-stream"){x8(Z,Error("this should not happen: "+$.code));break}let J=Z[s].flushCallbacks.get($.id);if(J)Z[s].flushCallbacks.delete($.id),process.nextTick(J);break}case"WARNING":process.emitWarning($.err);break;default:x8(Z,Error("this should not happen: "+$.code))}}function bI($){let Z=this.stream.deref();if(Z===void 0)return;II.unregister(Z),Z.worker.exited=!0,Z.worker.off("exit",bI),x8(Z,$!==0?Error("the worker thread exited"):null)}class _I extends N60{constructor($={}){super();if($.bufferSize<4)throw Error("bufferSize must at least fit a 4-byte utf-8 char");this[s]={},this[s].stateBuf=new SharedArrayBuffer(128),this[s].state=new Int32Array(this[s].stateBuf),this[s].dataBuf=new SharedArrayBuffer($.bufferSize||4194304),this[s].data=Buffer.from(this[s].dataBuf),this[s].sync=$.sync||!1,this[s].ending=!1,this[s].ended=!1,this[s].needDrain=!1,this[s].destroyed=!1,this[s].flushing=!1,this[s].ready=!1,this[s].finished=!1,this[s].errored=null,this[s].closed=!1,this[s].buf=[],this[s].bufHead=0,this[s].bufLen=0,this[s].flushCallbacks=new Map,this[s].nextFlushId=0,this.worker=E60(this,$),this.on("message",(Z,J)=>{this.worker.postMessage(Z,J)})}write($){let Z=Buffer.isBuffer($)?$:Buffer.from($);if(this[s].destroyed)return NB(this,Error("the worker has exited")),!1;if(this[s].ending)return NB(this,Error("the worker is ending")),!1;if(this[s].flushing&&this[s].bufLen+Z.length>=P60)try{qB(this),this[s].flushing=!0}catch(J){return x8(this,J),!1}if(this[s].buf.push(Z),this[s].bufLen+=Z.length,this[s].sync)try{return qB(this),!0}catch(J){return x8(this,J),!1}if(!this[s].flushing)this[s].flushing=!0,setImmediate(EI,this);return this[s].needDrain=this[s].data.length-this[s].bufLen-Atomics.load(this[s].state,t6)<=0,!this[s].needDrain}end(){if(this[s].destroyed)return;this[s].ending=!0,DB(this)}flush($){$=typeof $==="function"?$:RI,SI(this,(Z)=>{if(Z){process.nextTick($,Z);return}fI(this,$)})}flushSync(){if(this[s].destroyed)return;qB(this),vI(this)}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[s].ready}get destroyed(){return this[s].destroyed}get closed(){return this[s].closed}get writable(){return!this[s].destroyed&&!this[s].ending}get writableEnded(){return this[s].ending}get writableFinished(){return this[s].finished}get writableNeedDrain(){return this[s].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[s].errored}}function SI($,Z){if($[s].destroyed){process.nextTick(Z,Error("the worker has exited"));return}if(!$[s].sync&&($[s].flushing||$[s].bufLen>0)){setImmediate(SI,$,Z);return}t4($,Z)}function t4($,Z){let J=Atomics.load($[s].state,t6);L60($[s].state,i5,J,1/0,(Y,X)=>{if(Y){x8($,Y),Z(Y);return}if(X!=="ok"){t4($,Z);return}Z()})}function fI($,Z){if($[s].destroyed){process.nextTick(Z,Error("the worker has exited"));return}if(!$[s].ready){let Y=()=>{Q(),fI($,Z)},X=()=>{Q(),process.nextTick(Z,Error("the worker has exited"))},Q=()=>{$.off("ready",Y),$.off("close",X)};$.once("ready",Y),$.once("close",X);return}let J=++$[s].nextFlushId;$[s].flushCallbacks.set(J,Z);try{$.worker.postMessage({code:"FLUSH",context:"thread-stream",id:J})}catch(Y){$[s].flushCallbacks.delete(J),x8($,Y),process.nextTick(Z,Y)}}function _60($,Z){let J=$[s].flushCallbacks;if(J.size===0)return;let Y=Z||Error("the worker has exited");for(let X of J.values())process.nextTick(X,Y);J.clear()}function NB($,Z){setImmediate(()=>{$.emit("error",Z)})}function x8($,Z){if($[s].destroyed)return;if($[s].destroyed=!0,_60($,Z),Z)$[s].errored=Z,NB($,Z);if(!$.worker.exited)$.worker.terminate().catch(()=>{}).then(()=>{$[s].closed=!0,$.emit("close")});else setImmediate(()=>{$[s].closed=!0,$.emit("close")})}function kI($,Z,J){let X=Atomics.load($[s].state,t6),Q=Z;while(Q>0&&$[s].bufLen!==0){let G=$[s].bufHead,W=$[s].buf[G];if(W.length<=Q){if(W.copy($[s].data,X),X+=W.length,Q-=W.length,$[s].bufLen-=W.length,$[s].bufHead=G+1,$[s].bufHead===$[s].buf.length)$[s].buf.length=0,$[s].bufHead=0;else if($[s].bufHead>=1024&&$[s].bufHead*2>=$[s].buf.length)$[s].buf.splice(0,$[s].bufHead),$[s].bufHead=0;continue}W.copy($[s].data,X,0,Q),$[s].buf[G]=W.subarray(Q),$[s].bufLen-=Q,X+=Q,Q=0}return MB($,()=>{Atomics.store($[s].state,t6,X)}),J(),!0}function DB($){if($[s].ended||!$[s].ending||$[s].flushing)return;$[s].ended=!0;try{$.flushSync();let Z=Atomics.load($[s].state,i5);MB($,()=>{Atomics.store($[s].state,t6,-1)});let J=0;while(Z!==-1){if(Atomics.wait($[s].state,i5,Z,1000),Z=Atomics.load($[s].state,i5),Z===-2){x8($,Error("end() failed"));return}if(++J===10){x8($,Error("end() took too long (10s)"));return}}process.nextTick(()=>{$[s].finished=!0,$.emit("finish")})}catch(Z){x8($,Z)}}function qB($){let Z=()=>{if($[s].ending)DB($);else if($[s].needDrain)process.nextTick(CI,$)};$[s].flushing=!1;while($[s].bufLen!==0){let J=Atomics.load($[s].state,t6),Y=$[s].data.length-J;if(Y===0){vI($),PI($);continue}else if(Y<0)throw Error("overwritten");kI($,Y,Z)}}function vI($){if($[s].flushing)throw Error("unable to flush while flushing");let Z=Atomics.load($[s].state,t6),J=0;while(!0){let Y=Atomics.load($[s].state,i5);if(Y===-2)throw Error("_flushSync failed");if(Y!==Z)Atomics.wait($[s].state,i5,Y,1000);else break;if(++J===10)throw Error("_flushSync took too long (10s)")}}yI.exports=_I});var TB=S((Gk0,uI)=>{var __dirname="/home/runner/workspace/qode/node_modules/.bun/pino@10.3.1/node_modules/pino/lib",{createRequire:S60}=Y0("module"),{existsSync:f60}=Y0("fs"),k60=WB(),{join:wB,isAbsolute:gI,sep:v60}=Y0("path"),{fileURLToPath:y60}=Y0("url"),x60=BB(),LB=AB(),h60=xI();function g60($){LB.register($,p60),LB.registerBeforeExit($,c60),$.on("close",function(){LB.unregister($)})}function u60(){let $=process.execArgv;for(let Z=0;Z<$.length;Z++){let J=$[Z];if(J==="--import"||J==="--require"||J==="-r")return!0;if(J.startsWith("--import=")||J.startsWith("--require=")||J.startsWith("-r="))return!0}return!1}function m60($){let Z=$.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!Z)return $;let J=[],Y=!1;for(let X=0;X<Z.length;X++){let Q=Z[X];if(Q==="--require"||Q==="-r"||Q==="--import"){let G=Z[X+1];if(G&&hI(G)){Y=!0,X++;continue}if(J.push(Q),G)J.push(G),X++;continue}if(Q.startsWith("--require=")||Q.startsWith("-r=")||Q.startsWith("--import=")){let G=Q.slice(Q.indexOf("=")+1);if(hI(G)){Y=!0;continue}}J.push(Q)}return Y?J.join(" "):$}function hI($){let Z=l60($);if(!Z)return!1;let J=Z;if(J.startsWith("file://"))try{J=y60(J)}catch{return!1}return gI(J)&&!f60(J)}function l60($){let Z=$[0],J=$[$.length-1];if(Z==='"'&&J==='"'||Z==="'"&&J==="'")return $.slice(1,-1);return $}function d60($,Z,J,Y,X){if(!J.execArgv&&u60()&&Y0.main===void 0)J={...J,execArgv:[]};if(!J.env&&process.env.NODE_OPTIONS){let K=m60(process.env.NODE_OPTIONS);if(K!==process.env.NODE_OPTIONS)J={...J,env:{...process.env,NODE_OPTIONS:K}}}J={...J,name:X};let Q=new h60({filename:$,workerData:Z,workerOpts:J,sync:Y});Q.on("ready",G),Q.on("close",function(){process.removeListener("exit",W)}),process.on("exit",W);function G(){if(process.removeListener("exit",W),Q.unref(),J.autoEnd!==!1)g60(Q)}function W(){if(Q.closed)return;Q.flushSync(),x60(100),Q.end()}return Q}function p60($){$.ref(),$.flushSync(),$.end(),$.once("close",function(){$.unref()})}function c60($){$.flushSync()}function i60($){let{pipeline:Z,targets:J,levels:Y,dedupe:X,worker:Q={},caller:G=k60(),sync:W=!1}=$,K={...$.options},V=typeof G==="string"?[G]:G,U=typeof globalThis==="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==="object"?globalThis.__bundlerPathsOverrides:Object.create(null),H=$.target;if(H&&J)throw Error("only one of target or targets can be specified");if(J)H=U["pino-worker"]||wB(__dirname,"worker.js"),K.targets=J.filter((F)=>F.target).map((F)=>{return{...F,target:z(F.target)}}),K.pipelines=J.filter((F)=>F.pipeline).map((F)=>{return F.pipeline.map((A)=>{return{...A,level:F.level,target:z(A.target)}})});else if(Z)H=U["pino-worker"]||wB(__dirname,"worker.js"),K.pipelines=[Z.map((F)=>{return{...F,target:z(F.target)}})];if(Y)K.levels=Y;if(X)K.dedupe=X;K.pinoWillSendConfig=!0;let B=J||Z?"pino.transport":H;return d60(z(H),K,Q,W,B);function z(F){if(F=U[F]||F,gI(F)||F.indexOf("file://")===0)return F;if(F==="pino/file")return wB(__dirname,"..","file.js");let A;for(let j of V)try{let N=j==="node:repl"?process.cwd()+v60:j;A=S60(N).resolve(F);break}catch(N){continue}if(!A)throw Error(`unable to determine transport target for "${F}"`);return A}}uI.exports=i60});var ZG=S((Kk0,eI)=>{var n60=Y0("diagnostics_channel"),mI=KI(),{mapHttpRequest:o60,mapHttpResponse:s60}=GB(),PB=FI(),lI=AB(),{lsCacheSym:r60,chindingsSym:nI,writeSym:dI,serializersSym:oI,formatOptsSym:pI,endSym:a60,stringifiersSym:sI,stringifySym:rI,stringifySafeSym:IB,wildcardFirstSym:aI,nestedKeySym:t60,formattersSym:tI,messageKeySym:e60,errorKeySym:$Z0,nestedKeyStrSym:ZZ0,msgPrefixSym:e4}=PJ(),{isMainThread:JZ0}=Y0("worker_threads"),YZ0=TB(),[XZ0]=process.versions.node.split(".").map(($)=>Number($)),cI=n60.tracingChannel("pino_asJson"),RB=XZ0>=25?($)=>JSON.stringify($):GZ0;function CJ(){}function QZ0($,Z){if(!Z)return J;return function(...X){Z.call(this,X,J,$)};function J(Y,...X){if(typeof Y==="object"){let Q=Y;if(Y!==null){if(Y.method&&Y.headers&&Y.socket)Y=o60(Y);else if(typeof Y.setHeader==="function")Y=s60(Y)}let G;if(Q===null&&X.length===0)G=[null];else Q=X.shift(),G=X;if(typeof this[e4]==="string"&&Q!==void 0&&Q!==null)Q=this[e4]+Q;this[dI](Y,mI(Q,G,this[pI]),$)}else{let Q=Y===void 0?X.shift():Y;if(typeof this[e4]==="string"&&Q!==void 0&&Q!==null)Q=this[e4]+Q;this[dI](null,mI(Q,X,this[pI]),$)}}}function GZ0($){let Z="",J=0,Y=!1,X=255,Q=$.length;if(Q>100)return JSON.stringify($);for(var G=0;G<Q&&X>=32;G++)if(X=$.charCodeAt(G),X===34||X===92)Z+=$.slice(J,G)+"\\",J=G,Y=!0;if(!Y)Z=$;else Z+=$.slice(J);return X<32?JSON.stringify($):'"'+Z+'"'}function WZ0($,Z,J,Y){if(cI.hasSubscribers===!1)return iI.call(this,$,Z,J,Y);let X={instance:this,arguments};return cI.traceSync(iI,X,this,$,Z,J,Y)}function iI($,Z,J,Y){let X=this[rI],Q=this[IB],G=this[sI],W=this[a60],K=this[nI],V=this[oI],U=this[tI],H=this[e60],B=this[$Z0],z=this[r60][J]+Y;z=z+K;let F;if(U.log)$=U.log($);let A=G[aI],j="";for(let L in $)if(F=$[L],Object.prototype.hasOwnProperty.call($,L)&&F!==void 0){if(V[L])F=V[L](F);else if(L===B&&V.err)F=V.err(F);let q=G[L]||A;switch(typeof F){case"undefined":case"function":continue;case"number":if(Number.isFinite(F)===!1)F=null;case"boolean":if(q)F=q(F);break;case"string":F=(q||RB)(F);break;default:F=(q||X)(F,Q)}if(F===void 0)continue;let M=RB(L);j+=","+M+":"+F}let N="";if(Z!==void 0){F=V[H]?V[H](Z):Z;let L=G[H]||A;switch(typeof F){case"function":break;case"number":if(Number.isFinite(F)===!1)F=null;case"boolean":if(L)F=L(F);N=',"'+H+'":'+F;break;case"string":F=(L||RB)(F),N=',"'+H+'":'+F;break;default:F=(L||X)(F,Q),N=',"'+H+'":'+F}}if(this[t60]&&j)return z+this[ZZ0]+j.slice(1)+"}"+N+W;else return z+j+N+W}function KZ0($,Z){let J,Y=$[nI],X=$[rI],Q=$[IB],G=$[sI],W=G[aI],K=$[oI],V=$[tI].bindings;Z=V(Z);for(let U in Z)if(J=Z[U],((U.length<5||U!=="level"&&U!=="serializers"&&U!=="formatters"&&U!=="customLevels")&&Z.hasOwnProperty(U)&&J!==void 0)===!0){if(J=K[U]?K[U](J):J,J=(G[U]||W||X)(J,Q),J===void 0)continue;Y+=',"'+U+'":'+J}return Y}function VZ0($){return $.write!==$.constructor.prototype.write}function $G($){let Z=new PB($);if(Z.on("error",J),!$.sync&&JZ0)lI.register(Z,UZ0),Z.on("close",function(){lI.unregister(Z)});return Z;function J(Y){if(Y.code==="EPIPE"){Z.write=CJ,Z.end=CJ,Z.flushSync=CJ,Z.destroy=CJ;return}Z.removeListener("error",J),Z.emit("error",Y)}}function UZ0($,Z){if($.destroyed)return;if(Z==="beforeExit")$.flush(),$.on("drain",function(){$.end()});else $.flushSync()}function HZ0($){return function(J,Y,X={},Q){if(typeof X==="string")Q=$G({dest:X}),X={};else if(typeof Q==="string"){if(X&&X.transport)throw Error("only one of option.transport or stream can be specified");Q=$G({dest:Q})}else if(X instanceof PB||X.writable||X._writableState)Q=X,X={};else if(X.transport){if(X.transport instanceof PB||X.transport.writable||X.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(X.transport.targets&&X.transport.targets.length&&X.formatters&&typeof X.formatters.level==="function")throw Error("option.transport.targets do not allow custom level formatters");let K;if(X.customLevels)K=X.useOnlyCustomLevels?X.customLevels:Object.assign({},X.levels,X.customLevels);Q=YZ0({caller:Y,...X.transport,levels:K})}if(X=Object.assign({},$,X),X.serializers=Object.assign({},$.serializers,X.serializers),X.formatters=Object.assign({},$.formatters,X.formatters),X.prettyPrint)throw Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:G,onChild:W}=X;if(G===!1)X.level="silent";if(!W)X.onChild=CJ;if(!Q)if(!VZ0(process.stdout))Q=$G({fd:process.stdout.fd||1});else Q=process.stdout;return{opts:X,stream:Q}}}function BZ0($,Z){try{return JSON.stringify($)}catch(J){try{return(Z||this[IB])($)}catch(Y){return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function zZ0($,Z,J){return{level:$,bindings:Z,log:J}}function FZ0($){let Z=Number($);if(typeof $==="string"&&Number.isFinite(Z))return Z;if($===void 0)return 1;return $}eI.exports={noop:CJ,buildSafeSonicBoom:$G,asChindings:KZ0,asJson:WZ0,genLog:QZ0,createArgsNormalizer:HZ0,stringify:BZ0,buildFormatters:zZ0,normalizeDestFileDescriptor:FZ0}});var JG=S((Vk0,$C)=>{var AZ0={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},OZ0={ASC:"ASC",DESC:"DESC"};$C.exports={DEFAULT_LEVELS:AZ0,SORTING_ORDER:OZ0}});var bB=S((Uk0,XC)=>{var{lsCacheSym:qZ0,levelValSym:CB,useOnlyCustomLevelsSym:jZ0,streamSym:NZ0,formattersSym:MZ0,hooksSym:DZ0,levelCompSym:ZC}=PJ(),{noop:wZ0,genLog:n5}=ZG(),{DEFAULT_LEVELS:P6,SORTING_ORDER:JC}=JG(),YC={fatal:($)=>{let Z=n5(P6.fatal,$);return function(...J){let Y=this[NZ0];if(Z.call(this,...J),typeof Y.flushSync==="function")try{Y.flushSync()}catch(X){}}},error:($)=>n5(P6.error,$),warn:($)=>n5(P6.warn,$),info:($)=>n5(P6.info,$),debug:($)=>n5(P6.debug,$),trace:($)=>n5(P6.trace,$)},EB=Object.keys(P6).reduce(($,Z)=>{return $[P6[Z]]=Z,$},{}),LZ0=Object.keys(EB).reduce(($,Z)=>{return $[Z]='{"level":'+Number(Z),$},{});function TZ0($){let Z=$[MZ0].level,{labels:J}=$.levels,Y={};for(let X in J){let Q=Z(J[X],Number(X));Y[X]=JSON.stringify(Q).slice(0,-1)}return $[qZ0]=Y,$}function RZ0($,Z){if(Z)return!1;switch($){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function PZ0($){let{labels:Z,values:J}=this.levels;if(typeof $==="number"){if(Z[$]===void 0)throw Error("unknown level value"+$);$=Z[$]}if(J[$]===void 0)throw Error("unknown level "+$);let Y=this[CB],X=this[CB]=J[$],Q=this[jZ0],G=this[ZC],W=this[DZ0].logMethod;for(let K in J){if(G(J[K],X)===!1){this[K]=wZ0;continue}this[K]=RZ0(K,Q)?YC[K](W):n5(J[K],W)}this.emit("level-change",$,X,Z[Y],Y,this)}function IZ0($){let{levels:Z,levelVal:J}=this;return Z&&Z.labels?Z.labels[J]:""}function CZ0($){let{values:Z}=this.levels,J=Z[$];return J!==void 0&&this[ZC](J,this[CB])}function EZ0($,Z,J){if($===JC.DESC)return Z<=J;return Z>=J}function bZ0($){if(typeof $==="string")return EZ0.bind(null,$);return $}function _Z0($=null,Z=!1){let J=$?Object.keys($).reduce((Q,G)=>{return Q[$[G]]=G,Q},{}):null,Y=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),Z?null:EB,J),X=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),Z?null:P6,$);return{labels:Y,values:X}}function SZ0($,Z,J){if(typeof $==="number"){if(![].concat(Object.keys(Z||{}).map((Q)=>Z[Q]),J?[]:Object.keys(EB).map((Q)=>+Q),1/0).includes($))throw Error(`default level:${$} must be included in custom levels`);return}let Y=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),J?null:P6,Z);if(!($ in Y))throw Error(`default level:${$} must be included in custom levels`)}function fZ0($,Z){let{labels:J,values:Y}=$;for(let X in Z){if(X in Y)throw Error("levels cannot be overridden");if(Z[X]in J)throw Error("pre-existing level values cannot be used for new levels")}}function kZ0($){if(typeof $==="function")return;if(typeof $==="string"&&Object.values(JC).includes($))return;throw Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}XC.exports={initialLsCache:LZ0,genLsCache:TZ0,levelMethods:YC,getLevel:IZ0,setLevel:PZ0,isLevelEnabled:CZ0,mappings:_Z0,assertNoLevelCollisions:fZ0,assertDefaultLevelFound:SZ0,genLevelComparison:bZ0,assertLevelComparison:kZ0}});var _B=S((Hk0,QC)=>{QC.exports={version:"10.3.1"}});var zC=S((Bk0,BC)=>{var{EventEmitter:vZ0}=Y0("events"),{lsCacheSym:yZ0,levelValSym:xZ0,setLevelSym:fB,getLevelSym:GC,chindingsSym:XG,mixinSym:hZ0,asJsonSym:KC,writeSym:gZ0,mixinMergeStrategySym:uZ0,timeSym:mZ0,timeSliceIndexSym:lZ0,streamSym:VC,serializersSym:o5,formattersSym:kX,errorKeySym:dZ0,messageKeySym:pZ0,useOnlyCustomLevelsSym:cZ0,needsMetadataGsym:iZ0,redactFmtSym:nZ0,stringifySym:oZ0,formatOptsSym:sZ0,stringifiersSym:rZ0,msgPrefixSym:kB,hooksSym:aZ0}=PJ(),{getLevel:tZ0,setLevel:eZ0,isLevelEnabled:$50,mappings:Z50,initialLsCache:J50,genLsCache:Y50,assertNoLevelCollisions:X50}=bB(),{asChindings:vB,asJson:Q50,buildFormatters:SB,stringify:WC,noop:UC}=ZG(),{version:G50}=_B(),W50=UB(),K50=class{},HC={constructor:K50,child:V50,bindings:U50,setBindings:H50,flush:F50,isLevelEnabled:$50,version:G50,get level(){return this[GC]()},set level($){this[fB]($)},get levelVal(){return this[xZ0]},set levelVal($){throw Error("levelVal is read-only")},get msgPrefix(){return this[kB]},get[Symbol.toStringTag](){return"Pino"},[yZ0]:J50,[gZ0]:z50,[KC]:Q50,[GC]:tZ0,[fB]:eZ0};Object.setPrototypeOf(HC,vZ0.prototype);BC.exports=function(){return Object.create(HC)};var YG=($)=>$;function V50($,Z){if(!$)throw Error("missing bindings for child Pino");let J=this[o5],Y=this[kX],X=Object.create(this);if(Z==null){if(X[kX].bindings!==YG)X[kX]=SB(Y.level,YG,Y.log);if(X[XG]=vB(X,$),this.onChild!==UC)this.onChild(X);return X}if(Z.hasOwnProperty("serializers")===!0){X[o5]=Object.create(null);for(let V in J)X[o5][V]=J[V];let W=Object.getOwnPropertySymbols(J);for(var Q=0;Q<W.length;Q++){let V=W[Q];X[o5][V]=J[V]}for(let V in Z.serializers)X[o5][V]=Z.serializers[V];let K=Object.getOwnPropertySymbols(Z.serializers);for(var G=0;G<K.length;G++){let V=K[G];X[o5][V]=Z.serializers[V]}}else X[o5]=J;if(Z.hasOwnProperty("formatters")){let{level:W,bindings:K,log:V}=Z.formatters;X[kX]=SB(W||Y.level,K||YG,V||Y.log)}else X[kX]=SB(Y.level,YG,Y.log);if(Z.hasOwnProperty("customLevels")===!0)X50(this.levels,Z.customLevels),X.levels=Z50(Z.customLevels,X[cZ0]),Y50(X);if(typeof Z.redact==="object"&&Z.redact!==null||Array.isArray(Z.redact)){X.redact=Z.redact;let W=W50(X.redact,WC),K={stringify:W[nZ0]};X[oZ0]=WC,X[rZ0]=W,X[sZ0]=K}if(typeof Z.msgPrefix==="string")X[kB]=(this[kB]||"")+Z.msgPrefix;if(X[XG]=vB(X,$),Z.level!==void 0&&Z.level!==this.level||Z.hasOwnProperty("customLevels")){let W=Z.level||this.level;X[fB](W)}return this.onChild(X),X}function U50(){let Z=`{${this[XG].substr(1)}}`,J=JSON.parse(Z);return delete J.pid,delete J.hostname,J}function H50($){let Z=vB(this,$);this[XG]=Z}function B50($,Z){return Object.assign(Z,$)}function z50($,Z,J){let Y=this[mZ0](),X=this[hZ0],Q=this[dZ0],G=this[pZ0],W=this[uZ0]||B50,K,V=this[aZ0].streamWrite;if($===void 0||$===null)K={};else if($ instanceof Error){if(K={[Q]:$},Z===void 0)Z=$.message}else if(K=$,Z===void 0&&$[G]===void 0&&$[Q])Z=$[Q].message;if(X)K=W(K,X(K,J,this));let U=this[KC](K,Z,J,Y),H=this[VC];if(H[iZ0]===!0)H.lastLevel=J,H.lastObj=K,H.lastMsg=Z,H.lastTime=Y.slice(this[lZ0]),H.lastLogger=this;H.write(V?V(U):U)}function F50($){if($!=null&&typeof $!=="function")throw Error("callback must be a function");let Z=this[VC];if(typeof Z.flush==="function")Z.flush($||UC);else if($)$()}});var qC=S((zk0,OC)=>{var{hasOwnProperty:vX}=Object.prototype,r5=hB();r5.configure=hB;r5.stringify=r5;r5.default=r5;zk0.stringify=r5;zk0.configure=hB;OC.exports=r5;var A50=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function lZ($){if($.length<5000&&!A50.test($))return`"${$}"`;return JSON.stringify($)}function yB($,Z){if($.length>200||Z)return $.sort(Z);for(let J=1;J<$.length;J++){let Y=$[J],X=J;while(X!==0&&$[X-1]>Y)$[X]=$[X-1],X--;$[X]=Y}return $}var O50=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function xB($){return O50.call($)!==void 0&&$.length!==0}function FC($,Z,J){if($.length<J)J=$.length;let Y=Z===","?"":" ",X=`"0":${Y}${$[0]}`;for(let Q=1;Q<J;Q++)X+=`${Z}"${Q}":${Y}${$[Q]}`;return X}function q50($){if(vX.call($,"circularValue")){let Z=$.circularValue;if(typeof Z==="string")return`"${Z}"`;if(Z==null)return Z;if(Z===Error||Z===TypeError)return{toString(){throw TypeError("Converting circular structure to JSON")}};throw TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function j50($){let Z;if(vX.call($,"deterministic")){if(Z=$.deterministic,typeof Z!=="boolean"&&typeof Z!=="function")throw TypeError('The "deterministic" argument must be of type boolean or comparator function')}return Z===void 0?!0:Z}function N50($,Z){let J;if(vX.call($,Z)){if(J=$[Z],typeof J!=="boolean")throw TypeError(`The "${Z}" argument must be of type boolean`)}return J===void 0?!0:J}function AC($,Z){let J;if(vX.call($,Z)){if(J=$[Z],typeof J!=="number")throw TypeError(`The "${Z}" argument must be of type number`);if(!Number.isInteger(J))throw TypeError(`The "${Z}" argument must be an integer`);if(J<1)throw RangeError(`The "${Z}" argument must be >= 1`)}return J===void 0?1/0:J}function s5($){if($===1)return"1 item";return`${$} items`}function M50($){let Z=new Set;for(let J of $)if(typeof J==="string"||typeof J==="number")Z.add(String(J));return Z}function D50($){if(vX.call($,"strict")){let Z=$.strict;if(typeof Z!=="boolean")throw TypeError('The "strict" argument must be of type boolean');if(Z)return(J)=>{let Y=`Object can not safely be stringified. Received type ${typeof J}`;if(typeof J!=="function")Y+=` (${J.toString()})`;throw Error(Y)}}}function hB($){$={...$};let Z=D50($);if(Z){if($.bigint===void 0)$.bigint=!1;if(!("circularValue"in $))$.circularValue=Error}let J=q50($),Y=N50($,"bigint"),X=j50($),Q=typeof X==="function"?X:void 0,G=AC($,"maximumDepth"),W=AC($,"maximumBreadth");function K(z,F,A,j,N,L){let q=F[z];if(typeof q==="object"&&q!==null&&typeof q.toJSON==="function")q=q.toJSON(z);switch(q=j.call(F,z,q),typeof q){case"string":return lZ(q);case"object":{if(q===null)return"null";if(A.indexOf(q)!==-1)return J;let M="",C=",",R=L;if(Array.isArray(q)){if(q.length===0)return"[]";if(G<A.length+1)return'"[Array]"';if(A.push(q),N!=="")L+=N,M+=`
86
+ caused by: `+EP(Y,Z);else return J},S$0=($)=>EP($,new Set),bP=($,Z,J)=>{if(!fX($))return"";let Y=J?"":$.message||"";if(Z.has($))return Y+": ...";let X=aH($);if(X){Z.add($);let Q=typeof $.cause==="function";return Y+(Q?"":": ")+bP(X,Z,Q)}else return Y},f$0=($)=>bP($,new Set);_P.exports={isErrorLike:fX,getErrorCause:aH,stackWithCauses:S$0,messageWithCauses:f$0}});var eH=S((mf0,fP)=>{var k$0=Symbol("circular-ref-tag"),l4=Symbol("pino-raw-err-ref"),SP=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[l4]},set:function($){this[l4]=$}}});Object.defineProperty(SP,l4,{writable:!0,value:{}});fP.exports={pinoErrProto:SP,pinoErrorSymbols:{seen:k$0,rawSymbol:l4}}});var yP=S((lf0,vP)=>{vP.exports=ZB;var{messageWithCauses:v$0,stackWithCauses:y$0,isErrorLike:kP}=tH(),{pinoErrProto:x$0,pinoErrorSymbols:h$0}=eH(),{seen:$B}=h$0,{toString:g$0}=Object.prototype;function ZB($){if(!kP($))return $;$[$B]=void 0;let Z=Object.create(x$0);if(Z.type=g$0.call($.constructor)==="[object Function]"?$.constructor.name:$.name,Z.message=v$0($),Z.stack=y$0($),Array.isArray($.errors))Z.aggregateErrors=$.errors.map((J)=>ZB(J));for(let J in $)if(Z[J]===void 0){let Y=$[J];if(kP(Y)){if(J!=="cause"&&!Object.prototype.hasOwnProperty.call(Y,$B))Z[J]=ZB(Y)}else Z[J]=Y}return delete $[$B],Z.raw=$,Z}});var hP=S((df0,xP)=>{xP.exports=p4;var{isErrorLike:JB}=tH(),{pinoErrProto:u$0,pinoErrorSymbols:m$0}=eH(),{seen:d4}=m$0,{toString:l$0}=Object.prototype;function p4($){if(!JB($))return $;$[d4]=void 0;let Z=Object.create(u$0);if(Z.type=l$0.call($.constructor)==="[object Function]"?$.constructor.name:$.name,Z.message=$.message,Z.stack=$.stack,Array.isArray($.errors))Z.aggregateErrors=$.errors.map((J)=>p4(J));if(JB($.cause)&&!Object.prototype.hasOwnProperty.call($.cause,d4))Z.cause=p4($.cause);for(let J in $)if(Z[J]===void 0){let Y=$[J];if(JB(Y)){if(!Object.prototype.hasOwnProperty.call(Y,d4))Z[J]=p4(Y)}else Z[J]=Y}return delete $[d4],Z.raw=$,Z}});var lP=S((pf0,mP)=>{mP.exports={mapHttpRequest:d$0,reqSerializer:uP};var YB=Symbol("pino-raw-req-ref"),gP=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[YB]},set:function($){this[YB]=$}}});Object.defineProperty(gP,YB,{writable:!0,value:{}});function uP($){let Z=$.info||$.socket,J=Object.create(gP);if(J.id=typeof $.id==="function"?$.id():$.id||($.info?$.info.id:void 0),J.method=$.method,$.originalUrl)J.url=$.originalUrl;else{let Y=$.path;J.url=typeof Y==="string"?Y:$.url?$.url.path||$.url:void 0}if($.query)J.query=$.query;if($.params)J.params=$.params;return J.headers=$.headers,J.remoteAddress=Z&&Z.remoteAddress,J.remotePort=Z&&Z.remotePort,J.raw=$.raw||$,J}function d$0($){return{req:uP($)}}});var iP=S((cf0,cP)=>{cP.exports={mapHttpResponse:p$0,resSerializer:pP};var XB=Symbol("pino-raw-res-ref"),dP=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[XB]},set:function($){this[XB]=$}}});Object.defineProperty(dP,XB,{writable:!0,value:{}});function pP($){let Z=Object.create(dP);return Z.statusCode=$.headersSent?$.statusCode:null,Z.headers=$.getHeaders?$.getHeaders():$._headers,Z.raw=$,Z}function p$0($){return{res:pP($)}}});var GB=S((if0,nP)=>{var QB=yP(),c$0=hP(),c4=lP(),i4=iP();nP.exports={err:QB,errWithCause:c$0,mapHttpRequest:c4.mapHttpRequest,mapHttpResponse:i4.mapHttpResponse,req:c4.reqSerializer,res:i4.resSerializer,wrapErrorSerializer:function(Z){if(Z===QB)return Z;return function(Y){return Z(QB(Y))}},wrapRequestSerializer:function(Z){if(Z===c4.reqSerializer)return Z;return function(Y){return Z(c4.reqSerializer(Y))}},wrapResponseSerializer:function(Z){if(Z===i4.resSerializer)return Z;return function(Y){return Z(i4.resSerializer(Y))}}}});var WB=S((nf0,oP)=>{function i$0($,Z){return Z}oP.exports=function(){let Z=Error.prepareStackTrace;Error.prepareStackTrace=i$0;let J=Error().stack;if(Error.prepareStackTrace=Z,!Array.isArray(J))return;let Y=J.slice(2),X=[];for(let Q of Y){if(!Q)continue;X.push(Q.getFileName())}return X}});var $I=S((of0,eP)=>{function KB($){if($===null||typeof $!=="object")return $;if($ instanceof Date)return new Date($.getTime());if($ instanceof Array){let Z=[];for(let J=0;J<$.length;J++)Z[J]=KB($[J]);return Z}if(typeof $==="object"){let Z=Object.create(Object.getPrototypeOf($));for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))Z[J]=KB($[J]);return Z}return $}function sP($){let Z=[],J="",Y=!1,X=!1,Q="";for(let G=0;G<$.length;G++){let W=$[G];if(!Y&&W==="."){if(J)Z.push(J),J=""}else if(W==="["){if(J)Z.push(J),J="";Y=!0}else if(W==="]"&&Y)Z.push(J),J="",Y=!1,X=!1;else if((W==='"'||W==="'")&&Y)if(!X)X=!0,Q=W;else if(W===Q)X=!1,Q="";else J+=W;else J+=W}if(J)Z.push(J);return Z}function rP($,Z,J){let Y=$;for(let Q=0;Q<Z.length-1;Q++){let G=Z[Q];if(typeof Y!=="object"||Y===null||!(G in Y))return!1;if(typeof Y[G]!=="object"||Y[G]===null)return!1;Y=Y[G]}let X=Z[Z.length-1];if(X==="*"){if(Array.isArray(Y))for(let Q=0;Q<Y.length;Q++)Y[Q]=J;else if(typeof Y==="object"&&Y!==null){for(let Q in Y)if(Object.prototype.hasOwnProperty.call(Y,Q))Y[Q]=J}}else if(typeof Y==="object"&&Y!==null&&X in Y&&Object.prototype.hasOwnProperty.call(Y,X))Y[X]=J;return!0}function aP($,Z){let J=$;for(let X=0;X<Z.length-1;X++){let Q=Z[X];if(typeof J!=="object"||J===null||!(Q in J))return!1;if(typeof J[Q]!=="object"||J[Q]===null)return!1;J=J[Q]}let Y=Z[Z.length-1];if(Y==="*"){if(Array.isArray(J))for(let X=0;X<J.length;X++)J[X]=void 0;else if(typeof J==="object"&&J!==null){for(let X in J)if(Object.prototype.hasOwnProperty.call(J,X))delete J[X]}}else if(typeof J==="object"&&J!==null&&Y in J&&Object.prototype.hasOwnProperty.call(J,Y))delete J[Y];return!0}var n4=Symbol("PATH_NOT_FOUND");function n$0($,Z){let J=$;for(let Y of Z){if(J===null||J===void 0)return n4;if(typeof J!=="object"||J===null)return n4;if(!(Y in J))return n4;J=J[Y]}return J}function o$0($,Z){let J=$;for(let Y of Z){if(J===null||J===void 0)return;if(typeof J!=="object"||J===null)return;J=J[Y]}return J}function s$0($,Z,J,Y=!1){for(let X of Z){let Q=sP(X);if(Q.includes("*"))tP($,Q,J,X,Y);else if(Y)aP($,Q);else{let G=n$0($,Q);if(G===n4)continue;let W=typeof J==="function"?J(G,Q):J;rP($,Q,W)}}}function tP($,Z,J,Y,X=!1){let Q=Z.indexOf("*");if(Q===Z.length-1){let G=Z.slice(0,-1),W=$;for(let K of G){if(W===null||W===void 0)return;if(typeof W!=="object"||W===null)return;W=W[K]}if(Array.isArray(W))if(X)for(let K=0;K<W.length;K++)W[K]=void 0;else for(let K=0;K<W.length;K++){let V=[...G,K.toString()],U=typeof J==="function"?J(W[K],V):J;W[K]=U}else if(typeof W==="object"&&W!==null)if(X){let K=[];for(let V in W)if(Object.prototype.hasOwnProperty.call(W,V))K.push(V);for(let V of K)delete W[V]}else for(let K in W){let V=[...G,K],U=typeof J==="function"?J(W[K],V):J;W[K]=U}}else r$0($,Z,J,Q,Y,X)}function r$0($,Z,J,Y,X,Q=!1){let G=Z.slice(0,Y),W=Z.slice(Y+1),K=[];function V(U,H){if(H===G.length){if(Array.isArray(U))for(let B=0;B<U.length;B++)K[H]=B.toString(),V(U[B],H+1);else if(typeof U==="object"&&U!==null)for(let B in U)K[H]=B,V(U[B],H+1)}else if(H<G.length){let B=G[H];if(U&&typeof U==="object"&&U!==null&&B in U)K[H]=B,V(U[B],H+1)}else if(W.includes("*"))tP(U,W,typeof J==="function"?(z,F)=>{let A=[...K.slice(0,H),...F];return J(z,A)}:J,X,Q);else if(Q)aP(U,W);else{let B=typeof J==="function"?J(o$0(U,W),[...K.slice(0,H),...W]):J;rP(U,W,B)}}if(G.length===0)V($,0);else{let U=$;for(let H=0;H<G.length;H++){let B=G[H];if(U===null||U===void 0)return;if(typeof U!=="object"||U===null)return;U=U[B],K[H]=B}if(U!==null&&U!==void 0)V(U,G.length)}}function a$0($){if($.length===0)return null;let Z=new Map;for(let J of $){let Y=sP(J),X=Z;for(let Q=0;Q<Y.length;Q++){let G=Y[Q];if(!X.has(G))X.set(G,new Map);X=X.get(G)}}return Z}function t$0($,Z){if(!Z)return $;function J(Y,X,Q=0){if(!X||X.size===0)return Y;if(Y===null||typeof Y!=="object")return Y;if(Y instanceof Date)return new Date(Y.getTime());if(Array.isArray(Y)){let W=[];for(let K=0;K<Y.length;K++){let V=K.toString();if(X.has(V)||X.has("*"))W[K]=J(Y[K],X.get(V)||X.get("*"));else W[K]=Y[K]}return W}let G=Object.create(Object.getPrototypeOf(Y));for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))if(X.has(W)||X.has("*"))G[W]=J(Y[W],X.get(W)||X.get("*"));else G[W]=Y[W];return G}return J($,Z)}function e$0($){if(typeof $!=="string")throw Error("Paths must be (non-empty) strings");if($==="")throw Error("Invalid redaction path ()");if($.includes(".."))throw Error(`Invalid redaction path (${$})`);if($.includes(","))throw Error(`Invalid redaction path (${$})`);let Z=0,J=!1,Y="";for(let X=0;X<$.length;X++){let Q=$[X];if((Q==='"'||Q==="'")&&Z>0){if(!J)J=!0,Y=Q;else if(Q===Y)J=!1,Y=""}else if(Q==="["&&!J)Z++;else if(Q==="]"&&!J){if(Z--,Z<0)throw Error(`Invalid redaction path (${$})`)}}if(Z!==0)throw Error(`Invalid redaction path (${$})`)}function $80($){if(!Array.isArray($))throw TypeError("paths must be an array");for(let Z of $)e$0(Z)}function Z80($={}){let{paths:Z=[],censor:J="[REDACTED]",serialize:Y=JSON.stringify,strict:X=!0,remove:Q=!1}=$;$80(Z);let G=a$0(Z);return function(K){if(X&&(K===null||typeof K!=="object")){if(K===null||K===void 0)return Y?Y(K):K;if(typeof K!=="object")return Y?Y(K):K}let V=t$0(K,G),U=K,H=J;if(typeof J==="function")H=J;if(s$0(V,Z,H,Q),Y===!1)return V.restore=function(){return KB(U)},V;if(typeof Y==="function")return Y(V);return JSON.stringify(V)}}eP.exports=Z80});var PJ=S((sf0,ZI)=>{var J80=Symbol("pino.setLevel"),Y80=Symbol("pino.getLevel"),X80=Symbol("pino.levelVal"),Q80=Symbol("pino.levelComp"),G80=Symbol("pino.useLevelLabels"),W80=Symbol("pino.useOnlyCustomLevels"),K80=Symbol("pino.mixin"),V80=Symbol("pino.lsCache"),U80=Symbol("pino.chindings"),H80=Symbol("pino.asJson"),B80=Symbol("pino.write"),z80=Symbol("pino.redactFmt"),F80=Symbol("pino.time"),A80=Symbol("pino.timeSliceIndex"),O80=Symbol("pino.stream"),q80=Symbol("pino.stringify"),j80=Symbol("pino.stringifySafe"),N80=Symbol("pino.stringifiers"),M80=Symbol("pino.end"),D80=Symbol("pino.formatOpts"),w80=Symbol("pino.messageKey"),L80=Symbol("pino.errorKey"),T80=Symbol("pino.nestedKey"),R80=Symbol("pino.nestedKeyStr"),P80=Symbol("pino.mixinMergeStrategy"),I80=Symbol("pino.msgPrefix"),C80=Symbol("pino.wildcardFirst"),E80=Symbol.for("pino.serializers"),b80=Symbol.for("pino.formatters"),_80=Symbol.for("pino.hooks"),S80=Symbol.for("pino.metadata");ZI.exports={setLevelSym:J80,getLevelSym:Y80,levelValSym:X80,levelCompSym:Q80,useLevelLabelsSym:G80,mixinSym:K80,lsCacheSym:V80,chindingsSym:U80,asJsonSym:H80,writeSym:B80,serializersSym:E80,redactFmtSym:z80,timeSym:F80,timeSliceIndexSym:A80,streamSym:O80,stringifySym:q80,stringifySafeSym:j80,stringifiersSym:N80,endSym:M80,formatOptsSym:D80,messageKeySym:w80,errorKeySym:L80,nestedKeySym:T80,wildcardFirstSym:C80,needsMetadataGsym:S80,useOnlyCustomLevelsSym:W80,formattersSym:b80,hooksSym:_80,nestedKeyStrSym:R80,mixinMergeStrategySym:P80,msgPrefixSym:I80}});var UB=S((rf0,YI)=>{var JI=$I(),{redactFmtSym:f80,wildcardFirstSym:o4}=PJ(),VB=/[^.[\]]+|\[([^[\]]*?)\]/g;function k80($,Z){let{paths:J,censor:Y,remove:X}=v80($),Q=J.reduce((K,V)=>{VB.lastIndex=0;let U=VB.exec(V),H=VB.exec(V),B=U[1]!==void 0?U[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):U[0];if(B==="*")B=o4;if(H===null)return K[B]=null,K;if(K[B]===null)return K;let{index:z}=H,F=`${V.substr(z,V.length-1)}`;if(K[B]=K[B]||[],B!==o4&&K[B].length===0)K[B].push(...K[o4]||[]);if(B===o4)Object.keys(K).forEach(function(A){if(K[A])K[A].push(F)});return K[B].push(F),K},{}),G={[f80]:JI({paths:J,censor:Y,serialize:Z,strict:!1,remove:X})},W=(...K)=>{return typeof Y==="function"?Z(Y(...K)):Z(Y)};return[...Object.keys(Q),...Object.getOwnPropertySymbols(Q)].reduce((K,V)=>{if(Q[V]===null)K[V]=(U)=>W(U,[V]);else{let U=typeof Y==="function"?(H,B)=>{return Y(H,[V,...B])}:Y;K[V]=JI({paths:Q[V],censor:U,serialize:Z,strict:!1,remove:X})}return K},G)}function v80($){if(Array.isArray($))return $={paths:$,censor:"[Redacted]"},$;let{paths:Z,censor:J="[Redacted]",remove:Y}=$;if(Array.isArray(Z)===!1)throw Error("pino \u2013 redact must contain an array of strings");if(Y===!0)J=void 0;return{paths:Z,censor:J,remove:Y}}YI.exports=k80});var GI=S((af0,QI)=>{var y80=()=>"",x80=()=>`,"time":${Date.now()}`,h80=()=>`,"time":${Math.round(Date.now()/1000)}`,g80=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,u80=1000000n,XI=1000000000n,m80=BigInt(Date.now())*u80,l80=process.hrtime.bigint(),d80=()=>{let $=process.hrtime.bigint()-l80,Z=m80+$,J=Z/XI,Y=Z%XI,X=Number(J*1000n+Y/1000000n),Q=new Date(X),G=Q.getUTCFullYear(),W=(Q.getUTCMonth()+1).toString().padStart(2,"0"),K=Q.getUTCDate().toString().padStart(2,"0"),V=Q.getUTCHours().toString().padStart(2,"0"),U=Q.getUTCMinutes().toString().padStart(2,"0"),H=Q.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${G}-${W}-${K}T${V}:${U}:${H}.${Y.toString().padStart(9,"0")}Z"`};QI.exports={nullTime:y80,epochTime:x80,unixTime:h80,isoTime:g80,isoTimeNano:d80}});var KI=S((tf0,WI)=>{function p80($){try{return JSON.stringify($)}catch(Z){return'"[Circular]"'}}WI.exports=c80;function c80($,Z,J){var Y=J&&J.stringify||p80,X=1;if(typeof $==="object"&&$!==null){var Q=Z.length+X;if(Q===1)return $;var G=Array(Q);G[0]=Y($);for(var W=1;W<Q;W++)G[W]=Y(Z[W]);return G.join(" ")}if(typeof $!=="string")return $;var K=Z.length;if(K===0)return $;var V="",U=1-X,H=-1,B=$&&$.length||0;for(var z=0;z<B;){if($.charCodeAt(z)===37&&z+1<B){switch(H=H>-1?H:0,$.charCodeAt(z+1)){case 100:case 102:if(U>=K)break;if(Z[U]==null)break;if(H<z)V+=$.slice(H,z);V+=Number(Z[U]),H=z+2,z++;break;case 105:if(U>=K)break;if(Z[U]==null)break;if(H<z)V+=$.slice(H,z);V+=Math.floor(Number(Z[U])),H=z+2,z++;break;case 79:case 111:case 106:if(U>=K)break;if(Z[U]===void 0)break;if(H<z)V+=$.slice(H,z);var F=typeof Z[U];if(F==="string"){V+="'"+Z[U]+"'",H=z+2,z++;break}if(F==="function"){V+=Z[U].name||"<anonymous>",H=z+2,z++;break}V+=Y(Z[U]),H=z+2,z++;break;case 115:if(U>=K)break;if(H<z)V+=$.slice(H,z);V+=String(Z[U]),H=z+2,z++;break;case 37:if(H<z)V+=$.slice(H,z);V+="%",H=z+2,z++,U--;break}++U}++z}if(H===-1)return $;else if(H<B)V+=$.slice(H);return V}});var BB=S((ef0,HB)=>{if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let Z=function(J){if((J>0&&J<1/0)===!1){if(typeof J!=="number"&&typeof J!=="bigint")throw TypeError("sleep: ms must be a number");throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity")}Atomics.wait($,0,0,Number(J))},$=new Int32Array(new SharedArrayBuffer(4));HB.exports=Z}else{let $=function(Z){if((Z>0&&Z<1/0)===!1){if(typeof Z!=="number"&&typeof Z!=="bigint")throw TypeError("sleep: ms must be a number");throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity")}let Y=Date.now()+Number(Z);while(Y>Date.now());};HB.exports=$}});var FI=S(($k0,zI)=>{var p1=Y0("fs"),i80=Y0("events"),n80=Y0("util").inherits,VI=Y0("path"),FB=BB(),o80=Y0("assert"),s4=Buffer.allocUnsafe(0),[s80,r80]=(process.versions.node||"0.0").split(".").map(Number),a80=s80>=22&&r80>=7;function UI($,Z){Z._opening=!0,Z._writing=!0,Z._asyncDrainScheduled=!1;function J(Q,G){if(Q){if(Z._reopening=!1,Z._writing=!1,Z._opening=!1,Z.sync)process.nextTick(()=>{if(Z.listenerCount("error")>0)Z.emit("error",Q)});else Z.emit("error",Q);return}let W=Z._reopening;if(Z.fd=G,Z.file=$,Z._reopening=!1,Z._opening=!1,Z._writing=!1,Z.sync)process.nextTick(()=>Z.emit("ready"));else Z.emit("ready");if(Z.destroyed)return;if(!Z._writing&&Z._len>Z.minLength||Z._flushPending)Z._actualWrite();else if(W)process.nextTick(()=>Z.emit("drain"))}let Y=Z.append?"a":"w",X=Z.mode;if(Z.sync)try{if(Z.mkdir)p1.mkdirSync(VI.dirname($),{recursive:!0});let Q=p1.openSync($,Y,X);J(null,Q)}catch(Q){throw J(Q),Q}else if(Z.mkdir)p1.mkdir(VI.dirname($),{recursive:!0},(Q)=>{if(Q)return J(Q);p1.open($,Y,X,J)});else p1.open($,Y,X,J)}function e8($){if(!(this instanceof e8))return new e8($);let{fd:Z,dest:J,minLength:Y,maxLength:X,maxWrite:Q,periodicFlush:G,sync:W,append:K=!0,mkdir:V,retryEAGAIN:U,fsync:H,contentMode:B,mode:z}=$||{};Z=Z||J,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(Y||0,16387),this.file=null,this.destroyed=!1,this.minLength=Y||0,this.maxLength=X||0,this.maxWrite=Q||16384,this._periodicFlush=G||0,this._periodicFlushTimer=void 0,this.sync=W||!1,this.writable=!0,this._fsync=H||!1,this.append=K||!1,this.mode=z,this.retryEAGAIN=U||(()=>!0),this.mkdir=V||!1;let F,A;if(B==="buffer")this._writingBuf=s4,this.write=$60,this.flush=J60,this.flushSync=X60,this._actualWrite=G60,F=()=>p1.writeSync(this.fd,this._writingBuf),A=()=>p1.write(this.fd,this._writingBuf,this.release);else if(B===void 0||B==="utf8")this._writingBuf="",this.write=e80,this.flush=Z60,this.flushSync=Y60,this._actualWrite=Q60,F=()=>{if(Buffer.isBuffer(this._writingBuf))return p1.writeSync(this.fd,this._writingBuf);return p1.writeSync(this.fd,this._writingBuf,"utf8")},A=()=>{if(Buffer.isBuffer(this._writingBuf))return p1.write(this.fd,this._writingBuf,this.release);return p1.write(this.fd,this._writingBuf,"utf8",this.release)};else throw Error(`SonicBoom supports "utf8" and "buffer", but passed ${B}`);if(typeof Z==="number")this.fd=Z,process.nextTick(()=>this.emit("ready"));else if(typeof Z==="string")UI(Z,this);else throw Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);if(this.release=(j,N)=>{if(j){if((j.code==="EAGAIN"||j.code==="EBUSY")&&this.retryEAGAIN(j,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{FB(100),this.release(void 0,0)}catch(M){this.release(M)}else setTimeout(A,100);else this._writing=!1,this.emit("error",j);return}this.emit("write",N);let L=zB(this._writingBuf,this._len,N);if(this._len=L.len,this._writingBuf=L.writingBuf,this._writingBuf.length){if(!this.sync){A();return}try{do{let M=F(),C=zB(this._writingBuf,this._len,M);this._len=C.len,this._writingBuf=C.writingBuf}while(this._writingBuf.length)}catch(M){this.release(M);return}}if(this._fsync)p1.fsyncSync(this.fd);let q=this._len;if(this._reopening)this._writing=!1,this._reopening=!1,this.reopen();else if(q>this.minLength)this._actualWrite();else if(this._ending)if(q>0)this._actualWrite();else this._writing=!1,r4(this);else if(this._writing=!1,this.sync){if(!this._asyncDrainScheduled)this._asyncDrainScheduled=!0,process.nextTick(t80,this)}else this.emit("drain")},this.on("newListener",function(j){if(j==="drain")this._asyncDrainScheduled=!1}),this._periodicFlush!==0)this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref()}function zB($,Z,J){if(typeof $==="string")$=Buffer.from($);return Z=Math.max(Z-J,0),$=$.subarray(J),{writingBuf:$,len:Z}}function t80($){if(!($.listenerCount("drain")>0))return;$._asyncDrainScheduled=!1,$.emit("drain")}n80(e8,i80);function HI($,Z){if($.length===0)return s4;if($.length===1)return $[0];return Buffer.concat($,Z)}function e80($){if(this.destroyed)throw Error("SonicBoom destroyed");$=""+$;let Z=Buffer.byteLength($),J=this._len+Z,Y=this._bufs;if(this.maxLength&&J>this.maxLength)return this.emit("drop",$),this._len<this._hwm;if(Y.length===0||Buffer.byteLength(Y[Y.length-1])+Z>this.maxWrite)Y.push($);else Y[Y.length-1]+=$;if(this._len=J,!this._writing&&this._len>=this.minLength)this._actualWrite();return this._len<this._hwm}function $60($){if(this.destroyed)throw Error("SonicBoom destroyed");let Z=this._len+$.length,J=this._bufs,Y=this._lens;if(this.maxLength&&Z>this.maxLength)return this.emit("drop",$),this._len<this._hwm;if(J.length===0||Y[Y.length-1]+$.length>this.maxWrite)J.push([$]),Y.push($.length);else J[J.length-1].push($),Y[Y.length-1]+=$.length;if(this._len=Z,!this._writing&&this._len>=this.minLength)this._actualWrite();return this._len<this._hwm}function BI($){this._flushPending=!0;let Z=()=>{if(!this._fsync)try{p1.fsync(this.fd,(Y)=>{this._flushPending=!1,$(Y)})}catch(Y){$(Y)}else this._flushPending=!1,$();this.off("error",J)},J=(Y)=>{this._flushPending=!1,$(Y),this.off("drain",Z)};this.once("drain",Z),this.once("error",J)}function Z60($){if($!=null&&typeof $!=="function")throw Error("flush cb must be a function");if(this.destroyed){let Z=Error("SonicBoom destroyed");if($){$(Z);return}throw Z}if(this.minLength<=0){$?.();return}if($)BI.call(this,$);if(this._writing)return;if(this._bufs.length===0)this._bufs.push("");this._actualWrite()}function J60($){if($!=null&&typeof $!=="function")throw Error("flush cb must be a function");if(this.destroyed){let Z=Error("SonicBoom destroyed");if($){$(Z);return}throw Z}if(this.minLength<=0){$?.();return}if($)BI.call(this,$);if(this._writing)return;if(this._bufs.length===0)this._bufs.push([]),this._lens.push(0);this._actualWrite()}e8.prototype.reopen=function($){if(this.destroyed)throw Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen($)});return}if(this._ending)return;if(!this.file)throw Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if($)this.file=$;if(this._reopening=!0,this._writing)return;let Z=this.fd;this.once("ready",()=>{if(Z!==this.fd)p1.close(Z,(J)=>{if(J)return this.emit("error",J)})}),UI(this.file,this)};e8.prototype.end=function(){if(this.destroyed)throw Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}if(this._ending)return;if(this._ending=!0,this._writing)return;if(this._len>0&&this.fd>=0)this._actualWrite();else r4(this)};function Y60(){if(this.destroyed)throw Error("SonicBoom destroyed");if(this.fd<0)throw Error("sonic boom is not ready yet");if(!this._writing&&this._writingBuf.length>0)this._bufs.unshift(this._writingBuf),this._writingBuf="";let $="";while(this._bufs.length||$.length){if($.length<=0)$=this._bufs[0];try{let Z=Buffer.isBuffer($)?p1.writeSync(this.fd,$):p1.writeSync(this.fd,$,"utf8"),J=zB($,this._len,Z);if($=J.writingBuf,this._len=J.len,$.length<=0)this._bufs.shift()}catch(Z){if((Z.code==="EAGAIN"||Z.code==="EBUSY")&&!this.retryEAGAIN(Z,$.length,this._len-$.length))throw Z;FB(100)}}try{p1.fsyncSync(this.fd)}catch{}}function X60(){if(this.destroyed)throw Error("SonicBoom destroyed");if(this.fd<0)throw Error("sonic boom is not ready yet");if(!this._writing&&this._writingBuf.length>0)this._bufs.unshift([this._writingBuf]),this._writingBuf=s4;let $=s4;while(this._bufs.length||$.length){if($.length<=0)$=HI(this._bufs[0],this._lens[0]);try{let Z=p1.writeSync(this.fd,$);if($=$.subarray(Z),this._len=Math.max(this._len-Z,0),$.length<=0)this._bufs.shift(),this._lens.shift()}catch(Z){if((Z.code==="EAGAIN"||Z.code==="EBUSY")&&!this.retryEAGAIN(Z,$.length,this._len-$.length))throw Z;FB(100)}}}e8.prototype.destroy=function(){if(this.destroyed)return;r4(this)};function Q60(){let $=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let Z=Buffer.isBuffer(this._writingBuf)?p1.writeSync(this.fd,this._writingBuf):p1.writeSync(this.fd,this._writingBuf,"utf8");$(null,Z)}catch(Z){$(Z)}else p1.write(this.fd,this._writingBuf,$)}function G60(){let $=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:HI(this._bufs.shift(),this._lens.shift()),this.sync)try{let Z=p1.writeSync(this.fd,this._writingBuf);$(null,Z)}catch(Z){$(Z)}else{if(a80)this._writingBuf=Buffer.from(this._writingBuf);p1.write(this.fd,this._writingBuf,$)}}function r4($){if($.fd===-1){$.once("ready",r4.bind(null,$));return}if($._periodicFlushTimer!==void 0)clearInterval($._periodicFlushTimer);$.destroyed=!0,$._bufs=[],$._lens=[],o80(typeof $.fd==="number",`sonic.fd must be a number, got ${typeof $.fd}`);try{p1.fsync($.fd,Z)}catch{}function Z(){if($.fd!==1&&$.fd!==2)p1.close($.fd,J);else J()}function J(Y){if(Y){$.emit("error",Y);return}if($._ending&&!$._writing)$.emit("finish");$.emit("close")}}e8.SonicBoom=e8;e8.default=e8;zI.exports=e8});var AB=S((Zk0,NI)=>{var $6={exit:[],beforeExit:[]},AI={exit:V60,beforeExit:U60},IJ;function W60(){if(IJ===void 0)IJ=new FinalizationRegistry(H60)}function K60($){if($6[$].length>0)return;process.on($,AI[$])}function OI($){if($6[$].length>0)return;if(process.removeListener($,AI[$]),$6.exit.length===0&&$6.beforeExit.length===0)IJ=void 0}function V60(){qI("exit")}function U60(){qI("beforeExit")}function qI($){for(let Z of $6[$]){let J=Z.deref(),Y=Z.fn;if(J!==void 0)Y(J,$)}$6[$]=[]}function H60($){for(let Z of["exit","beforeExit"]){let J=$6[Z].indexOf($);$6[Z].splice(J,J+1),OI(Z)}}function jI($,Z,J){if(Z===void 0)throw Error("the object can't be undefined");K60($);let Y=new WeakRef(Z);Y.fn=J,W60(),IJ.register(Z,Y),$6[$].push(Y)}function B60($,Z){jI("exit",$,Z)}function z60($,Z){jI("beforeExit",$,Z)}function F60($){if(IJ===void 0)return;IJ.unregister($);for(let Z of["exit","beforeExit"])$6[Z]=$6[Z].filter((J)=>{let Y=J.deref();return Y&&Y!==$}),OI(Z)}NI.exports={register:B60,registerBeforeExit:z60,unregister:F60}});var MI=S((Jk0,A60)=>{A60.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var wI=S((Yk0,DI)=>{function O60($,Z,J,Y,X){let Q=Y===1/0?1/0:Date.now()+Y,G=()=>{let W=Atomics.load($,Z);if(W===J){X(null,"ok");return}if(Q!==1/0&&Date.now()>Q){X(null,"timed-out");return}let K=Q===1/0?1e4:Math.min(1e4,Math.max(1,Q-Date.now())),V=Atomics.waitAsync($,Z,W,K);if(V.async)V.value.then(G);else setImmediate(G)};G()}function q60($,Z,J,Y,X){let Q=Y===1/0?1/0:Date.now()+Y,G=()=>{if(Atomics.load($,Z)!==J){X(null,"ok");return}if(Q!==1/0&&Date.now()>Q){X(null,"timed-out");return}let K=Q===1/0?1e4:Math.min(1e4,Math.max(1,Q-Date.now())),V=Atomics.waitAsync($,Z,J,K);if(V.async)V.value.then((U)=>{if(U==="ok"){X(null,"ok");return}G()});else setImmediate(G)};G()}DI.exports={wait:O60,waitDiff:q60}});var TI=S((Xk0,LI)=>{LI.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var xI=S((Qk0,yI)=>{var __dirname="/home/runner/workspace/products/qitqode/qode/node_modules/.bun/thread-stream@4.2.0/node_modules/thread-stream",{version:j60}=MI(),{EventEmitter:N60}=Y0("events"),{Worker:M60}=Y0("worker_threads"),{join:D60}=Y0("path"),{pathToFileURL:w60}=Y0("url"),{wait:L60}=wI(),{WRITE_INDEX:t6,READ_INDEX:i5,SEQ_INDEX:OB}=TI(),T60=Y0("buffer"),R60=Y0("assert"),s=Symbol("kImpl"),P60=T60.constants.MAX_STRING_LENGTH;function RI(){}function MB($,Z){Atomics.add($[s].state,OB,1),Z(),Atomics.add($[s].state,OB,1),Atomics.notify($[s].state,OB)}function PI($){MB($,()=>{Atomics.store($[s].state,i5,0),Atomics.store($[s].state,t6,0)})}class a4{constructor($){this._value=$}deref(){return this._value}}class jB{register(){}unregister(){}}var I60=process.env.NODE_V8_COVERAGE?jB:global.FinalizationRegistry||jB,C60=process.env.NODE_V8_COVERAGE?a4:global.WeakRef||a4,II=new I60(($)=>{if($.exited)return;$.terminate()});function E60($,Z){let{filename:J,workerData:Y}=Z,Q=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||D60(__dirname,"lib","worker.js"),G=new M60(Q,{...Z.workerOpts,name:Z.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:J.indexOf("file://")===0?J:w60(J).href,dataBuf:$[s].dataBuf,stateBuf:$[s].stateBuf,workerData:{$context:{threadStreamVersion:j60},...Y}}});return G.stream=new a4($),G.on("message",b60),G.on("exit",bI),II.register($,G),G}function CI($){if(R60(!$[s].sync),$[s].needDrain)$[s].needDrain=!1,$.emit("drain")}function EI($){while(!0){let Z=Atomics.load($[s].state,t6),J=$[s].data.length-Z;if(J>0){if($[s].bufLen===0){if($[s].flushing=!1,$[s].ending)DB($);else if($[s].needDrain)process.nextTick(CI,$);return}kI($,J,RI);continue}if(J===0){if(Z===0&&$[s].bufLen===0)return;t4($,()=>{if($.destroyed)return;PI($),EI($)});return}x8($,Error("overwritten"));return}}function b60($){let Z=this.stream.deref();if(Z===void 0){this.exited=!0,this.terminate();return}if($?.code==null)return;switch($.code){case"READY":this.stream=new C60(Z),t4(Z,()=>{Z[s].ready=!0,Z.emit("ready")});break;case"ERROR":x8(Z,$.err);break;case"EVENT":if(Array.isArray($.args))Z.emit($.name,...$.args);else Z.emit($.name,$.args);break;case"FLUSHED":{if($.context!=="thread-stream"){x8(Z,Error("this should not happen: "+$.code));break}let J=Z[s].flushCallbacks.get($.id);if(J)Z[s].flushCallbacks.delete($.id),process.nextTick(J);break}case"WARNING":process.emitWarning($.err);break;default:x8(Z,Error("this should not happen: "+$.code))}}function bI($){let Z=this.stream.deref();if(Z===void 0)return;II.unregister(Z),Z.worker.exited=!0,Z.worker.off("exit",bI),x8(Z,$!==0?Error("the worker thread exited"):null)}class _I extends N60{constructor($={}){super();if($.bufferSize<4)throw Error("bufferSize must at least fit a 4-byte utf-8 char");this[s]={},this[s].stateBuf=new SharedArrayBuffer(128),this[s].state=new Int32Array(this[s].stateBuf),this[s].dataBuf=new SharedArrayBuffer($.bufferSize||4194304),this[s].data=Buffer.from(this[s].dataBuf),this[s].sync=$.sync||!1,this[s].ending=!1,this[s].ended=!1,this[s].needDrain=!1,this[s].destroyed=!1,this[s].flushing=!1,this[s].ready=!1,this[s].finished=!1,this[s].errored=null,this[s].closed=!1,this[s].buf=[],this[s].bufHead=0,this[s].bufLen=0,this[s].flushCallbacks=new Map,this[s].nextFlushId=0,this.worker=E60(this,$),this.on("message",(Z,J)=>{this.worker.postMessage(Z,J)})}write($){let Z=Buffer.isBuffer($)?$:Buffer.from($);if(this[s].destroyed)return NB(this,Error("the worker has exited")),!1;if(this[s].ending)return NB(this,Error("the worker is ending")),!1;if(this[s].flushing&&this[s].bufLen+Z.length>=P60)try{qB(this),this[s].flushing=!0}catch(J){return x8(this,J),!1}if(this[s].buf.push(Z),this[s].bufLen+=Z.length,this[s].sync)try{return qB(this),!0}catch(J){return x8(this,J),!1}if(!this[s].flushing)this[s].flushing=!0,setImmediate(EI,this);return this[s].needDrain=this[s].data.length-this[s].bufLen-Atomics.load(this[s].state,t6)<=0,!this[s].needDrain}end(){if(this[s].destroyed)return;this[s].ending=!0,DB(this)}flush($){$=typeof $==="function"?$:RI,SI(this,(Z)=>{if(Z){process.nextTick($,Z);return}fI(this,$)})}flushSync(){if(this[s].destroyed)return;qB(this),vI(this)}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[s].ready}get destroyed(){return this[s].destroyed}get closed(){return this[s].closed}get writable(){return!this[s].destroyed&&!this[s].ending}get writableEnded(){return this[s].ending}get writableFinished(){return this[s].finished}get writableNeedDrain(){return this[s].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[s].errored}}function SI($,Z){if($[s].destroyed){process.nextTick(Z,Error("the worker has exited"));return}if(!$[s].sync&&($[s].flushing||$[s].bufLen>0)){setImmediate(SI,$,Z);return}t4($,Z)}function t4($,Z){let J=Atomics.load($[s].state,t6);L60($[s].state,i5,J,1/0,(Y,X)=>{if(Y){x8($,Y),Z(Y);return}if(X!=="ok"){t4($,Z);return}Z()})}function fI($,Z){if($[s].destroyed){process.nextTick(Z,Error("the worker has exited"));return}if(!$[s].ready){let Y=()=>{Q(),fI($,Z)},X=()=>{Q(),process.nextTick(Z,Error("the worker has exited"))},Q=()=>{$.off("ready",Y),$.off("close",X)};$.once("ready",Y),$.once("close",X);return}let J=++$[s].nextFlushId;$[s].flushCallbacks.set(J,Z);try{$.worker.postMessage({code:"FLUSH",context:"thread-stream",id:J})}catch(Y){$[s].flushCallbacks.delete(J),x8($,Y),process.nextTick(Z,Y)}}function _60($,Z){let J=$[s].flushCallbacks;if(J.size===0)return;let Y=Z||Error("the worker has exited");for(let X of J.values())process.nextTick(X,Y);J.clear()}function NB($,Z){setImmediate(()=>{$.emit("error",Z)})}function x8($,Z){if($[s].destroyed)return;if($[s].destroyed=!0,_60($,Z),Z)$[s].errored=Z,NB($,Z);if(!$.worker.exited)$.worker.terminate().catch(()=>{}).then(()=>{$[s].closed=!0,$.emit("close")});else setImmediate(()=>{$[s].closed=!0,$.emit("close")})}function kI($,Z,J){let X=Atomics.load($[s].state,t6),Q=Z;while(Q>0&&$[s].bufLen!==0){let G=$[s].bufHead,W=$[s].buf[G];if(W.length<=Q){if(W.copy($[s].data,X),X+=W.length,Q-=W.length,$[s].bufLen-=W.length,$[s].bufHead=G+1,$[s].bufHead===$[s].buf.length)$[s].buf.length=0,$[s].bufHead=0;else if($[s].bufHead>=1024&&$[s].bufHead*2>=$[s].buf.length)$[s].buf.splice(0,$[s].bufHead),$[s].bufHead=0;continue}W.copy($[s].data,X,0,Q),$[s].buf[G]=W.subarray(Q),$[s].bufLen-=Q,X+=Q,Q=0}return MB($,()=>{Atomics.store($[s].state,t6,X)}),J(),!0}function DB($){if($[s].ended||!$[s].ending||$[s].flushing)return;$[s].ended=!0;try{$.flushSync();let Z=Atomics.load($[s].state,i5);MB($,()=>{Atomics.store($[s].state,t6,-1)});let J=0;while(Z!==-1){if(Atomics.wait($[s].state,i5,Z,1000),Z=Atomics.load($[s].state,i5),Z===-2){x8($,Error("end() failed"));return}if(++J===10){x8($,Error("end() took too long (10s)"));return}}process.nextTick(()=>{$[s].finished=!0,$.emit("finish")})}catch(Z){x8($,Z)}}function qB($){let Z=()=>{if($[s].ending)DB($);else if($[s].needDrain)process.nextTick(CI,$)};$[s].flushing=!1;while($[s].bufLen!==0){let J=Atomics.load($[s].state,t6),Y=$[s].data.length-J;if(Y===0){vI($),PI($);continue}else if(Y<0)throw Error("overwritten");kI($,Y,Z)}}function vI($){if($[s].flushing)throw Error("unable to flush while flushing");let Z=Atomics.load($[s].state,t6),J=0;while(!0){let Y=Atomics.load($[s].state,i5);if(Y===-2)throw Error("_flushSync failed");if(Y!==Z)Atomics.wait($[s].state,i5,Y,1000);else break;if(++J===10)throw Error("_flushSync took too long (10s)")}}yI.exports=_I});var TB=S((Gk0,uI)=>{var __dirname="/home/runner/workspace/products/qitqode/qode/node_modules/.bun/pino@10.3.1/node_modules/pino/lib",{createRequire:S60}=Y0("module"),{existsSync:f60}=Y0("fs"),k60=WB(),{join:wB,isAbsolute:gI,sep:v60}=Y0("path"),{fileURLToPath:y60}=Y0("url"),x60=BB(),LB=AB(),h60=xI();function g60($){LB.register($,p60),LB.registerBeforeExit($,c60),$.on("close",function(){LB.unregister($)})}function u60(){let $=process.execArgv;for(let Z=0;Z<$.length;Z++){let J=$[Z];if(J==="--import"||J==="--require"||J==="-r")return!0;if(J.startsWith("--import=")||J.startsWith("--require=")||J.startsWith("-r="))return!0}return!1}function m60($){let Z=$.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!Z)return $;let J=[],Y=!1;for(let X=0;X<Z.length;X++){let Q=Z[X];if(Q==="--require"||Q==="-r"||Q==="--import"){let G=Z[X+1];if(G&&hI(G)){Y=!0,X++;continue}if(J.push(Q),G)J.push(G),X++;continue}if(Q.startsWith("--require=")||Q.startsWith("-r=")||Q.startsWith("--import=")){let G=Q.slice(Q.indexOf("=")+1);if(hI(G)){Y=!0;continue}}J.push(Q)}return Y?J.join(" "):$}function hI($){let Z=l60($);if(!Z)return!1;let J=Z;if(J.startsWith("file://"))try{J=y60(J)}catch{return!1}return gI(J)&&!f60(J)}function l60($){let Z=$[0],J=$[$.length-1];if(Z==='"'&&J==='"'||Z==="'"&&J==="'")return $.slice(1,-1);return $}function d60($,Z,J,Y,X){if(!J.execArgv&&u60()&&Y0.main===void 0)J={...J,execArgv:[]};if(!J.env&&process.env.NODE_OPTIONS){let K=m60(process.env.NODE_OPTIONS);if(K!==process.env.NODE_OPTIONS)J={...J,env:{...process.env,NODE_OPTIONS:K}}}J={...J,name:X};let Q=new h60({filename:$,workerData:Z,workerOpts:J,sync:Y});Q.on("ready",G),Q.on("close",function(){process.removeListener("exit",W)}),process.on("exit",W);function G(){if(process.removeListener("exit",W),Q.unref(),J.autoEnd!==!1)g60(Q)}function W(){if(Q.closed)return;Q.flushSync(),x60(100),Q.end()}return Q}function p60($){$.ref(),$.flushSync(),$.end(),$.once("close",function(){$.unref()})}function c60($){$.flushSync()}function i60($){let{pipeline:Z,targets:J,levels:Y,dedupe:X,worker:Q={},caller:G=k60(),sync:W=!1}=$,K={...$.options},V=typeof G==="string"?[G]:G,U=typeof globalThis==="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==="object"?globalThis.__bundlerPathsOverrides:Object.create(null),H=$.target;if(H&&J)throw Error("only one of target or targets can be specified");if(J)H=U["pino-worker"]||wB(__dirname,"worker.js"),K.targets=J.filter((F)=>F.target).map((F)=>{return{...F,target:z(F.target)}}),K.pipelines=J.filter((F)=>F.pipeline).map((F)=>{return F.pipeline.map((A)=>{return{...A,level:F.level,target:z(A.target)}})});else if(Z)H=U["pino-worker"]||wB(__dirname,"worker.js"),K.pipelines=[Z.map((F)=>{return{...F,target:z(F.target)}})];if(Y)K.levels=Y;if(X)K.dedupe=X;K.pinoWillSendConfig=!0;let B=J||Z?"pino.transport":H;return d60(z(H),K,Q,W,B);function z(F){if(F=U[F]||F,gI(F)||F.indexOf("file://")===0)return F;if(F==="pino/file")return wB(__dirname,"..","file.js");let A;for(let j of V)try{let N=j==="node:repl"?process.cwd()+v60:j;A=S60(N).resolve(F);break}catch(N){continue}if(!A)throw Error(`unable to determine transport target for "${F}"`);return A}}uI.exports=i60});var ZG=S((Kk0,eI)=>{var n60=Y0("diagnostics_channel"),mI=KI(),{mapHttpRequest:o60,mapHttpResponse:s60}=GB(),PB=FI(),lI=AB(),{lsCacheSym:r60,chindingsSym:nI,writeSym:dI,serializersSym:oI,formatOptsSym:pI,endSym:a60,stringifiersSym:sI,stringifySym:rI,stringifySafeSym:IB,wildcardFirstSym:aI,nestedKeySym:t60,formattersSym:tI,messageKeySym:e60,errorKeySym:$Z0,nestedKeyStrSym:ZZ0,msgPrefixSym:e4}=PJ(),{isMainThread:JZ0}=Y0("worker_threads"),YZ0=TB(),[XZ0]=process.versions.node.split(".").map(($)=>Number($)),cI=n60.tracingChannel("pino_asJson"),RB=XZ0>=25?($)=>JSON.stringify($):GZ0;function CJ(){}function QZ0($,Z){if(!Z)return J;return function(...X){Z.call(this,X,J,$)};function J(Y,...X){if(typeof Y==="object"){let Q=Y;if(Y!==null){if(Y.method&&Y.headers&&Y.socket)Y=o60(Y);else if(typeof Y.setHeader==="function")Y=s60(Y)}let G;if(Q===null&&X.length===0)G=[null];else Q=X.shift(),G=X;if(typeof this[e4]==="string"&&Q!==void 0&&Q!==null)Q=this[e4]+Q;this[dI](Y,mI(Q,G,this[pI]),$)}else{let Q=Y===void 0?X.shift():Y;if(typeof this[e4]==="string"&&Q!==void 0&&Q!==null)Q=this[e4]+Q;this[dI](null,mI(Q,X,this[pI]),$)}}}function GZ0($){let Z="",J=0,Y=!1,X=255,Q=$.length;if(Q>100)return JSON.stringify($);for(var G=0;G<Q&&X>=32;G++)if(X=$.charCodeAt(G),X===34||X===92)Z+=$.slice(J,G)+"\\",J=G,Y=!0;if(!Y)Z=$;else Z+=$.slice(J);return X<32?JSON.stringify($):'"'+Z+'"'}function WZ0($,Z,J,Y){if(cI.hasSubscribers===!1)return iI.call(this,$,Z,J,Y);let X={instance:this,arguments};return cI.traceSync(iI,X,this,$,Z,J,Y)}function iI($,Z,J,Y){let X=this[rI],Q=this[IB],G=this[sI],W=this[a60],K=this[nI],V=this[oI],U=this[tI],H=this[e60],B=this[$Z0],z=this[r60][J]+Y;z=z+K;let F;if(U.log)$=U.log($);let A=G[aI],j="";for(let L in $)if(F=$[L],Object.prototype.hasOwnProperty.call($,L)&&F!==void 0){if(V[L])F=V[L](F);else if(L===B&&V.err)F=V.err(F);let q=G[L]||A;switch(typeof F){case"undefined":case"function":continue;case"number":if(Number.isFinite(F)===!1)F=null;case"boolean":if(q)F=q(F);break;case"string":F=(q||RB)(F);break;default:F=(q||X)(F,Q)}if(F===void 0)continue;let M=RB(L);j+=","+M+":"+F}let N="";if(Z!==void 0){F=V[H]?V[H](Z):Z;let L=G[H]||A;switch(typeof F){case"function":break;case"number":if(Number.isFinite(F)===!1)F=null;case"boolean":if(L)F=L(F);N=',"'+H+'":'+F;break;case"string":F=(L||RB)(F),N=',"'+H+'":'+F;break;default:F=(L||X)(F,Q),N=',"'+H+'":'+F}}if(this[t60]&&j)return z+this[ZZ0]+j.slice(1)+"}"+N+W;else return z+j+N+W}function KZ0($,Z){let J,Y=$[nI],X=$[rI],Q=$[IB],G=$[sI],W=G[aI],K=$[oI],V=$[tI].bindings;Z=V(Z);for(let U in Z)if(J=Z[U],((U.length<5||U!=="level"&&U!=="serializers"&&U!=="formatters"&&U!=="customLevels")&&Z.hasOwnProperty(U)&&J!==void 0)===!0){if(J=K[U]?K[U](J):J,J=(G[U]||W||X)(J,Q),J===void 0)continue;Y+=',"'+U+'":'+J}return Y}function VZ0($){return $.write!==$.constructor.prototype.write}function $G($){let Z=new PB($);if(Z.on("error",J),!$.sync&&JZ0)lI.register(Z,UZ0),Z.on("close",function(){lI.unregister(Z)});return Z;function J(Y){if(Y.code==="EPIPE"){Z.write=CJ,Z.end=CJ,Z.flushSync=CJ,Z.destroy=CJ;return}Z.removeListener("error",J),Z.emit("error",Y)}}function UZ0($,Z){if($.destroyed)return;if(Z==="beforeExit")$.flush(),$.on("drain",function(){$.end()});else $.flushSync()}function HZ0($){return function(J,Y,X={},Q){if(typeof X==="string")Q=$G({dest:X}),X={};else if(typeof Q==="string"){if(X&&X.transport)throw Error("only one of option.transport or stream can be specified");Q=$G({dest:Q})}else if(X instanceof PB||X.writable||X._writableState)Q=X,X={};else if(X.transport){if(X.transport instanceof PB||X.transport.writable||X.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(X.transport.targets&&X.transport.targets.length&&X.formatters&&typeof X.formatters.level==="function")throw Error("option.transport.targets do not allow custom level formatters");let K;if(X.customLevels)K=X.useOnlyCustomLevels?X.customLevels:Object.assign({},X.levels,X.customLevels);Q=YZ0({caller:Y,...X.transport,levels:K})}if(X=Object.assign({},$,X),X.serializers=Object.assign({},$.serializers,X.serializers),X.formatters=Object.assign({},$.formatters,X.formatters),X.prettyPrint)throw Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:G,onChild:W}=X;if(G===!1)X.level="silent";if(!W)X.onChild=CJ;if(!Q)if(!VZ0(process.stdout))Q=$G({fd:process.stdout.fd||1});else Q=process.stdout;return{opts:X,stream:Q}}}function BZ0($,Z){try{return JSON.stringify($)}catch(J){try{return(Z||this[IB])($)}catch(Y){return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function zZ0($,Z,J){return{level:$,bindings:Z,log:J}}function FZ0($){let Z=Number($);if(typeof $==="string"&&Number.isFinite(Z))return Z;if($===void 0)return 1;return $}eI.exports={noop:CJ,buildSafeSonicBoom:$G,asChindings:KZ0,asJson:WZ0,genLog:QZ0,createArgsNormalizer:HZ0,stringify:BZ0,buildFormatters:zZ0,normalizeDestFileDescriptor:FZ0}});var JG=S((Vk0,$C)=>{var AZ0={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},OZ0={ASC:"ASC",DESC:"DESC"};$C.exports={DEFAULT_LEVELS:AZ0,SORTING_ORDER:OZ0}});var bB=S((Uk0,XC)=>{var{lsCacheSym:qZ0,levelValSym:CB,useOnlyCustomLevelsSym:jZ0,streamSym:NZ0,formattersSym:MZ0,hooksSym:DZ0,levelCompSym:ZC}=PJ(),{noop:wZ0,genLog:n5}=ZG(),{DEFAULT_LEVELS:P6,SORTING_ORDER:JC}=JG(),YC={fatal:($)=>{let Z=n5(P6.fatal,$);return function(...J){let Y=this[NZ0];if(Z.call(this,...J),typeof Y.flushSync==="function")try{Y.flushSync()}catch(X){}}},error:($)=>n5(P6.error,$),warn:($)=>n5(P6.warn,$),info:($)=>n5(P6.info,$),debug:($)=>n5(P6.debug,$),trace:($)=>n5(P6.trace,$)},EB=Object.keys(P6).reduce(($,Z)=>{return $[P6[Z]]=Z,$},{}),LZ0=Object.keys(EB).reduce(($,Z)=>{return $[Z]='{"level":'+Number(Z),$},{});function TZ0($){let Z=$[MZ0].level,{labels:J}=$.levels,Y={};for(let X in J){let Q=Z(J[X],Number(X));Y[X]=JSON.stringify(Q).slice(0,-1)}return $[qZ0]=Y,$}function RZ0($,Z){if(Z)return!1;switch($){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function PZ0($){let{labels:Z,values:J}=this.levels;if(typeof $==="number"){if(Z[$]===void 0)throw Error("unknown level value"+$);$=Z[$]}if(J[$]===void 0)throw Error("unknown level "+$);let Y=this[CB],X=this[CB]=J[$],Q=this[jZ0],G=this[ZC],W=this[DZ0].logMethod;for(let K in J){if(G(J[K],X)===!1){this[K]=wZ0;continue}this[K]=RZ0(K,Q)?YC[K](W):n5(J[K],W)}this.emit("level-change",$,X,Z[Y],Y,this)}function IZ0($){let{levels:Z,levelVal:J}=this;return Z&&Z.labels?Z.labels[J]:""}function CZ0($){let{values:Z}=this.levels,J=Z[$];return J!==void 0&&this[ZC](J,this[CB])}function EZ0($,Z,J){if($===JC.DESC)return Z<=J;return Z>=J}function bZ0($){if(typeof $==="string")return EZ0.bind(null,$);return $}function _Z0($=null,Z=!1){let J=$?Object.keys($).reduce((Q,G)=>{return Q[$[G]]=G,Q},{}):null,Y=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),Z?null:EB,J),X=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),Z?null:P6,$);return{labels:Y,values:X}}function SZ0($,Z,J){if(typeof $==="number"){if(![].concat(Object.keys(Z||{}).map((Q)=>Z[Q]),J?[]:Object.keys(EB).map((Q)=>+Q),1/0).includes($))throw Error(`default level:${$} must be included in custom levels`);return}let Y=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),J?null:P6,Z);if(!($ in Y))throw Error(`default level:${$} must be included in custom levels`)}function fZ0($,Z){let{labels:J,values:Y}=$;for(let X in Z){if(X in Y)throw Error("levels cannot be overridden");if(Z[X]in J)throw Error("pre-existing level values cannot be used for new levels")}}function kZ0($){if(typeof $==="function")return;if(typeof $==="string"&&Object.values(JC).includes($))return;throw Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}XC.exports={initialLsCache:LZ0,genLsCache:TZ0,levelMethods:YC,getLevel:IZ0,setLevel:PZ0,isLevelEnabled:CZ0,mappings:_Z0,assertNoLevelCollisions:fZ0,assertDefaultLevelFound:SZ0,genLevelComparison:bZ0,assertLevelComparison:kZ0}});var _B=S((Hk0,QC)=>{QC.exports={version:"10.3.1"}});var zC=S((Bk0,BC)=>{var{EventEmitter:vZ0}=Y0("events"),{lsCacheSym:yZ0,levelValSym:xZ0,setLevelSym:fB,getLevelSym:GC,chindingsSym:XG,mixinSym:hZ0,asJsonSym:KC,writeSym:gZ0,mixinMergeStrategySym:uZ0,timeSym:mZ0,timeSliceIndexSym:lZ0,streamSym:VC,serializersSym:o5,formattersSym:kX,errorKeySym:dZ0,messageKeySym:pZ0,useOnlyCustomLevelsSym:cZ0,needsMetadataGsym:iZ0,redactFmtSym:nZ0,stringifySym:oZ0,formatOptsSym:sZ0,stringifiersSym:rZ0,msgPrefixSym:kB,hooksSym:aZ0}=PJ(),{getLevel:tZ0,setLevel:eZ0,isLevelEnabled:$50,mappings:Z50,initialLsCache:J50,genLsCache:Y50,assertNoLevelCollisions:X50}=bB(),{asChindings:vB,asJson:Q50,buildFormatters:SB,stringify:WC,noop:UC}=ZG(),{version:G50}=_B(),W50=UB(),K50=class{},HC={constructor:K50,child:V50,bindings:U50,setBindings:H50,flush:F50,isLevelEnabled:$50,version:G50,get level(){return this[GC]()},set level($){this[fB]($)},get levelVal(){return this[xZ0]},set levelVal($){throw Error("levelVal is read-only")},get msgPrefix(){return this[kB]},get[Symbol.toStringTag](){return"Pino"},[yZ0]:J50,[gZ0]:z50,[KC]:Q50,[GC]:tZ0,[fB]:eZ0};Object.setPrototypeOf(HC,vZ0.prototype);BC.exports=function(){return Object.create(HC)};var YG=($)=>$;function V50($,Z){if(!$)throw Error("missing bindings for child Pino");let J=this[o5],Y=this[kX],X=Object.create(this);if(Z==null){if(X[kX].bindings!==YG)X[kX]=SB(Y.level,YG,Y.log);if(X[XG]=vB(X,$),this.onChild!==UC)this.onChild(X);return X}if(Z.hasOwnProperty("serializers")===!0){X[o5]=Object.create(null);for(let V in J)X[o5][V]=J[V];let W=Object.getOwnPropertySymbols(J);for(var Q=0;Q<W.length;Q++){let V=W[Q];X[o5][V]=J[V]}for(let V in Z.serializers)X[o5][V]=Z.serializers[V];let K=Object.getOwnPropertySymbols(Z.serializers);for(var G=0;G<K.length;G++){let V=K[G];X[o5][V]=Z.serializers[V]}}else X[o5]=J;if(Z.hasOwnProperty("formatters")){let{level:W,bindings:K,log:V}=Z.formatters;X[kX]=SB(W||Y.level,K||YG,V||Y.log)}else X[kX]=SB(Y.level,YG,Y.log);if(Z.hasOwnProperty("customLevels")===!0)X50(this.levels,Z.customLevels),X.levels=Z50(Z.customLevels,X[cZ0]),Y50(X);if(typeof Z.redact==="object"&&Z.redact!==null||Array.isArray(Z.redact)){X.redact=Z.redact;let W=W50(X.redact,WC),K={stringify:W[nZ0]};X[oZ0]=WC,X[rZ0]=W,X[sZ0]=K}if(typeof Z.msgPrefix==="string")X[kB]=(this[kB]||"")+Z.msgPrefix;if(X[XG]=vB(X,$),Z.level!==void 0&&Z.level!==this.level||Z.hasOwnProperty("customLevels")){let W=Z.level||this.level;X[fB](W)}return this.onChild(X),X}function U50(){let Z=`{${this[XG].substr(1)}}`,J=JSON.parse(Z);return delete J.pid,delete J.hostname,J}function H50($){let Z=vB(this,$);this[XG]=Z}function B50($,Z){return Object.assign(Z,$)}function z50($,Z,J){let Y=this[mZ0](),X=this[hZ0],Q=this[dZ0],G=this[pZ0],W=this[uZ0]||B50,K,V=this[aZ0].streamWrite;if($===void 0||$===null)K={};else if($ instanceof Error){if(K={[Q]:$},Z===void 0)Z=$.message}else if(K=$,Z===void 0&&$[G]===void 0&&$[Q])Z=$[Q].message;if(X)K=W(K,X(K,J,this));let U=this[KC](K,Z,J,Y),H=this[VC];if(H[iZ0]===!0)H.lastLevel=J,H.lastObj=K,H.lastMsg=Z,H.lastTime=Y.slice(this[lZ0]),H.lastLogger=this;H.write(V?V(U):U)}function F50($){if($!=null&&typeof $!=="function")throw Error("callback must be a function");let Z=this[VC];if(typeof Z.flush==="function")Z.flush($||UC);else if($)$()}});var qC=S((zk0,OC)=>{var{hasOwnProperty:vX}=Object.prototype,r5=hB();r5.configure=hB;r5.stringify=r5;r5.default=r5;zk0.stringify=r5;zk0.configure=hB;OC.exports=r5;var A50=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function lZ($){if($.length<5000&&!A50.test($))return`"${$}"`;return JSON.stringify($)}function yB($,Z){if($.length>200||Z)return $.sort(Z);for(let J=1;J<$.length;J++){let Y=$[J],X=J;while(X!==0&&$[X-1]>Y)$[X]=$[X-1],X--;$[X]=Y}return $}var O50=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function xB($){return O50.call($)!==void 0&&$.length!==0}function FC($,Z,J){if($.length<J)J=$.length;let Y=Z===","?"":" ",X=`"0":${Y}${$[0]}`;for(let Q=1;Q<J;Q++)X+=`${Z}"${Q}":${Y}${$[Q]}`;return X}function q50($){if(vX.call($,"circularValue")){let Z=$.circularValue;if(typeof Z==="string")return`"${Z}"`;if(Z==null)return Z;if(Z===Error||Z===TypeError)return{toString(){throw TypeError("Converting circular structure to JSON")}};throw TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function j50($){let Z;if(vX.call($,"deterministic")){if(Z=$.deterministic,typeof Z!=="boolean"&&typeof Z!=="function")throw TypeError('The "deterministic" argument must be of type boolean or comparator function')}return Z===void 0?!0:Z}function N50($,Z){let J;if(vX.call($,Z)){if(J=$[Z],typeof J!=="boolean")throw TypeError(`The "${Z}" argument must be of type boolean`)}return J===void 0?!0:J}function AC($,Z){let J;if(vX.call($,Z)){if(J=$[Z],typeof J!=="number")throw TypeError(`The "${Z}" argument must be of type number`);if(!Number.isInteger(J))throw TypeError(`The "${Z}" argument must be an integer`);if(J<1)throw RangeError(`The "${Z}" argument must be >= 1`)}return J===void 0?1/0:J}function s5($){if($===1)return"1 item";return`${$} items`}function M50($){let Z=new Set;for(let J of $)if(typeof J==="string"||typeof J==="number")Z.add(String(J));return Z}function D50($){if(vX.call($,"strict")){let Z=$.strict;if(typeof Z!=="boolean")throw TypeError('The "strict" argument must be of type boolean');if(Z)return(J)=>{let Y=`Object can not safely be stringified. Received type ${typeof J}`;if(typeof J!=="function")Y+=` (${J.toString()})`;throw Error(Y)}}}function hB($){$={...$};let Z=D50($);if(Z){if($.bigint===void 0)$.bigint=!1;if(!("circularValue"in $))$.circularValue=Error}let J=q50($),Y=N50($,"bigint"),X=j50($),Q=typeof X==="function"?X:void 0,G=AC($,"maximumDepth"),W=AC($,"maximumBreadth");function K(z,F,A,j,N,L){let q=F[z];if(typeof q==="object"&&q!==null&&typeof q.toJSON==="function")q=q.toJSON(z);switch(q=j.call(F,z,q),typeof q){case"string":return lZ(q);case"object":{if(q===null)return"null";if(A.indexOf(q)!==-1)return J;let M="",C=",",R=L;if(Array.isArray(q)){if(q.length===0)return"[]";if(G<A.length+1)return'"[Array]"';if(A.push(q),N!=="")L+=N,M+=`
87
87
  ${L}`,C=`,
88
88
  ${L}`;let b=Math.min(q.length,W),y=0;for(;y<b-1;y++){let g=K(String(y),q,A,j,N,L);M+=g!==void 0?g:"null",M+=C}let k=K(String(y),q,A,j,N,L);if(M+=k!==void 0?k:"null",q.length-1>W){let g=q.length-W-1;M+=`${C}"... ${s5(g)} not stringified"`}if(N!=="")M+=`
89
89
  ${R}`;return A.pop(),`[${M}]`}let w=Object.keys(q),I=w.length;if(I===0)return"{}";if(G<A.length+1)return'"[Object]"';let _="",E="";if(N!=="")L+=N,C=`,
@@ -485,7 +485,7 @@ ${J}`);Z.destroy($)}function Ku($){if(typeof $!=="function")throw new Qu(typeof
485
485
  `})}KK.prototype.incr=function($,Z,J,Y){this.redis.rateLimit(this.key+$,J,Y,this.continueExceeding,this.exponentialBackoff,(X,Q)=>{X?Z(X,null):Z(null,{current:Q[0],ttl:Q[1]})})};KK.prototype.child=function($){return new KK($.continueExceeding,$.exponentialBackoff,this.redis,`${this.key}${$.routeInfo.method}${$.routeInfo.url}-`)};Mu.exports=KK});var Cu=S((Kh0,VK)=>{var Sq0=Ou(),{parse:Tu,format:fq0}=qu(),kq0=Nu(),vq0=Du(),yq0={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},xq0={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},UA=()=>{},hq0=($)=>$.ip,gq0=($,Z)=>{let J=Error(`Rate limit exceeded, retry in ${Z.after}`);return J.statusCode=Z.statusCode,J};async function HA($,Z){let J={global:typeof Z.global==="boolean"?Z.global:!0};if(typeof Z.enableDraftSpec==="boolean"&&Z.enableDraftSpec)J.enableDraftSpec=!0,J.labels=xq0;else J.enableDraftSpec=!1,J.labels=yq0;if(J.addHeaders=Object.assign({[J.labels.rateLimit]:!0,[J.labels.rateRemaining]:!0,[J.labels.rateReset]:!0,[J.labels.retryAfter]:!0},Z.addHeaders),J.addHeadersOnExceeding=Object.assign({[J.labels.rateLimit]:!0,[J.labels.rateRemaining]:!0,[J.labels.rateReset]:!0},Z.addHeadersOnExceeding),Number.isFinite(Z.max)&&Z.max>=0)J.max=Math.trunc(Z.max);else if(typeof Z.max==="function")J.max=Z.max;else J.max=1000;if(Number.isFinite(Z.timeWindow)&&Z.timeWindow>=0)J.timeWindow=Math.trunc(Z.timeWindow);else if(typeof Z.timeWindow==="string")J.timeWindow=Tu(Z.timeWindow);else if(typeof Z.timeWindow==="function")J.timeWindow=Z.timeWindow;else J.timeWindow=60000;if(J.hook=Z.hook||"onRequest",J.allowList=Z.allowList||Z.whitelist||null,J.ban=Number.isFinite(Z.ban)&&Z.ban>=0?Math.trunc(Z.ban):-1,J.onBanReach=typeof Z.onBanReach==="function"?Z.onBanReach:UA,J.onExceeding=typeof Z.onExceeding==="function"?Z.onExceeding:UA,J.onExceeded=typeof Z.onExceeded==="function"?Z.onExceeded:UA,J.continueExceeding=typeof Z.continueExceeding==="boolean"?Z.continueExceeding:!1,J.exponentialBackoff=typeof Z.exponentialBackoff==="boolean"?Z.exponentialBackoff:!1,J.keyGenerator=typeof Z.keyGenerator==="function"?Z.keyGenerator:hq0,typeof Z.errorResponseBuilder==="function")J.errorResponseBuilder=Z.errorResponseBuilder,J.isCustomErrorMessage=!0;else J.errorResponseBuilder=gq0,J.isCustomErrorMessage=!1;J.skipOnError=typeof Z.skipOnError==="boolean"?Z.skipOnError:!1;let Y={rateLimitRan:Symbol("fastify.request.rateLimitRan"),store:null};if(Z.store){let X=Z.store;Y.store=new X(J)}else if(Z.redis)Y.store=new vq0(J.continueExceeding,J.exponentialBackoff,Z.redis,Z.nameSpace);else Y.store=new kq0(J.continueExceeding,J.exponentialBackoff,Z.cache);if($.decorateRequest(Y.rateLimitRan,!1),!$.hasDecorator("createRateLimit"))$.decorate("createRateLimit",(X)=>{let Q=wu(Y,J,X);return(G)=>Pu.apply(this,Q.concat(G))});if(!$.hasDecorator("rateLimit"))$.decorate("rateLimit",(X)=>{let Q=wu(Y,J,X);return Iu(...Q)});$.addHook("onRoute",(X)=>{if(X.config?.rateLimit!=null){if(typeof X.config.rateLimit==="object"){let Q=Object.create(Y),G=Ru(J,X.config.rateLimit,{routeInfo:X});Q.store=Y.store.child(G),Lu(Q,G,X)}else if(X.config.rateLimit!==!1)throw Error("Unknown value for route rate-limit configuration")}else if(J.global)Lu(Y,J,X)})}function Ru(...$){let Z=Object.assign({},...$);if(Number.isFinite(Z.timeWindow)&&Z.timeWindow>=0)Z.timeWindow=Math.trunc(Z.timeWindow);else if(typeof Z.timeWindow==="string")Z.timeWindow=Tu(Z.timeWindow);else if(typeof Z.timeWindow!=="function")Z.timeWindow=60000;if(Number.isFinite(Z.max)&&Z.max>=0)Z.max=Math.trunc(Z.max);else if(typeof Z.max!=="function")Z.max=1000;if(Number.isFinite(Z.ban)&&Z.ban>=0)Z.ban=Math.trunc(Z.ban);else Z.ban=-1;if(Z.groupId!==void 0&&typeof Z.groupId!=="string")throw Error("groupId must be a string");return Z}function wu($,Z,J){if(typeof J==="object"){let Y=Object.create($),X=Ru(Z,J,{routeInfo:{}});return Y.store=Y.store.child(X),[Y,X]}return[$,Z]}function Lu($,Z,J){let Y=Z.hook,X=Iu($,Z);if(Array.isArray(J[Y]))J[Y].push(X);else if(typeof J[Y]==="function")J[Y]=[J[Y],X];else J[Y]=[X]}async function Pu($,Z,J){let{store:Y}=$,X=await Z.keyGenerator(J),Q=J.routeOptions.config?.rateLimit?.groupId;if(Q)X+=Q;if(Z.allowList){if(typeof Z.allowList==="function"){if(await Z.allowList(J,X))return{isAllowed:!0,key:X}}else if(Z.allowList.indexOf(X)!==-1)return{isAllowed:!0,key:X}}let G=typeof Z.max==="number"?Z.max:await Z.max(J,X),W=typeof Z.timeWindow==="number"?Z.timeWindow:await Z.timeWindow(J,X),K=0,V=0,U=0;try{let H=await new Promise((B,z)=>{Y.incr(X,(F,A)=>{F?z(F):B(A)},W,G)});K=H.current,V=H.ttl,U=Math.ceil(H.ttl/1000)}catch(H){if(!Z.skipOnError)throw H}return{isAllowed:!1,key:X,max:G,timeWindow:W,remaining:Math.max(0,G-K),ttl:V,ttlInSeconds:U,isExceeded:K>G,isBanned:Z.ban!==-1&&K-G>Z.ban}}function Iu($,Z){let{rateLimitRan:J}=$;return async(Y,X)=>{if(Y[J])return;Y[J]=!0;let Q=await Pu($,Z,Y);if(Q.isAllowed)return;let{key:G,max:W,remaining:K,ttl:V,ttlInSeconds:U,isExceeded:H,isBanned:B}=Q;if(!H){if(Z.addHeadersOnExceeding[Z.labels.rateLimit])X.header(Z.labels.rateLimit,W);if(Z.addHeadersOnExceeding[Z.labels.rateRemaining])X.header(Z.labels.rateRemaining,K);if(Z.addHeadersOnExceeding[Z.labels.rateReset])X.header(Z.labels.rateReset,U);Z.onExceeding(Y,G);return}if(Z.onExceeded(Y,G),Z.addHeaders[Z.labels.rateLimit])X.header(Z.labels.rateLimit,W);if(Z.addHeaders[Z.labels.rateRemaining])X.header(Z.labels.rateRemaining,0);if(Z.addHeaders[Z.labels.rateReset])X.header(Z.labels.rateReset,U);if(Z.addHeaders[Z.labels.retryAfter])X.header(Z.labels.retryAfter,U);let z={statusCode:429,ban:!1,max:W,ttl:V,after:fq0(U*1000,!0)};if(B)z.statusCode=403,z.ban=!0,Z.onBanReach(Y,G);throw Z.errorResponseBuilder(Y,z)}}VK.exports=Sq0(HA,{fastify:"5.x",name:"@fastify/rate-limit"});VK.exports.default=HA;VK.exports.fastifyRateLimit=HA});var km=S((fm,jK)=>{(($,Z)=>{if(typeof define==="function"&&define.amd)define([],Z);else if(typeof jK==="object"&&jK.exports)jK.exports=Z();else $.fuzzysort=Z()})(fm,($)=>{var Z=(u,l)=>{if(!u||!l)return r;var $0=z(u);if(!g(l))l=B(l);var v=$0.bitflags;if((v&l._bitflags)!==v)return r;return A($0,l)},J=(u,l,$0)=>{if(!u)return $0?.all?F(l,$0):t;var v=z(u),h=v.bitflags,c=v.containsSpace,m=U($0?.threshold||0),a=$0?.limit||d,e=0,H0=0,A0=l.length;function P0(x){if(e<a)h0.add(x),++e;else if(++H0,x._score>h0.peek()._score)h0.replaceTop(x)}if($0?.key){var s0=$0.key;for(var o=0;o<A0;++o){var K0=l[o],z0=k(K0,s0);if(!z0)continue;if(!g(z0))z0=B(z0);if((h&z0._bitflags)!==h)continue;var j0=A(v,z0);if(j0===r)continue;if(j0._score<m)continue;j0.obj=K0,P0(j0)}}else if($0?.keys){var Q1=$0.keys,_0=Q1.length;$:for(var o=0;o<A0;++o){var K0=l[o];{var e0=0;for(var S0=0;S0<_0;++S0){var s0=Q1[S0],z0=k(K0,s0);if(!z0){b[S0]=G0;continue}if(!g(z0))z0=B(z0);b[S0]=z0,e0|=z0._bitflags}if((h&e0)!==h)continue}if(c)for(let n=0;n<v.spaceSearches.length;n++)E[n]=p;for(var S0=0;S0<_0;++S0){if(z0=b[S0],z0===G0){y[S0]=G0;continue}if(y[S0]=A(v,z0,!1,c),y[S0]===r){y[S0]=G0;continue}if(c)for(let J0=0;J0<v.spaceSearches.length;J0++){if(f[J0]>-1000){if(E[J0]>p){var C1=(E[J0]+f[J0])/4;if(C1>E[J0])E[J0]=C1}}if(f[J0]>E[J0])E[J0]=f[J0]}}if(c){for(let n=0;n<v.spaceSearches.length;n++)if(E[n]===p)continue $}else{var n0=!1;for(let n=0;n<_0;n++)if(y[n]._score!==p){n0=!0;break}if(!n0)continue}var z1=new W(_0);for(let n=0;n<_0;n++)z1[n]=y[n];if(c){var a0=0;for(let n=0;n<v.spaceSearches.length;n++)a0+=E[n]}else{var a0=p;for(let J0=0;J0<_0;J0++){var j0=z1[J0];if(j0._score>-1000){if(a0>p){var C1=(a0+j0._score)/4;if(C1>a0)a0=C1}}if(j0._score>a0)a0=j0._score}}if(z1.obj=K0,z1._score=a0,$0?.scoreFn){if(a0=$0.scoreFn(z1),!a0)continue;a0=U(a0),z1._score=a0}if(a0<m)continue;P0(z1)}}else for(var o=0;o<A0;++o){var z0=l[o];if(!z0)continue;if(!g(z0))z0=B(z0);if((h&z0._bitflags)!==h)continue;var j0=A(v,z0);if(j0===r)continue;if(j0._score<m)continue;P0(j0)}if(e===0)return t;var U1=Array(e);for(var o=e-1;o>=0;--o)U1[o]=h0.poll();return U1.total=e+H0,U1},Y=(u,l="<b>",$0="</b>")=>{var v=typeof l==="function"?l:void 0,h=u.target,c=h.length,m=u.indexes,a="",e=0,H0=0,A0=!1,P0=[];for(var s0=0;s0<c;++s0){var o=h[s0];if(m[H0]===s0){if(++H0,!A0)if(A0=!0,v)P0.push(a),a="";else a+=l;if(H0===m.length){if(v)a+=o,P0.push(v(a,e++)),a="",P0.push(h.substr(s0+1));else a+=o+$0+h.substr(s0+1);break}}else if(A0)if(A0=!1,v)P0.push(v(a,e++)),a="";else a+=$0;a+=o}return v?P0:a},X=(u)=>{if(typeof u==="number")u=""+u;else if(typeof u!=="string")u="";var l=L(u);return K(u,{_targetLower:l._lower,_targetLowerCodes:l.lowerCodes,_bitflags:l.bitflags})},Q=()=>{C.clear(),R.clear()};class G{get["indexes"](){return this._indexes.slice(0,this._indexes.len).sort((u,l)=>u-l)}set["indexes"](u){return this._indexes=u}["highlight"](u,l){return Y(this,u,l)}get["score"](){return V(this._score)}set["score"](u){this._score=U(u)}}class W extends Array{get["score"](){return V(this._score)}set["score"](u){this._score=U(u)}}var K=(u,l)=>{let $0=new G;return $0.target=u,$0.obj=l.obj??r,$0._score=l._score??p,$0._indexes=l._indexes??[],$0._targetLower=l._targetLower??"",$0._targetLowerCodes=l._targetLowerCodes??r,$0._nextBeginningIndexes=l._nextBeginningIndexes??r,$0._bitflags=l._bitflags??0,$0},V=(u)=>{if(u===p)return 0;if(u>1)return u;return Math.E**(((-u+1)**0.04307-1)*-2)},U=(u)=>{if(u===0)return p;if(u>1)return u;return 1-Math.pow(Math.log(u)/-2+1,23.218017181332716)},H=(u)=>{if(typeof u==="number")u=""+u;else if(typeof u!=="string")u="";u=u.trim();var l=L(u),$0=[];if(l.containsSpace){var v=u.split(/\s+/);v=[...new Set(v)];for(var h=0;h<v.length;h++){if(v[h]==="")continue;var c=L(v[h]);$0.push({lowerCodes:c.lowerCodes,_lower:v[h].toLowerCase(),containsSpace:!1})}}return{lowerCodes:l.lowerCodes,_lower:l._lower,containsSpace:l.containsSpace,bitflags:l.bitflags,spaceSearches:$0}},B=(u)=>{if(u.length>999)return X(u);var l=C.get(u);if(l!==void 0)return l;return l=X(u),C.set(u,l),l},z=(u)=>{if(u.length>999)return H(u);var l=R.get(u);if(l!==void 0)return l;return l=H(u),R.set(u,l),l},F=(u,l)=>{var $0=[];$0.total=u.length;var v=l?.limit||d;if(l?.key)for(var h=0;h<u.length;h++){var c=u[h],m=k(c,l.key);if(m==r)continue;if(!g(m))m=B(m);var a=K(m.target,{_score:m._score,obj:c});if($0.push(a),$0.length>=v)return $0}else if(l?.keys)for(var h=0;h<u.length;h++){var c=u[h],e=new W(l.keys.length);for(var H0=l.keys.length-1;H0>=0;--H0){var m=k(c,l.keys[H0]);if(!m){e[H0]=G0;continue}if(!g(m))m=B(m);m._score=p,m._indexes.len=0,e[H0]=m}if(e.obj=c,e._score=p,$0.push(e),$0.length>=v)return $0}else for(var h=0;h<u.length;h++){var m=u[h];if(m==r)continue;if(!g(m))m=B(m);if(m._score=p,m._indexes.len=0,$0.push(m),$0.length>=v)return $0}return $0},A=(u,l,$0=!1,v=!1)=>{if($0===!1&&u.containsSpace)return j(u,l,v);var{_lower:h,lowerCodes:c}=u,m=c[0],a=l._targetLowerCodes,e=c.length,H0=a.length,o=0,A0=0,P0=0;for(;;){var s0=m===a[A0];if(s0){if(w[P0++]=A0,++o,o===e)break;m=c[o]}if(++A0,A0>=H0)return r}var o=0,K0=!1,z0=0,j0=l._nextBeginningIndexes;if(j0===r)j0=l._nextBeginningIndexes=M(l.target);A0=w[0]===0?0:j0[w[0]-1];var Q1=0;if(A0!==H0)for(;;)if(A0>=H0){if(o<=0)break;if(++Q1,Q1>200)break;--o;var _0=I[--z0];A0=j0[_0]}else{var s0=c[o]===a[A0];if(s0){if(I[z0++]=A0,++o,o===e){K0=!0;break}++A0}else A0=j0[A0]}var e0=e<=1?-1:l._targetLower.indexOf(h,w[0]),S0=!!~e0,C1=!S0?!1:e0===0||l._nextBeginningIndexes[e0-1]===e0;if(S0&&!C1)for(var n0=0;n0<j0.length;n0=j0[n0]){if(n0<=e0)continue;for(var z1=0;z1<e;z1++)if(c[z1]!==l._targetLowerCodes[n0+z1])break;if(z1===e){e0=n0,C1=!0;break}}var a0=(n)=>{var J0=0,C0=0;for(var M0=1;M0<e;++M0)if(n[M0]-n[M0-1]!==1)J0-=n[M0],++C0;var D1=n[e-1]-n[0]-(e-1);if(J0-=(12+D1)*C0,n[0]!==0)J0-=n[0]*n[0]*0.2;if(!K0)J0*=1000;else{var g0=1;for(var M0=j0[0];M0<H0;M0=j0[M0])++g0;if(g0>24)J0*=(g0-24)*10}if(J0-=(H0-e)/2,S0)J0/=1+e*e*1;if(C1)J0/=1+e*e*1;return J0-=(H0-e)/2,J0};if(!K0){if(S0)for(var n0=0;n0<e;++n0)w[n0]=e0+n0;var U1=w,x=a0(U1)}else if(C1){for(var n0=0;n0<e;++n0)w[n0]=e0+n0;var U1=w,x=a0(w)}else var U1=I,x=a0(I);l._score=x;for(var n0=0;n0<e;++n0)l._indexes[n0]=U1[n0];l._indexes.len=e;let i=new G;return i.target=l.target,i._score=l._score,i._indexes=l._indexes,i},j=(u,l,$0)=>{var v=new Set,h=0,c=r,m=0,a=u.spaceSearches,e=a.length,H0=0,A0=()=>{for(let C1=H0-1;C1>=0;C1--)l._nextBeginningIndexes[_[C1*2+0]]=_[C1*2+1]},P0=!1;for(var S0=0;S0<e;++S0){f[S0]=p;var s0=a[S0];if(c=A(s0,l),$0){if(c===r)continue;P0=!0}else if(c===r)return A0(),r;var o=S0===e-1;if(!o){var K0=c._indexes,z0=!0;for(let n0=0;n0<K0.len-1;n0++)if(K0[n0+1]-K0[n0]!==1){z0=!1;break}if(z0){var j0=K0[K0.len-1]+1,Q1=l._nextBeginningIndexes[j0-1];for(let n0=j0-1;n0>=0;n0--){if(Q1!==l._nextBeginningIndexes[n0])break;l._nextBeginningIndexes[n0]=j0,_[H0*2+0]=n0,_[H0*2+1]=Q1,H0++}}}if(h+=c._score/e,f[S0]=c._score/e,c._indexes[0]<m)h-=(m-c._indexes[0])*2;m=c._indexes[0];for(var _0=0;_0<c._indexes.len;++_0)v.add(c._indexes[_0])}if($0&&!P0)return r;A0();var e0=A(u,l,!0);if(e0!==r&&e0._score>h){if($0)for(var S0=0;S0<e;++S0)f[S0]=e0._score/e;return e0}if($0)c=l;c._score=h;var S0=0;for(let C1 of v)c._indexes[S0++]=C1;return c._indexes.len=S0,c},N=(u)=>u.replace(/\p{Script=Latin}+/gu,(l)=>l.normalize("NFD")).replace(/[\u0300-\u036f]/g,""),L=(u)=>{u=N(u);var l=u.length,$0=u.toLowerCase(),v=[],h=0,c=!1;for(var m=0;m<l;++m){var a=v[m]=$0.charCodeAt(m);if(a===32){c=!0;continue}var e=a>=97&&a<=122?a-97:a>=48&&a<=57?26:a<=127?30:31;h|=1<<e}return{lowerCodes:v,bitflags:h,containsSpace:c,_lower:$0}},q=(u)=>{var l=u.length,$0=[],v=0,h=!1,c=!1;for(var m=0;m<l;++m){var a=u.charCodeAt(m),e=a>=65&&a<=90,H0=e||a>=97&&a<=122||a>=48&&a<=57,A0=e&&!h||!c||!H0;if(h=e,c=H0,A0)$0[v++]=m}return $0},M=(u)=>{u=N(u);var l=u.length,$0=q(u),v=[],h=$0[0],c=0;for(var m=0;m<l;++m)if(h>m)v[m]=h;else h=$0[++c],v[m]=h===void 0?l:h;return v},C=new Map,R=new Map,w=[],I=[],_=[],E=[],f=[],b=[],y=[],k=(u,l)=>{var $0=u[l];if($0!==void 0)return $0;if(typeof l==="function")return l(u);var v=l;if(!Array.isArray(l))v=l.split(".");var h=v.length,c=-1;while(u&&++c<h)u=u[v[c]];return u},g=(u)=>{return typeof u==="object"&&typeof u._bitflags==="number"},d=1/0,p=-d,t=[];t.total=0;var r=null,G0=X(""),O0=(u)=>{var l=[],$0=0,v={},h=(c)=>{for(var m=0,a=l[m],e=1;e<$0;){var H0=e+1;m=e,H0<$0&&l[H0]._score<l[e]._score&&(m=H0),l[m-1>>1]=l[m],e=1+(m<<1)}for(var A0=m-1>>1;m>0&&a._score<l[A0]._score;A0=(m=A0)-1>>1)l[m]=l[A0];l[m]=a};return v.add=(c)=>{var m=$0;l[$0++]=c;for(var a=m-1>>1;m>0&&c._score<l[a]._score;a=(m=a)-1>>1)l[m]=l[a];l[m]=c},v.poll=(c)=>{if($0!==0){var m=l[0];return l[0]=l[--$0],h(),m}},v.peek=(c)=>{if($0!==0)return l[0]},v.replaceTop=(c)=>{l[0]=c,h()},v},h0=O0();return{single:Z,go:J,prepare:X,cleanup:Q}})});var Y9={};F1(Y9,{toRow:()=>bM0,plan:()=>lM0,listGlobal:()=>cM0,list:()=>pM0,layer:()=>Ld,isDefaultTitle:()=>EM0,getUsage:()=>dM0,fromRow:()=>OY,defaultLayer:()=>rM0,SetTitleInput:()=>xM0,SetRevertInput:()=>uM0,SetPermissionInput:()=>gM0,SetArchivedInput:()=>hM0,Service:()=>nK,RemoveInput:()=>yM0,ProjectInfo:()=>Md,MessagesInput:()=>mM0,Info:()=>z6,GlobalInfo:()=>_M0,GetInput:()=>kM0,ForkInput:()=>fM0,Event:()=>qY,CreateInput:()=>SM0,ChildrenInput:()=>vM0,BusyError:()=>wd});var JV;((tM0)=>{let $=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],Z=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function J(){return[$[Math.floor(Math.random()*$.length)],Z[Math.floor(Math.random()*Z.length)]].join("-")}tM0.create=J})(JV||={});var l1={};F1(l1,{subscribeAll:()=>vd,subscribe:()=>kd,publish:()=>fd,layer:()=>YV,defaultLayer:()=>_d,Service:()=>IY,InstanceDisposed:()=>UO,Bus:()=>l1});var NZ=E0.create({service:"bus"}),UO=L1.define("server.instance.disposed",P.object({directory:P.string()}));class IY extends S1.Service()("@qitqode/Bus"){}var YV=T0.effect(IY,T.gen(function*(){let $=yield*B0.make(T.fn("Bus.state")(function*(K){let V=yield*h6.unbounded(),U=new Map;return yield*T.addFinalizer(()=>T.gen(function*(){yield*h6.publish(V,{type:UO.type,properties:{directory:K.directory}}),yield*h6.shutdown(V);for(let H of U.values())yield*h6.shutdown(H)})),{wildcard:V,typed:U}}));function Z(K,V){return T.gen(function*(){let U=K.typed.get(V.type);if(!U)U=yield*h6.unbounded(),K.typed.set(V.type,U);return U})}function J(K,V){return T.gen(function*(){let U=yield*B0.get($),H={type:K.type,properties:V};NZ.debug("publishing",{type:K.type});let B=U.typed.get(K.type);if(B)yield*h6.publish(B,H);yield*h6.publish(U.wildcard,H);let z=yield*B0.directory,F=yield*B0.context,A=yield*B0.workspaceID;L7.emit("event",{directory:z,project:F.project.id,workspace:A,payload:H})})}function Y(K){return NZ.info("subscribing",{type:K.type}),I$.unwrap(T.gen(function*(){let V=yield*B0.get($),U=yield*Z(V,K);return I$.fromPubSub(U)})).pipe(I$.ensuring(T.sync(()=>NZ.info("unsubscribing",{type:K.type}))))}function X(){return NZ.info("subscribing",{type:"*"}),I$.unwrap(T.gen(function*(){let K=yield*B0.get($);return I$.fromPubSub(K.wildcard)})).pipe(I$.ensuring(T.sync(()=>NZ.info("unsubscribing",{type:"*"}))))}function Q(K,V,U){return T.gen(function*(){NZ.info("subscribing",{type:V});let H=yield*T7.make(),B=yield*PY.make(),z=yield*PY.provide(B)(h6.subscribe(K));return yield*PY.provide(B)(I$.fromSubscription(z).pipe(I$.runForEach((F)=>T.tryPromise({try:()=>Promise.resolve().then(()=>U(F)),catch:(A)=>{NZ.error("subscriber failed",{type:V,cause:A})}}).pipe(T.ignore)),T.forkScoped)),()=>{NZ.info("unsubscribing",{type:V}),H.fork(PY.close(B,B9.void))}})}let G=T.fn("Bus.subscribeCallback")(function*(K,V){let U=yield*B0.get($),H=yield*Z(U,K);return yield*Q(H,K.type,V)}),W=T.fn("Bus.subscribeAllCallback")(function*(K){let V=yield*B0.get($);return yield*Q(V.wildcard,"*",K)});return IY.of({publish:J,subscribe:Y,subscribeAll:X,subscribeCallback:G,subscribeAllCallback:W})})),_d=YV,{runPromise:Sd,runSync:HO}=VO(IY,YV);async function fd($,Z){return Sd((J)=>J.publish($,Z))}function kd($,Z){return HO((J)=>J.subscribeCallback($,Z))}function vd($){return HO((Z)=>Z.subscribeAllCallback($))}var X$={};F1(X$,{versionedType:()=>CY,run:()=>rd,reset:()=>cd,replayAll:()=>sd,replay:()=>qO,remove:()=>ad,registry:()=>EY,project:()=>od,payloads:()=>td,init:()=>id,define:()=>nd,SyncEvent:()=>X$});var _8=g6("event_sequence",{aggregate_id:w1().notNull().primaryKey(),seq:j8().notNull()}),z9=g6("event",{id:w1().primaryKey(),aggregate_id:w1().notNull().references(()=>_8.aggregate_id,{onDelete:"cascade"}),seq:j8().notNull(),type:w1().notNull(),data:w1({mode:"json"}).$type().notNull()});var d1={};F1(d1,{timestamp:()=>pd,schema:()=>gd,descending:()=>dd,create:()=>zO,ascending:()=>ld,Identifier:()=>d1});import{randomBytes as yd}from"crypto";var xd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function XV($){let Z="",J=yd($);for(let Y=0;Y<$;Y++)Z+=xd[J[Y]%62];return Z}function QV(){let $=0,Z=0;return(J)=>{if(J!==void 0)return BigInt(J)*BigInt(4096);let Y=Date.now();if(Y>$)$=Y,Z=0;if(Z++,Z>4095)$++,Z=1;return BigInt($)*BigInt(4096)+BigInt(Z)}}function GV($){let Z=Buffer.alloc(6);for(let J=0;J<6;J++)Z[J]=Number($>>BigInt(40-8*J)&BigInt(255));return Z.toString("hex")}var hd;((HD0)=>{let Z=QV();function J(){return X(!1)}HD0.ascending=J;function Y(){return X(!0)}HD0.descending=Y;function X(Q,G){let W=Z(G);return W=Q?~W:W,GV(W)+XV(14)}HD0.create=X})(hd||={});var F9={event:"evt",session:"ses",message:"msg",permission:"per",question:"que",user:"usr",part:"prt",pty:"pty",tool:"tool",workspace:"wrk",entry:"ent",workflow:"wf"};function gd($){return P.string().startsWith(F9[$])}var ud=26,md=QV();function ld($,Z){return BO($,"ascending",Z)}function dd($,Z){return BO($,"descending",Z)}function BO($,Z,J){if(!J)return zO(F9[$],Z);if(!J.startsWith(F9[$]))throw Error(`ID ${J} does not start with ${F9[$]}`);return J}function zO($,Z,J){let Y=md(J);return Y=Z==="descending"?~Y:Y,$+"_"+GV(Y)+XV(ud-12)}function pd($){let Z=$.split("_")[0],J=$.slice(Z.length+1,Z.length+13),Y=BigInt("0x"+J);return Number(Y/BigInt(4096))}var FO=O.String.annotate({[F$]:d1.schema("event")}).pipe(O.brand("EventID"),u0(($)=>({ascending:(Z)=>$.make(d1.ascending("event",Z)),zod:d1.schema("event").pipe(P.custom())})));var EY=new Map,A9,O9=new Map,WV=!1,KV;function cd(){WV=!1,A9=void 0,KV=($,Z)=>Z}function id($){A9=new Map($.projectors);for(let[Z,J]of O9.entries()){let Y=EY.get(CY(Z,J));L1.define(Y.type,Y.properties||Y.schema)}WV=!0,KV=$.convertEvent||((Z,J)=>J)}function CY($,Z){return Z?`${$}.${Z}`:$}function nd($){if(WV)throw Error("Error defining sync event: sync system has been frozen");let Z={type:$.type,version:$.version,aggregate:$.aggregate,schema:$.schema,properties:$.busSchema?$.busSchema:$.schema};return O9.set(Z.type,Math.max(Z.version,O9.get(Z.type)||0)),EY.set(CY(Z.type,Z.version),Z),Z}function od($,Z){return[$,Z]}function OO($,Z,J){if(A9==null)throw Error("No projectors available. Call `SyncEvent.init` to install projectors");let Y=A9.get($);if(!Y)throw Error(`Projector not found for event: ${$.type}`);W1.transaction((X)=>{if(Y(X,Z.data),b0.QITQODE_EXPERIMENTAL_WORKSPACES)X.insert(_8).values({aggregate_id:Z.aggregateID,seq:Z.seq}).onConflictDoUpdate({target:_8.aggregate_id,set:{seq:Z.seq}}).run(),X.insert(z9).values({id:Z.id,seq:Z.seq,aggregate_id:Z.aggregateID,type:CY($.type,$.version),data:Z.data}).run();W1.effect(()=>{if(J?.publish){let Q=KV($.type,Z.data);if(Q instanceof Promise)Q.then((G)=>{l1.publish({type:$.type,properties:$.schema},G)});else l1.publish({type:$.type,properties:$.schema},Q);L7.emit("event",{directory:S8.directory,project:S8.project.id,workspace:AO.workspaceID,payload:{type:"sync",syncEvent:{type:CY($.type,$.version),...Z}}})}})})}function qO($,Z){let J=EY.get($.type);if(!J)throw Error(`Unknown event type: ${$.type}`);let X=W1.use((G)=>G.select({seq:_8.seq}).from(_8).where(m0(_8.aggregate_id,$.aggregateID)).get())?.seq??-1;if($.seq<=X)return;let Q=X+1;if($.seq!==Q)throw Error(`Sequence mismatch for aggregate "${$.aggregateID}": expected ${Q}, got ${$.seq}`);OO(J,$,{publish:!!Z?.publish})}function sd($,Z){let J=$[0]?.aggregateID;if(!J)return;if($.some((X)=>X.aggregateID!==J))throw Error("Replay events must belong to the same session");let Y=$[0].seq;for(let[X,Q]of $.entries()){let G=Y+X;if(Q.seq!==G)throw Error(`Replay sequence mismatch at index ${X}: expected ${G}, got ${Q.seq}`)}for(let X of $)qO(X,Z);return J}function rd($,Z,J){let Y=Z[$.aggregate];if(Y==null)throw Error(`SyncEvent.run: "${$.aggregate}" required but not found: ${JSON.stringify(Z)}`);if($.version!==O9.get($.type))throw Error(`SyncEvent.run: running old versions of events is not allowed: ${$.type}`);let{publish:X=!0}=J||{};W1.transaction((Q)=>{let G=FO.ascending(),W=Q.select({seq:_8.seq}).from(_8).where(m0(_8.aggregate_id,Y)).get(),K=W?.seq!=null?W.seq+1:0;OO($,{id:G,seq:K,aggregateID:Y,data:Z},{publish:X})},{behavior:"immediate"})}function ad($){W1.transaction((Z)=>{Z.delete(_8).where(m0(_8.aggregate_id,$)).run(),Z.delete(z9).where(m0(z9.aggregate_id,$)).run()})}function td(){return EY.entries().map(([$,Z])=>{return P.object({type:P.literal("sync"),name:P.literal($),id:P.string(),seq:P.number(),aggregateID:P.literal(Z.aggregate),data:Z.schema}).meta({ref:`SyncEvent.${Z.type}`})}).toArray()}var b$={};F1(b$,{toModelMessagesEffect:()=>K2,toModelMessages:()=>re,stream:()=>pU,parts:()=>PL,page:()=>RL,isMedia:()=>NX,get:()=>Ca,fromError:()=>xA,fingerprint:()=>OH,filterCompactedEffect:()=>Ea,filterCompacted:()=>cU,cursor:()=>dU,WithParts:()=>Ta,User:()=>ML,ToolStateRunning:()=>zL,ToolStatePending:()=>BL,ToolStateError:()=>AL,ToolStateCompleted:()=>FL,ToolState:()=>OL,ToolPart:()=>qL,TextPart:()=>tw,SymbolSource:()=>ZL,SubtaskPart:()=>GL,StructuredOutputError:()=>dw,StepStartPart:()=>VL,StepFinishPart:()=>HL,SnapshotPart:()=>rw,SYNTHETIC_ATTACHMENT_PROMPT:()=>W2,RetryPart:()=>KL,ResourceSource:()=>JL,ReasoningPart:()=>ew,Provenance:()=>NL,PatchPart:()=>aw,Part:()=>mU,OutputLengthError:()=>U4,OutputFormatText:()=>nw,OutputFormatJsonSchema:()=>ow,ModelError:()=>iw,MessageV2:()=>b$,InvalidOutputError:()=>pw,Info:()=>lU,Format:()=>sw,FileSource:()=>$L,FilePartSource:()=>YL,FilePart:()=>uU,Event:()=>La,ErrorDiagnostic:()=>lw,ContextOverflowError:()=>GX,ContentFilterError:()=>cw,CompactionPart:()=>WL,CheckpointPart:()=>QL,AuthError:()=>H4,Assistant:()=>DL,AgentPart:()=>XL,AbortedError:()=>f5,APIError:()=>L6});var r0=O.String.annotate({[F$]:d1.schema("session")}).pipe(O.brand("SessionID"),u0(($)=>({descending:(Z)=>$.make(d1.descending("session",Z)),zod:d1.schema("session").pipe(P.custom())}))),i1=O.String.annotate({[F$]:d1.schema("message")}).pipe(O.brand("MessageID"),u0(($)=>({ascending:(Z)=>$.make(d1.ascending("message",Z)),zod:d1.schema("message").pipe(P.custom())}))),MZ=O.String.annotate({[F$]:d1.schema("part")}).pipe(O.brand("PartID"),u0(($)=>({ascending:(Z)=>$.make(d1.ascending("part",Z)),zod:d1.schema("part").pipe(P.custom())})));var X4={};F1(X4,{layer:()=>Iw,defaultLayer:()=>Ha,Symbol:()=>Ga,Status:()=>Ka,Service:()=>Y4,Range:()=>J4,Event:()=>Pw,DocumentSymbol:()=>Wa,Diagnostic:()=>XX});var S7=m6(Kj(),1);import yY from"path";import{pathToFileURL as F5,fileURLToPath as uc}from"url";var Vj={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".jl":"julia",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};function xV($,Z){let J;return Promise.race([$,new Promise((X,Q)=>{J=setTimeout(()=>{Q(Error(`Operation timed out after ${Z}ms`))},Z)})]).finally(()=>clearTimeout(J))}var mc=150,A5=E0.create({service:"lsp.client"}),lc=j1.create("LSPInitializeError",P.object({serverID:P.string()})),Uj={Diagnostics:L1.define("lsp.client.diagnostics",P.object({serverID:P.string(),path:P.string()}))};async function Hj($){let Z=A5.clone().tag("serverID",$.serverID);Z.info("starting client");let J=S7.createMessageConnection(new S7.StreamMessageReader($.server.process.stdout),new S7.StreamMessageWriter($.server.process.stdin)),Y=new Map;if(J.onNotification("textDocument/publishDiagnostics",(G)=>{let W=o0.normalizePath(uc(G.uri));Z.info("textDocument/publishDiagnostics",{path:W,count:G.diagnostics.length});let K=Y.has(W);if(Y.set(W,G.diagnostics),!K&&$.serverID==="typescript")return;l1.publish(Uj.Diagnostics,{path:W,serverID:$.serverID})}),J.onRequest("window/workDoneProgress/create",(G)=>{return Z.info("window/workDoneProgress/create",G),null}),J.onRequest("workspace/configuration",async()=>{return[$.server.initialization??{}]}),J.onRequest("client/registerCapability",async()=>{}),J.onRequest("client/unregisterCapability",async()=>{}),J.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:F5($.root).href}]),J.listen(),Z.info("sending initialize"),await xV(J.sendRequest("initialize",{rootUri:F5($.root).href,processId:$.server.process.pid,workspaceFolders:[{name:"workspace",uri:F5($.root).href}],initializationOptions:{...$.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0,didChangeWatchedFiles:{dynamicRegistration:!0}},textDocument:{synchronization:{didOpen:!0,didChange:!0},publishDiagnostics:{versionSupport:!0}}}}),45000).catch((G)=>{throw Z.error("initialize error",{error:G}),new lc({serverID:$.serverID},{cause:G})}),await J.sendNotification("initialized",{}),$.server.initialization)await J.sendNotification("workspace/didChangeConfiguration",{settings:$.server.initialization});let X={},Q={root:$.root,get serverID(){return $.serverID},get connection(){return J},notify:{async open(G){G.path=yY.isAbsolute(G.path)?G.path:yY.resolve($.directory,G.path);let W=await o0.readText(G.path),K=yY.extname(G.path),V=Vj[K]??"plaintext",U=X[G.path];if(U!==void 0){A5.info("workspace/didChangeWatchedFiles",G),await J.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:F5(G.path).href,type:2}]});let H=U+1;X[G.path]=H,A5.info("textDocument/didChange",{path:G.path,version:H}),await J.sendNotification("textDocument/didChange",{textDocument:{uri:F5(G.path).href,version:H},contentChanges:[{text:W}]});return}A5.info("workspace/didChangeWatchedFiles",G),await J.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:F5(G.path).href,type:1}]}),A5.info("textDocument/didOpen",G),Y.delete(G.path),await J.sendNotification("textDocument/didOpen",{textDocument:{uri:F5(G.path).href,languageId:V,version:0,text:W}}),X[G.path]=0;return}},get diagnostics(){return Y},async waitForDiagnostics(G){let W=o0.normalizePath(yY.isAbsolute(G.path)?G.path:yY.resolve($.directory,G.path));A5.info("waiting for diagnostics",{path:W});let K,V;return await xV(new Promise((U)=>{K=l1.subscribe(Uj.Diagnostics,(H)=>{if(H.properties.path===W&&H.properties.serverID===Q.serverID){if(V)clearTimeout(V);V=setTimeout(()=>{A5.info("got diagnostics",{path:W}),K?.(),U()},mc)}})}),3000).catch(()=>{}).finally(()=>{if(V)clearTimeout(V);K?.()})},async shutdown(){Z.info("shutting down"),J.end(),J.dispose(),await f1.stop($.server.process),Z.info("shutdown")}};return Z.info("initialized"),Q}import Tw from"path";import{pathToFileURL as Rw,fileURLToPath as Qa}from"url";var f7={};F1(f7,{Zls:()=>xj,YamlLS:()=>wj,Vue:()=>Oj,Typescript:()=>Aj,Ty:()=>gj,Tinymist:()=>ij,TexLab:()=>oj,TerraformLS:()=>nj,Svelte:()=>Mj,SourceKit:()=>Ej,RustAnalyzer:()=>bj,Rubocop:()=>hj,Pyright:()=>uj,Prisma:()=>Tj,PHPIntelephense:()=>lj,Oxlint:()=>jj,Ocaml:()=>vj,Nixd:()=>cj,LuaLS:()=>Lj,KotlinLS:()=>fj,JuliaLS:()=>dj,JDTLS:()=>Sj,HLS:()=>pj,Gopls:()=>Pj,Gleam:()=>yj,FSharp:()=>Cj,ElixirLS:()=>mj,ESLint:()=>qj,DockerfileLS:()=>sj,Deno:()=>Fj,Dart:()=>kj,Clojure:()=>rj,Clangd:()=>_j,CSharp:()=>Ij,Biome:()=>Nj,BashLS:()=>Rj,Astro:()=>Dj});function Z1($,Z,J){let Y=Array.isArray(Z)?[...Z]:[],X=Array.isArray(Z)?J:Z,Q=f1.spawn([$,...Y],{...X,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(!Q.stdin||!Q.stdout||!Q.stderr)throw Error("Process output not available");return Q}import dc from"fs/promises";import hV from"path";var Q0=E0.create({service:"lsp.server"}),gV=async($)=>dc.stat($).then(()=>!0).catch(()=>!1),j6=($,Z={})=>f1.run($,{...Z,nothrow:!0}),zj=($,Z={})=>f1.text($,{...Z,nothrow:!0});async function N6($,Z){if($)return $;if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;return q6.which(Z)}var M6=($,Z,J)=>Z1($,Z,{cwd:J,env:{...n8()}}),t0=($,Z)=>{return async(J,Y)=>{if(Z){let G=o0.up({targets:Z,start:hV.dirname(J),stop:Y.directory}),W=await G.next();if(await G.return(),W.value)return}let X=o0.up({targets:$,start:hV.dirname(J),stop:Y.directory}),Q=await X.next();if(await X.return(),!Q.value)return Y.directory;return hV.dirname(Q.value)}};import{createRequire as pc}from"module";import cc from"path";var wZ;((CL0)=>{function $(Z,J){try{return pc(cc.join(J,"package.json")).resolve(Z)}catch{}}CL0.resolve=$})(wZ||={});import ic from"path";async function LZ($,Z,J){let Y=await fetch($);if(!Y.ok){Q0.error(`Failed to download ${J}`);return}let X=ic.join(F0.Path.bin,Z);if(Y.body)await o0.writeStream(X,Y.body);return X}async function TZ($,Z){return D8.extractZip($,F0.Path.bin).then(()=>!0).catch((J)=>{return Q0.error(`Failed to extract ${Z} archive`,{error:J}),!1})}import D6 from"fs/promises";import{text as nc}from"stream/consumers";import w8 from"path";var Fj={id:"deno",root:async($,Z)=>{let J=o0.up({targets:["deno.json","deno.jsonc"],start:w8.dirname($),stop:Z.directory}),Y=await J.next();if(await J.return(),!Y.value)return;return w8.dirname(Y.value)},extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn($){let Z=d0("deno");if(!Z){Q0.info("deno not found, please install deno first");return}return{process:Z1(Z,["lsp"],{cwd:$})}}},Aj={id:"typescript",root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],async spawn($,Z){let J=wZ.resolve("typescript/lib/tsserver.js",Z.directory);if(Q0.info("typescript server",{tsserver:J}),!J)return;let Y=await q6.which("typescript-language-server");if(!Y)return;return{process:Z1(Y,["--stdio"],{cwd:$,env:{...n8()}}),initialization:{tsserver:{path:J}}}}},Oj={id:"vue",extensions:[".vue"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($){let Z=await N6(d0("vue-language-server"),"@vue/language-server");if(!Z)return;return{process:M6(Z,["--stdio"],$),initialization:{}}}},qj={id:"eslint",root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn($,Z){if(!wZ.resolve("eslint",Z.directory))return;Q0.info("spawning eslint server");let Y=w8.join(F0.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await o0.exists(Y)){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading and building VS Code ESLint server");let Q=await LZ("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip","vscode-eslint.zip","vscode-eslint");if(!Q)return;if(!await TZ(Q,"vscode-eslint"))return;await D6.rm(Q,{force:!0});let W=w8.join(F0.Path.bin,"vscode-eslint-main"),K=w8.join(F0.Path.bin,"vscode-eslint");if(await D6.stat(K).catch(()=>{return}))Q0.info("removing old eslint installation",{path:K}),await D6.rm(K,{force:!0,recursive:!0});await D6.rename(W,K);let U=process.platform==="win32"?"npm.cmd":"npm";await f1.run([U,"install"],{cwd:K}),await f1.run([U,"run","compile"],{cwd:K}),Q0.info("installed VS Code ESLint server",{serverPath:Y})}return{process:Z1("node",[Y,"--stdio"],{cwd:$,env:{...n8()}})}}},jj={id:"oxlint",root:t0([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn($,Z){let J=process.platform==="win32"?".cmd":"",Y=w8.join("node_modules",".bin","oxc_language_server"+J),X=w8.join("node_modules",".bin","oxlint"+J),Q=async(K)=>{let V=w8.join($,K);if(await o0.exists(V))return V;let U=o0.up({targets:[K],start:$,stop:Z.worktree}),H=await U.next();if(await U.return(),H.value)return H.value;return},G=await Q(X);if(!G){let K=d0("oxlint");if(K)G=K}if(G){let K=Z1(G,["--help"]);if(await K.exited,K.stdout){if((await nc(K.stdout)).includes("--lsp"))return{process:Z1(G,["--lsp"],{cwd:$})}}}let W=await Q(Y);if(!W){let K=d0("oxc_language_server");if(K)W=K}if(W)return{process:Z1(W,[],{cwd:$})};Q0.info("oxlint not found, please install oxlint");return}},Nj={id:"biome",root:t0(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn($){let Z=w8.join($,"node_modules",".bin","biome"),J;if(await o0.exists(Z))J=Z;if(!J){let Q=d0("biome");if(Q)J=Q}let Y=["lsp-proxy","--stdio"];if(!J){if(!wZ.resolve("biome",$))return;if(J=await q6.which("biome"),!J)return;Y=["lsp-proxy","--stdio"]}return{process:Z1(J,Y,{cwd:$,env:{...n8()}})}}},Mj={id:"svelte",extensions:[".svelte"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($){let Z=await N6(d0("svelteserver"),"svelte-language-server");if(!Z)return;return{process:M6(Z,["--stdio"],$),initialization:{}}}},Dj={id:"astro",extensions:[".astro"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($,Z){let J=wZ.resolve("typescript/lib/tsserver.js",Z.directory);if(!J){Q0.info("typescript not found, required for Astro language server");return}let Y=w8.dirname(J),X=await N6(d0("astro-ls"),"@astrojs/language-server");if(!X)return;return{process:M6(X,["--stdio"],$),initialization:{typescript:{tsdk:Y}}}}},wj={id:"yaml-ls",extensions:[".yaml",".yml"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($){let Z=await N6(d0("yaml-language-server"),"yaml-language-server");if(!Z)return;return{process:M6(Z,["--stdio"],$)}}},Lj={id:"lua-ls",root:t0([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn($){let Z=d0("lua-language-server");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading lua-language-server from GitHub releases");let J=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!J.ok){Q0.error("Failed to fetch lua-language-server release info");return}let Y=await J.json(),X=process.platform,Q=process.arch,G="",W=Q;if(Q==="arm64")W="arm64";else if(Q==="x64")W="x64";else if(Q==="ia32")W="ia32";let K=X;if(X==="darwin")K="darwin";else if(X==="linux")K="linux";else if(X==="win32")K="win32";let V=X==="win32"?"zip":"tar.gz";G=`lua-language-server-${Y.tag_name}-${K}-${W}.${V}`;let U=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],H=`${K}-${W}.${V}`;if(!U.includes(H)){Q0.error(`Platform ${X} and architecture ${Q} is not supported by lua-language-server`);return}let B=Y.assets.find((L)=>L.name===G);if(!B){Q0.error(`Could not find asset ${G} in latest lua-language-server release`);return}let z=B.browser_download_url,F=await fetch(z);if(!F.ok){Q0.error("Failed to download lua-language-server");return}let A=w8.join(F0.Path.bin,G);if(F.body)await o0.writeStream(A,F.body);let j=w8.join(F0.Path.bin,`lua-language-server-${W}-${K}`);if(await D6.stat(j).catch(()=>{return}))await D6.rm(j,{force:!0,recursive:!0});if(await D6.mkdir(j,{recursive:!0}),V==="zip"){if(!await D8.extractZip(A,j).then(()=>!0).catch((q)=>{return Q0.error("Failed to extract lua-language-server archive",{error:q}),!1}))return}else if(!await j6(["tar","-xzf",A,"-C",j]).then((q)=>q.code===0).catch((q)=>{return Q0.error("Failed to extract lua-language-server archive",{error:q}),!1}))return;if(await D6.rm(A,{force:!0}),Z=w8.join(j,"bin","lua-language-server"+(X==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract lua-language-server binary");return}if(X!=="win32"){if(!await D6.chmod(Z,493).then(()=>!0).catch((q)=>{return Q0.error("Failed to set executable permission for lua-language-server binary",{error:q}),!1}))return}Q0.info("installed lua-language-server",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},Tj={id:"prisma",extensions:[".prisma"],root:t0(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn($){let Z=d0("prisma");if(!Z){Q0.info("prisma not found, please install prisma");return}return{process:Z1(Z,["language-server"],{cwd:$})}}},Rj={id:"bash",extensions:[".sh",".bash",".zsh",".ksh"],root:async($,Z)=>Z.directory,async spawn($){let Z=await N6(d0("bash-language-server"),"bash-language-server");if(!Z)return;return{process:M6(Z,["start"],$)}}};import $8 from"fs/promises";import o1 from"path";import oc from"os";var Pj={id:"gopls",root:async($,Z)=>{let J=await t0(["go.work"])($,Z);if(J)return J;return t0(["go.mod","go.sum"])($,Z)},extensions:[".go"],async spawn($){let Z=d0("gopls");if(!Z){if(!d0("go"))return;if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing gopls"),await f1.spawn(["go","install","golang.org/x/tools/gopls@latest"],{env:{GOBIN:F0.Path.bin},stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install gopls");return}Z=o1.join(F0.Path.bin,"gopls"+(process.platform==="win32"?".exe":"")),Q0.info("installed gopls",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},Ij={id:"csharp",root:t0([".slnx",".sln",".csproj","global.json"]),extensions:[".cs"],async spawn($){let Z=d0("csharp-ls");if(!Z){if(!d0("dotnet")){Q0.error(".NET SDK is required to install csharp-ls");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing csharp-ls via dotnet tool"),await f1.spawn(["dotnet","tool","install","csharp-ls","--tool-path",F0.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install csharp-ls");return}Z=o1.join(F0.Path.bin,"csharp-ls"+(process.platform==="win32"?".exe":"")),Q0.info("installed csharp-ls",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},Cj={id:"fsharp",root:t0([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn($){let Z=d0("fsautocomplete");if(!Z){if(!d0("dotnet")){Q0.error(".NET SDK is required to install fsautocomplete");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing fsautocomplete via dotnet tool"),await f1.spawn(["dotnet","tool","install","fsautocomplete","--tool-path",F0.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install fsautocomplete");return}Z=o1.join(F0.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":"")),Q0.info("installed fsautocomplete",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},Ej={id:"sourcekit-lsp",extensions:[".swift",".objc","objcpp"],root:t0(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn($){let Z=d0("sourcekit-lsp");if(Z)return{process:Z1(Z,{cwd:$})};if(!d0("xcrun"))return;let J=await zj(["xcrun","--find","sourcekit-lsp"]);if(J.code!==0)return;let Y=J.text.trim();return{process:Z1(Y,{cwd:$})}}},bj={id:"rust",root:async($,Z)=>{let J=await t0(["Cargo.toml","Cargo.lock"])($,Z);if(J===void 0)return;let Y=J;while(Y!==o1.dirname(Y)){let X=o1.join(Y,"Cargo.toml");try{if((await o0.readText(X)).includes("[workspace]"))return Y}catch{}let Q=o1.dirname(Y);if(Q===Y||!o0.contains(Z.worktree,Q))break;Y=Q}return J},extensions:[".rs"],async spawn($){let Z=d0("rust-analyzer");if(!Z){Q0.info("rust-analyzer not found in path, please install it");return}return{process:Z1(Z,{cwd:$})}}},_j={id:"clangd",root:t0(["compile_commands.json","compile_flags.txt",".clangd"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn($){let Z=["--background-index","--clang-tidy"],J=d0("clangd");if(J)return{process:Z1(J,Z,{cwd:$})};let Y=process.platform==="win32"?".exe":"",X=o1.join(F0.Path.bin,"clangd"+Y);if(await o0.exists(X))return{process:Z1(X,Z,{cwd:$})};let Q=await $8.readdir(F0.Path.bin,{withFileTypes:!0}).catch(()=>[]);for(let R of Q){if(!R.isDirectory())continue;if(!R.name.startsWith("clangd_"))continue;let w=o1.join(F0.Path.bin,R.name,"bin","clangd"+Y);if(await o0.exists(w))return{process:Z1(w,Z,{cwd:$})}}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading clangd from GitHub releases");let G=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!G.ok){Q0.error("Failed to fetch clangd release info");return}let W=await G.json(),K=W.tag_name;if(!K){Q0.error("clangd release did not include a tag name");return}let V=process.platform,H={darwin:"mac",linux:"linux",win32:"windows"}[V];if(!H){Q0.error(`Platform ${V} is not supported by clangd auto-download`);return}let B=W.assets??[],z=(R)=>{if(!R.name)return!1;if(!R.browser_download_url)return!1;if(!R.name.includes(H))return!1;return R.name.includes(K)},F=B.find((R)=>z(R)&&R.name?.endsWith(".zip"))??B.find((R)=>z(R)&&R.name?.endsWith(".tar.xz"))??B.find((R)=>z(R));if(!F?.name||!F.browser_download_url){Q0.error("clangd could not match release asset",{tag:K,platform:V});return}let A=F.name,j=await fetch(F.browser_download_url);if(!j.ok){Q0.error("Failed to download clangd");return}let N=o1.join(F0.Path.bin,A),L=await j.arrayBuffer();if(L.byteLength===0){Q0.error("Failed to write clangd archive");return}await o0.write(N,Buffer.from(L));let q=A.endsWith(".zip"),M=A.endsWith(".tar.xz");if(!q&&!M){Q0.error("clangd encountered unsupported asset",{asset:A});return}if(q){if(!await D8.extractZip(N,F0.Path.bin).then(()=>!0).catch((w)=>{return Q0.error("Failed to extract clangd archive",{error:w}),!1}))return}if(M)await j6(["tar","-xf",N],{cwd:F0.Path.bin});await $8.rm(N,{force:!0});let C=o1.join(F0.Path.bin,"clangd_"+K,"bin","clangd"+Y);if(!await o0.exists(C)){Q0.error("Failed to extract clangd binary");return}if(V!=="win32")await $8.chmod(C,493).catch(()=>{});return await $8.unlink(o1.join(F0.Path.bin,"clangd")).catch(()=>{}),await $8.symlink(C,o1.join(F0.Path.bin,"clangd")).catch(()=>{}),Q0.info("installed clangd",{bin:C}),{process:Z1(C,Z,{cwd:$})}}},Sj={id:"jdtls",root:async($,Z)=>{let J=["settings.gradle","settings.gradle.kts"],Y=["gradlew","gradlew.bat"],X=Y.concat(J),[Q,G,W]=await Promise.all([t0(["pom.xml","build.gradle","build.gradle.kts",".project",".classpath"],X)($,Z),t0(Y,J)($,Z),t0(J)($,Z)]);if(Q)return Q;if(G)return G;if(W)return W},extensions:[".java"],async spawn($){let Z=d0("java");if(!Z){Q0.error("Java 21 or newer is required to run the JDTLS. Please install it first.");return}let J=await j6(["java","-version"]).then((U)=>{let H=/"(\d+)\.\d+\.\d+"/.exec(U.stderr.toString());return!H?void 0:parseInt(H[1])});if(J==null||J<21){Q0.error("JDTLS requires at least Java 21.");return}let Y=o1.join(F0.Path.bin,"jdtls"),X=o1.join(Y,"plugins");if(!await gV(X)){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("Downloading JDTLS LSP server."),await $8.mkdir(Y,{recursive:!0});let U="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",H="release.tar.gz";Q0.info("Downloading JDTLS archive",{url:U,dest:Y});let B=await fetch(U);if(!B.ok||!B.body){Q0.error("Failed to download JDTLS",{status:B.status,statusText:B.statusText});return}await o0.writeStream(o1.join(Y,H),B.body),Q0.info("Extracting JDTLS archive");let z=await j6(["tar","-xzf",H],{cwd:Y});if(z.code!==0){Q0.error("Failed to extract JDTLS",{exitCode:z.code,stderr:z.stderr.toString()});return}await $8.rm(o1.join(Y,H),{force:!0}),Q0.info("JDTLS download and extraction completed")}let G=(await $8.readdir(X).catch(()=>[])).find((U)=>/^org\.eclipse\.equinox\.launcher_.*\.jar$/.test(U))?.trim()??"",W=o1.join(X,G);if(!await gV(W)){Q0.error(`Failed to locate the JDTLS launcher module in the installed directory: ${Y}.`);return}let K=o1.join(Y,(()=>{switch(process.platform){case"darwin":return"config_mac";case"linux":return"config_linux";case"win32":return"config_win";default:return"config_linux"}})()),V=await $8.mkdtemp(o1.join(oc.tmpdir(),"qitqode-jdtls-data"));return{process:Z1(Z,["-jar",W,"-configuration",K,"-data",V,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens java.base/java.util=ALL-UNNAMED","--add-opens java.base/java.lang=ALL-UNNAMED"],{cwd:$})}}},fj={id:"kotlin-ls",extensions:[".kt",".kts"],root:async($,Z)=>{let J=await t0(["settings.gradle.kts","settings.gradle"])($,Z);if(J)return J;let Y=await t0(["gradlew","gradlew.bat"])($,Z);if(Y)return Y;let X=await t0(["build.gradle.kts","build.gradle"])($,Z);if(X)return X;return t0(["pom.xml"])($,Z)},async spawn($){let Z=o1.join(F0.Path.bin,"kotlin-ls"),J=process.platform==="win32"?o1.join(Z,"kotlin-lsp.cmd"):o1.join(Z,"kotlin-lsp.sh");if(!await o0.exists(J)){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("Downloading Kotlin Language Server from GitHub.");let X=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!X.ok){Q0.error("Failed to fetch kotlin-lsp release info");return}let G=(await X.json()).name?.replace(/^v/,"");if(!G){Q0.error("Could not determine Kotlin LSP version from release");return}let{platform:W,arch:K}=process,V=K;if(K==="arm64")V="aarch64";else if(K==="x64")V="x64";let U=W;if(W==="darwin")U="mac";else if(W==="linux")U="linux";else if(W==="win32")U="win";let H=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],B=`${U}-${V}`;if(!H.includes(B)){Q0.error(`Platform ${W}/${K} is not supported by Kotlin LSP`);return}let z=`kotlin-lsp-${G}-${U}-${V}.zip`,F=`https://download-cdn.jetbrains.com/kotlin-lsp/${G}/${z}`;await $8.mkdir(Z,{recursive:!0});let A=o1.join(Z,"kotlin-ls.zip"),j=await fetch(F);if(!j.ok||!j.body){Q0.error("Failed to download Kotlin Language Server",{status:j.status,statusText:j.statusText});return}if(await o0.writeStream(A,j.body),!await D8.extractZip(A,Z).then(()=>!0).catch((L)=>{return Q0.error("Failed to extract Kotlin LS archive",{error:L}),!1}))return;if(await $8.rm(A,{force:!0}),process.platform!=="win32")await $8.chmod(J,493).catch(()=>{});Q0.info("Installed Kotlin Language Server",{path:J})}if(!await o0.exists(J)){Q0.error(`Failed to locate the Kotlin LS launcher script in the installed directory: ${Z}.`);return}return{process:Z1(J,["--stdio"],{cwd:$})}}},kj={id:"dart",extensions:[".dart"],root:t0(["pubspec.yaml","analysis_options.yaml"]),async spawn($){let Z=d0("dart");if(!Z){Q0.info("dart not found, please install dart first");return}return{process:Z1(Z,["language-server","--lsp"],{cwd:$})}}},vj={id:"ocaml-lsp",extensions:[".ml",".mli"],root:t0(["dune-project","dune-workspace",".merlin","opam"]),async spawn($){let Z=d0("ocamllsp");if(!Z){Q0.info("ocamllsp not found, please install ocaml-lsp-server");return}return{process:Z1(Z,{cwd:$})}}},yj={id:"gleam",extensions:[".gleam"],root:t0(["gleam.toml"]),async spawn($){let Z=d0("gleam");if(!Z){Q0.info("gleam not found, please install gleam first");return}return{process:Z1(Z,["lsp"],{cwd:$})}}},xj={id:"zls",extensions:[".zig",".zon"],root:t0(["build.zig"]),async spawn($){let Z=d0("zls");if(!Z){if(!d0("zig")){Q0.error("Zig is required to use zls. Please install Zig first.");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading zls from GitHub releases");let Y=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!Y.ok){Q0.error("Failed to fetch zls release info");return}let X=await Y.json(),Q=process.platform,G=process.arch,W="",K=G;if(G==="arm64")K="aarch64";else if(G==="x64")K="x86_64";else if(G==="ia32")K="x86";let V=Q;if(Q==="darwin")V="macos";else if(Q==="win32")V="windows";let U=Q==="win32"?"zip":"tar.xz";if(W=`zls-${K}-${V}.${U}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(W)){Q0.error(`Platform ${Q} and architecture ${G} is not supported by zls`);return}let B=X.assets?.find((F)=>F.name===W);if(!B?.browser_download_url){Q0.error(`Could not find asset ${W} in latest zls release`);return}let z=await LZ(B.browser_download_url,W,"zls");if(!z)return;if(U==="zip"){if(!await TZ(z,"zls"))return}else await j6(["tar","-xf",z],{cwd:F0.Path.bin});if(await $8.rm(z,{force:!0}),Z=o1.join(F0.Path.bin,"zls"+(Q==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract zls binary");return}if(Q!=="win32")await $8.chmod(Z,493).catch(()=>{});Q0.info("installed zls",{bin:Z})}return{process:Z1(Z,{cwd:$})}}};import O5 from"fs/promises";import f8 from"path";function sc($){return[process.env.VIRTUAL_ENV,f8.join($,".venv"),f8.join($,"venv")].filter((Z)=>Z!==void 0)}async function uV($,Z){let J=process.platform==="win32";for(let Y of sc($)){let X=J?f8.join(Y,"Scripts",`${Z}.exe`):f8.join(Y,"bin",Z);if(await o0.exists(X))return X}return}var hj={id:"ruby-lsp",root:t0(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn($){let Z=d0("rubocop");if(!Z){let J=d0("ruby"),Y=d0("gem");if(!J||!Y){Q0.info("Ruby not found, please install Ruby first");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing rubocop"),await f1.spawn(["gem","install","rubocop","--bindir",F0.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install rubocop");return}Z=f8.join(F0.Path.bin,"rubocop"+(process.platform==="win32"?".exe":"")),Q0.info("installed rubocop",{bin:Z})}return{process:Z1(Z,["--lsp"],{cwd:$})}}},gj={id:"ty",extensions:[".py",".pyi"],root:t0(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn($){if(!b0.QITQODE_EXPERIMENTAL_LSP_TY)return;let Z=d0("ty"),J={},Y=await uV($,"python");if(Y)J.pythonPath=Y;if(!Z)Z=await uV($,"ty")??null;if(!Z){Q0.error("ty not found, please install ty first");return}return{process:Z1(Z,["server"],{cwd:$}),initialization:J}}},uj={id:"pyright",extensions:[".py",".pyi"],root:t0(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn($){let Z=await N6(d0("pyright-langserver"),"pyright");if(!Z)return;let J=["--stdio"],Y={},X=await uV($,"python");if(X)Y.pythonPath=X;return{process:M6(Z,J,$),initialization:Y}}},mj={id:"elixir-ls",extensions:[".ex",".exs"],root:t0(["mix.exs","mix.lock"]),async spawn($){let Z=d0("elixir-ls");if(!Z){let J=f8.join(F0.Path.bin,"elixir-ls");if(Z=f8.join(F0.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await o0.exists(Z)){if(!d0("elixir")){Q0.error("elixir is required to run elixir-ls");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading elixir-ls from GitHub releases");let X=await LZ("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip","elixir-ls.zip","elixir-ls");if(!X)return;if(!await TZ(X,"elixir-ls"))return;await O5.rm(X,{force:!0,recursive:!0});let G=f8.join(F0.Path.bin,"elixir-ls-master"),W={MIX_ENV:"prod",...n8()};await f1.run(["mix","deps.get"],{cwd:G,env:W}),await f1.run(["mix","compile"],{cwd:G,env:W}),await f1.run(["mix","elixir_ls.release2","-o","release"],{cwd:G,env:W}),Q0.info("installed elixir-ls",{path:J})}}return{process:Z1(Z,{cwd:$})}}},lj={id:"php intelephense",extensions:[".php"],root:t0(["composer.json","composer.lock",".php-version"]),async spawn($){let Z=await N6(d0("intelephense"),"intelephense");if(!Z)return;return{process:M6(Z,["--stdio"],$),initialization:{telemetry:{enabled:!1}}}}},dj={id:"julials",extensions:[".jl"],root:t0(["Project.toml","Manifest.toml","*.jl"]),async spawn($){let Z=d0("julia");if(!Z){Q0.info("julia not found, please install julia first (https://julialang.org/downloads/)");return}return{process:Z1(Z,["--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],{cwd:$})}}},pj={id:"haskell-language-server",extensions:[".hs",".lhs"],root:t0(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn($){let Z=d0("haskell-language-server-wrapper");if(!Z){Q0.info("haskell-language-server-wrapper not found, please install haskell-language-server");return}return{process:Z1(Z,["--lsp"],{cwd:$})}}},cj={id:"nixd",extensions:[".nix"],root:async($,Z)=>{let J=await t0(["flake.nix"])($,Z);if(J&&J!==Z.directory)return J;if(Z.worktree&&Z.worktree!==Z.directory)return Z.worktree;return Z.directory},async spawn($){let Z=d0("nixd");if(!Z){Q0.info("nixd not found, please install nixd first");return}return{process:Z1(Z,[],{cwd:$,env:{...n8()}})}}},ij={id:"tinymist",extensions:[".typ",".typc"],root:t0(["typst.toml"]),async spawn($){let Z=d0("tinymist");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading tinymist from GitHub releases");let J=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!J.ok){Q0.error("Failed to fetch tinymist release info");return}let Y=await J.json(),X=process.platform,G=process.arch==="arm64"?"aarch64":"x86_64",W,K;if(X==="darwin")W="apple-darwin",K="tar.gz";else if(X==="win32")W="pc-windows-msvc",K="zip";else W="unknown-linux-gnu",K="tar.gz";let V=`tinymist-${G}-${W}.${K}`,H=(Y.assets??[]).find((z)=>z.name===V);if(!H?.browser_download_url){Q0.error(`Could not find asset ${V} in tinymist release`);return}let B=await LZ(H.browser_download_url,V,"tinymist");if(!B)return;if(K==="zip"){if(!await TZ(B,"tinymist"))return}else await j6(["tar","-xzf",B,"--strip-components=1"],{cwd:F0.Path.bin});if(await O5.rm(B,{force:!0}),Z=f8.join(F0.Path.bin,"tinymist"+(X==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract tinymist binary");return}if(X!=="win32")await O5.chmod(Z,493).catch(()=>{});Q0.info("installed tinymist",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},nj={id:"terraform",extensions:[".tf",".tfvars"],root:t0([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn($){let Z=d0("terraform-ls");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading terraform-ls from HashiCorp releases");let J=await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest");if(!J.ok){Q0.error("Failed to fetch terraform-ls release info");return}let Y=await J.json(),X=process.platform,G=process.arch==="arm64"?"arm64":"amd64",W=X==="win32"?"windows":X,V=(Y.builds??[]).find((z)=>z.arch===G&&z.os===W);if(!V?.url){Q0.error(`Could not find build for ${W}/${G} terraform-ls release version ${Y.version}`);return}let U=await fetch(V.url);if(!U.ok){Q0.error("Failed to download terraform-ls");return}let H=f8.join(F0.Path.bin,"terraform-ls.zip");if(U.body)await o0.writeStream(H,U.body);if(!await D8.extractZip(H,F0.Path.bin).then(()=>!0).catch((z)=>{return Q0.error("Failed to extract terraform-ls archive",{error:z}),!1}))return;if(await O5.rm(H,{force:!0}),Z=f8.join(F0.Path.bin,"terraform-ls"+(X==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract terraform-ls binary");return}if(X!=="win32")await O5.chmod(Z,493).catch(()=>{});Q0.info("installed terraform-ls",{bin:Z})}return{process:Z1(Z,["serve"],{cwd:$}),initialization:{experimentalFeatures:{prefillRequiredFields:!0,validateOnSave:!0}}}}},oj={id:"texlab",extensions:[".tex",".bib"],root:t0([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn($){let Z=d0("texlab");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading texlab from GitHub releases");let J=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!J.ok){Q0.error("Failed to fetch texlab release info");return}let Y=await J.json();if(!Y.tag_name?.replace("v","")){Q0.error("texlab release did not include a version tag");return}let Q=process.platform,W=process.arch==="arm64"?"aarch64":"x86_64",K=Q==="darwin"?"macos":Q==="win32"?"windows":"linux",V=Q==="win32"?"zip":"tar.gz",U=`texlab-${W}-${K}.${V}`,B=(Y.assets??[]).find((F)=>F.name===U);if(!B?.browser_download_url){Q0.error(`Could not find asset ${U} in texlab release`);return}let z=await LZ(B.browser_download_url,U,"texlab");if(!z)return;if(V==="zip"){if(!await TZ(z,"texlab"))return}if(V==="tar.gz")await j6(["tar","-xzf",z],{cwd:F0.Path.bin});if(await O5.rm(z,{force:!0}),Z=f8.join(F0.Path.bin,"texlab"+(Q==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract texlab binary");return}if(Q!=="win32")await O5.chmod(Z,493).catch(()=>{});Q0.info("installed texlab",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},sj={id:"dockerfile",extensions:[".dockerfile","Dockerfile"],root:async($,Z)=>Z.directory,async spawn($){let Z=await N6(d0("docker-langserver"),"dockerfile-language-server-nodejs");if(!Z)return;return{process:M6(Z,["--stdio"],$)}}},rj={id:"clojure-lsp",extensions:[".clj",".cljs",".cljc",".edn"],root:t0(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn($){let Z=d0("clojure-lsp");if(!Z&&process.platform==="win32")Z=d0("clojure-lsp.exe");if(!Z){Q0.info("clojure-lsp not found, please install clojure-lsp first");return}return{process:Z1(Z,["listen"],{cwd:$})}}};var X8={};F1(X8,{layer:()=>Dw,defaultLayer:()=>Ya,Service:()=>Z4,Server:()=>$a,Layout:()=>Za,Info:()=>E5,ConfigDirectoryTypoError:()=>Ja});import tr from"path";var k8={};F1(k8,{sweepStaleAuthTmp:()=>tj,layer:()=>$N,defaultLayer:()=>tc,WellKnown:()=>cV,Service:()=>_9,Oauth:()=>dV,OAUTH_DUMMY_KEY:()=>lV,Info:()=>ej,AuthError:()=>S9,Auth:()=>k8,Api:()=>pV});import rc from"path";var lV="qitqode-oauth-dummy-key",b9=rc.join(F0.Path.data,"auth.json"),ac=60000;async function tj(){let $=b9+".tmp";try{let{stat:Z,unlink:J}=await import("fs/promises"),Y=await Z($);if(Date.now()-Y.mtimeMs>=ac)await J($).catch(()=>{return})}catch{}}var E9=($)=>(Z)=>new S9({message:$,cause:Z});class dV extends O.Class("OAuth")({type:O.Literal("oauth"),refresh:O.String,access:O.String,expires:O.Number,accountId:O.optional(O.String),enterpriseUrl:O.optional(O.String)}){}class pV extends O.Class("ApiAuth")({type:O.Literal("api"),key:O.String,metadata:O.optional(O.Record(O.String,O.String))}){}class cV extends O.Class("WellKnownAuth")({type:O.Literal("wellknown"),key:O.String,token:O.String}){}var aj=O.Union([dV,pV,cV]).annotate({discriminator:"type",identifier:"Auth"}),ej=Object.assign(aj,{zod:w0(aj)});class S9 extends O.TaggedErrorClass()("AuthError",{message:O.String,cause:O.optional(O.Defect)}){}class _9 extends S1.Service()("@qitqode/Auth"){}var $N=T0.effect(_9,T.gen(function*(){let $=yield*D$.Service,Z=O.decodeUnknownOption(ej);yield*T.promise(()=>tj());let J=T.fn("Auth.readFile")(function*(){let V=yield*$.readJson(b9).pipe(T.orElseSucceed(()=>({})));if(!k7.isEnvelope(V))return V;let U=yield*T.promise(()=>k7.encryptionKey());if(!U)return yield*T.fail(new S9({message:"auth.json is encrypted but the OS keyring is unavailable. Restore keyring access or delete auth.json and log in again."}));return yield*T.try({try:()=>JSON.parse(k7.decrypt(V,U)),catch:E9("Failed to decrypt auth data (keyring key mismatch?)")})}),Y=T.fn("Auth.writeFile")(function*(V){let U=yield*T.promise(()=>k7.encryptionKey()),H=U?k7.encrypt(JSON.stringify(V),U):V,B=b9+".tmp";yield*$.writeJson(B,H).pipe(T.mapError(E9("Failed to write auth data"))),yield*$.chmod(B,384).pipe(T.mapError(E9("Failed to set auth file permissions"))),yield*$.rename(B,b9).pipe(T.mapError(E9("Failed to atomically replace auth data")))}),X=T.fn("Auth.all")(function*(){let V=yield*J(),U=y7.filterMap(V,(H)=>v7.fromOption(Z(H),()=>{return}));if(process.env.QITQODE_AUTH_CONTENT)try{let H=JSON.parse(process.env.QITQODE_AUTH_CONTENT);return{...y7.filterMap(H,(z)=>v7.fromOption(Z(z),()=>{return})),...U}}catch(H){console.error("[Auth] Failed to parse QITQODE_AUTH_CONTENT env var:",H)}return U}),Q=T.fn("Auth.get")(function*(V){return(yield*X())[V]}),G="auth-file",W=T.fn("Auth.set")(function*(V,U){yield*T.scoped(T.gen(function*(){yield*mV.effect(G);let H=V.replace(/\/+$/,""),B=yield*X();if(H!==V)delete B[V];delete B[H+"/"],yield*Y({...B,[H]:U})}))}),K=T.fn("Auth.remove")(function*(V){yield*T.scoped(T.gen(function*(){yield*mV.effect(G);let U=V.replace(/\/+$/,""),H=yield*X();delete H[V],delete H[U],yield*Y(H)}))});return _9.of({get:Q,all:X,set:W,remove:K})})),tc=$N.pipe(T0.provide(D$.defaultLayer));var l6={};F1(l6,{layer:()=>ZN,defaultLayer:()=>ec,Service:()=>f9,Env:()=>l6});class f9 extends S1.Service()("@qitqode/Env"){}var ZN=T0.effect(f9,T.gen(function*(){let $=yield*B0.make(T.fn("Env.state")(()=>T.succeed({...process.env}))),Z=T.fn("Env.get")((Q)=>B0.use($,(G)=>G[Q])),J=T.fn("Env.all")(()=>B0.get($)),Y=T.fn("Env.set")(function*(Q,G){let W=yield*B0.get($);W[Q]=G}),X=T.fn("Env.remove")(function*(Q){let G=yield*B0.get($);delete G[Q]});return f9.of({get:Z,all:J,set:Y,remove:X})})),ec=ZN;var JN={Connected:L1.define("server.connected",P.object({})),Heartbeat:L1.define("server.heartbeat",P.object({})),Disposed:L1.define("global.disposed",P.object({}))};var o7={};F1(o7,{layer:()=>FN,defaultLayer:()=>Qi,UserCode:()=>uY,Service:()=>u9,RefreshToken:()=>x7,PollSuccess:()=>u7,PollSlow:()=>l7,PollResult:()=>YN,PollPending:()=>m7,PollExpired:()=>d7,PollError:()=>c7,PollDenied:()=>p7,OrgID:()=>v9,Org:()=>lY,Login:()=>dY,Info:()=>mY,DeviceCode:()=>h7,AccountTransportError:()=>j5,AccountServiceError:()=>RZ,AccountRepoError:()=>g7,AccountID:()=>hY,Account:()=>o7,AccessToken:()=>gY});var i7={};F1(i7,{layer:()=>$i,Service:()=>x9,AccountRepo:()=>i7});var L8=g6("account",{id:w1().$type().primaryKey(),email:w1().notNull(),url:w1().notNull(),access_token:w1().$type().notNull(),refresh_token:w1().$type().notNull(),token_expiry:j8(),...xY}),q5=g6("account_state",{id:j8().primaryKey(),active_account_id:w1().$type().references(()=>L8.id,{onDelete:"set null"}),active_org_id:w1().$type()}),kT0=g6("control_account",{email:w1().notNull(),url:w1().notNull(),access_token:w1().$type().notNull(),refresh_token:w1().$type().notNull(),token_expiry:j8(),active:j8({mode:"boolean"}).notNull().$default(()=>!1),...xY},($)=>[k9({columns:[$.email,$.url]})]);var hY=O.String.pipe(O.brand("AccountID")),v9=O.String.pipe(O.brand("OrgID")),gY=O.String.pipe(O.brand("AccessToken")),x7=O.String.pipe(O.brand("RefreshToken")),h7=O.String.pipe(O.brand("DeviceCode")),uY=O.String.pipe(O.brand("UserCode"));class mY extends O.Class("Account")({id:hY,email:O.String,url:O.String,active_org_id:O.NullOr(v9)}){}class lY extends O.Class("Org")({id:v9,name:O.String}){}class g7 extends O.TaggedErrorClass()("AccountRepoError",{message:O.String,cause:O.optional(O.Defect)}){}class RZ extends O.TaggedErrorClass()("AccountServiceError",{message:O.String,cause:O.optional(O.Defect)}){}class j5 extends O.TaggedErrorClass()("AccountTransportError",{method:O.String,url:O.String,description:O.optional(O.String),cause:O.optional(O.Defect)}){static fromHttpClientError($){return new j5({method:$.request.method,url:$.request.url,description:$.description,cause:$.cause})}get message(){return[`Could not reach ${this.method} ${this.url}.`,"This failed before the server returned an HTTP response.",this.description,"Check your network, proxy, or VPN configuration and try again."].filter(Boolean).join(`
486
486
  `)}}class dY extends O.Class("Login")({code:h7,user:uY,url:O.String,server:O.String,expiry:O.Duration,interval:O.Duration}){}class u7 extends O.TaggedClass()("PollSuccess",{email:O.String}){}class m7 extends O.TaggedClass()("PollPending",{}){}class l7 extends O.TaggedClass()("PollSlow",{}){}class d7 extends O.TaggedClass()("PollExpired",{}){}class p7 extends O.TaggedClass()("PollDenied",{}){}class c7 extends O.TaggedClass()("PollError",{cause:O.Defect}){}var YN=O.Union([u7,m7,l7,d7,p7,c7]);var y9=($)=>{let Z=new URL($);Z.search="",Z.hash="";let J=Z.pathname.replace(/\/+$/,"");return J.length===0?Z.origin:`${Z.origin}${J}`};var XN=1;class x9 extends S1.Service()("@qitqode/AccountRepo"){}var $i=T0.effect(x9,T.gen(function*(){let $=O.decodeUnknownSync(mY),Z=(B)=>T.try({try:()=>W1.use(B),catch:(z)=>new g7({message:"Database operation failed",cause:z})}),J=(B)=>T.try({try:()=>W1.transaction(B),catch:(z)=>new g7({message:"Database operation failed",cause:z})}),Y=(B)=>{let z=B.select().from(q5).where(m0(q5.id,XN)).get();if(!z?.active_account_id)return;let F=B.select().from(L8).where(m0(L8.id,z.active_account_id)).get();if(!F)return;return{...F,active_org_id:z.active_org_id??null}},X=(B,z,F)=>{let A=O1.getOrNull(F);return B.insert(q5).values({id:XN,active_account_id:z,active_org_id:A}).onConflictDoUpdate({target:q5.id,set:{active_account_id:z,active_org_id:A}}).run()},Q=T.fn("AccountRepo.active")(()=>Z((B)=>Y(B)).pipe(T.map((B)=>B?O1.some($(B)):O1.none()))),G=T.fn("AccountRepo.list")(()=>Z((B)=>B.select().from(L8).all().map((z)=>$({...z,active_org_id:null})))),W=T.fn("AccountRepo.remove")((B)=>J((z)=>{z.update(q5).set({active_account_id:null,active_org_id:null}).where(m0(q5.active_account_id,B)).run(),z.delete(L8).where(m0(L8.id,B)).run()}).pipe(T.asVoid)),K=T.fn("AccountRepo.use")((B,z)=>Z((F)=>X(F,B,z)).pipe(T.asVoid)),V=T.fn("AccountRepo.getRow")((B)=>Z((z)=>z.select().from(L8).where(m0(L8.id,B)).get()).pipe(T.map(O1.fromNullishOr))),U=T.fn("AccountRepo.persistToken")((B)=>Z((z)=>z.update(L8).set({access_token:B.accessToken,refresh_token:B.refreshToken,token_expiry:O1.getOrNull(B.expiry)}).where(m0(L8.id,B.accountID)).run()).pipe(T.asVoid)),H=T.fn("AccountRepo.persistAccount")((B)=>J((z)=>{let F=y9(B.url);z.insert(L8).values({id:B.id,email:B.email,url:F,access_token:B.accessToken,refresh_token:B.refreshToken,token_expiry:B.expiry}).onConflictDoUpdate({target:L8.id,set:{email:B.email,url:F,access_token:B.accessToken,refresh_token:B.refreshToken,token_expiry:B.expiry}}).run(),X(z,B.id,B.orgID)}).pipe(T.asVoid));return x9.of({active:Q,list:G,remove:W,use:K,getRow:V,persistToken:U,persistAccount:H})}));class VN extends O.Class("RemoteConfig")({config:O.Record(O.String,O.Json)}){}var g9=O.Number.pipe(O.decodeTo(O.Duration,{decode:nV.transform(($)=>Z8.seconds($)),encode:nV.transform(($)=>Z8.toSeconds($))}));class UN extends O.Class("TokenRefresh")({access_token:gY,refresh_token:x7,expires_in:g9}){}class HN extends O.Class("DeviceAuth")({device_code:h7,user_code:uY,verification_uri_complete:O.String,expires_in:g9,interval:g9}){}class BN extends O.Class("DeviceTokenSuccess")({access_token:gY,refresh_token:x7,token_type:O.Literal("Bearer"),expires_in:g9}){}class tV extends O.Class("DeviceTokenError")({error:O.String,error_description:O.String}){toPollResult(){if(this.error==="authorization_pending")return new m7;if(this.error==="slow_down")return new l7;if(this.error==="expired_token")return new d7;if(this.error==="access_denied")return new p7;return new c7({cause:this.error})}}var Zi=O.Union([BN,tV]);class zN extends O.Class("User")({id:hY,email:O.String}){}class sV extends O.Class("ClientId")({client_id:O.String}){}class rV extends O.Class("DeviceTokenRequest")({grant_type:O.String,device_code:h7,client_id:O.String}){}class aV extends O.Class("TokenRefreshRequest")({grant_type:O.String,refresh_token:x7,client_id:O.String}){}var iV="opencode-cli",Ji=Z8.minutes(5),Yi=Z8.toMillis(Ji),QN=($,Z)=>$!=null&&$>Z+Yi,o8=($="Account service operation failed")=>(Z)=>Z.pipe(T.mapError((J)=>Xi(J,$))),Xi=($,Z)=>{if($ instanceof RZ||$ instanceof j5)return $;if(GN.isHttpClientError($))switch($.reason._tag){case"TransportError":return j5.fromHttpClientError($.reason);default:return new RZ({message:Z,cause:$})}return new RZ({message:Z,cause:$})};class u9 extends S1.Service()("@qitqode/Account"){}var FN=T0.effect(u9,T.gen(function*(){let $=yield*i7.Service,Z=yield*h9.HttpClient,J=KN(Z),Y=h9.filterStatusOk(Z),X=h9.filterStatusOk(J),Q=(R)=>J.execute(R).pipe(o8("HTTP request failed")),G=(R)=>X.execute(R).pipe(o8("HTTP request failed")),W=(R)=>R.pipe(T.flatMap((w)=>Y.execute(w)),o8("HTTP request failed")),K=(R)=>R.pipe(T.flatMap((w)=>Z.execute(w)),o8("HTTP request failed")),V=T.fnUntraced(function*(R){let w=yield*n7.currentTimeMillis,I=yield*W(V$.post(`${R.url}/auth/device/token`).pipe(V$.acceptJson,V$.schemaBodyJson(aV)(new aV({grant_type:"refresh_token",refresh_token:R.refresh_token,client_id:iV})))),_=yield*PZ.schemaBodyJson(UN)(I).pipe(o8("Failed to decode response")),E=O1.some(w+Z8.toMillis(_.expires_in));return yield*$.persistToken({accountID:R.id,accessToken:_.access_token,refreshToken:_.refresh_token,expiry:E}),_.access_token}),U=yield*oV.make({capacity:Number.POSITIVE_INFINITY,timeToLive:Z8.zero,lookup:T.fnUntraced(function*(R){let w=yield*$.getRow(R);if(O1.isNone(w))return yield*T.fail(new RZ({message:"Account not found during token refresh"}));let I=w.value,_=yield*n7.currentTimeMillis;if(QN(I.token_expiry,_))return I.access_token;return yield*V(I)})}),H=T.fnUntraced(function*(R){let w=yield*n7.currentTimeMillis;if(QN(R.token_expiry,w))return R.access_token;return yield*oV.get(U,R.id)}),B=T.fnUntraced(function*(R){let w=yield*$.getRow(R);if(O1.isNone(w))return O1.none();let I=w.value,_=yield*H(I);return O1.some({account:I,accessToken:_})}),z=T.fnUntraced(function*(R,w){let I=yield*G(V$.get(`${R}/api/orgs`).pipe(V$.acceptJson,V$.bearerToken(w)));return yield*PZ.schemaBodyJson(O.Array(lY))(I).pipe(o8("Failed to decode response"))}),F=T.fnUntraced(function*(R,w){let I=yield*G(V$.get(`${R}/api/user`).pipe(V$.acceptJson,V$.bearerToken(w)));return yield*PZ.schemaBodyJson(zN)(I).pipe(o8("Failed to decode response"))}),A=T.fn("Account.token")((R)=>B(R).pipe(T.map(O1.map((w)=>w.accessToken)))),j=T.fn("Account.activeOrg")(function*(){let R=yield*$.active();if(O1.isNone(R))return O1.none();let w=R.value;if(!w.active_org_id)return O1.none();let _=(yield*L(w.id)).find((E)=>E.id===w.active_org_id);if(!_)return O1.none();return O1.some({account:w,org:_})}),N=T.fn("Account.orgsByAccount")(function*(){let R=yield*$.list();return yield*T.forEach(R,(w)=>L(w.id).pipe(T.catch(()=>T.succeed([])),T.map((I)=>({account:w,orgs:I}))),{concurrency:3})}),L=T.fn("Account.orgs")(function*(R){let w=yield*B(R);if(O1.isNone(w))return[];let{account:I,accessToken:_}=w.value;return yield*z(I.url,_)}),q=T.fn("Account.config")(function*(R,w){let I=yield*B(R);if(O1.isNone(I))return O1.none();let{account:_,accessToken:E}=I.value,f=yield*Q(V$.get(`${_.url}/api/config`).pipe(V$.acceptJson,V$.bearerToken(E),V$.setHeaders({"x-org-id":w})));if(f.status===404)return O1.none();let b=yield*PZ.filterStatusOk(f).pipe(o8()),y=yield*PZ.schemaBodyJson(VN)(b).pipe(o8("Failed to decode response"));return O1.some(y.config)}),M=T.fn("Account.login")(function*(R){let w=y9(R),I=yield*W(V$.post(`${w}/auth/device/code`).pipe(V$.acceptJson,V$.schemaBodyJson(sV)(new sV({client_id:iV})))),_=yield*PZ.schemaBodyJson(HN)(I).pipe(o8("Failed to decode response"));return new dY({code:_.device_code,user:_.user_code,url:`${w}${_.verification_uri_complete}`,server:w,expiry:_.expires_in,interval:_.interval})}),C=T.fn("Account.poll")(function*(R){let w=yield*K(V$.post(`${R.server}/auth/device/token`).pipe(V$.acceptJson,V$.schemaBodyJson(rV)(new rV({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:R.code,client_id:iV})))),I=yield*PZ.schemaBodyJson(Zi)(w).pipe(o8("Failed to decode response"));if(I instanceof tV)return I.toPollResult();let _=I.access_token,E=F(R.server,_),f=z(R.server,_),[b,y]=yield*T.all([E,f],{concurrency:2}),k=y.length>0?O1.some(y[0].id):O1.none(),d=(yield*n7.currentTimeMillis)+Z8.toMillis(I.expires_in),p=I.refresh_token;return yield*$.persistAccount({id:b.id,email:b.email,url:R.server,accessToken:_,refreshToken:p,expiry:d,orgID:k}),new u7({email:b.email})});return u9.of({active:$.active,activeOrg:j,list:$.list,orgsByAccount:N,remove:$.remove,use:$.use,orgs:L,config:q,token:A,login:M,poll:C})})),Qi=FN.pipe(T0.provide(i7.layer),T0.provide(WN.layer));import Gi from"path";async function qN(){let $=["qitqode.jsonc","qitqode.json","config.json"].map((Z)=>Gi.join(F0.Path.config,Z));for(let Z of $)if(await o0.exists(Z))return Z;return $[0]}function eV($,Z,J=[]){if(!J8(Z)){let Y=AN($,J,Z,{formattingOptions:{insertSpaces:!0,tabSize:2}});return ON($,Y)}return Object.entries(Z).reduce((Y,[X,Q])=>{if(Q===void 0)return Y;return eV(Y,Q,[...J,X])},$)}function s7($){let{plugin_origins:Z,mcp_origins:J,...Y}=$;return Y}var Wi=E0.create({service:"config.sources"});function jN($,Z){if(!J8($))return $;let J={...$};if(!(("theme"in J)||("keybinds"in J)||("tui"in J)))return J;return delete J.theme,delete J.keybinds,delete J.tui,Wi.warn("tui keys in qitqode config are deprecated; move them to tui.json",{path:Z}),J}async function NN($,Z){if(!$.plugin)return $;for(let J=0;J<$.plugin.length;J++)$.plugin[J]=await s8.resolvePluginSpec($.plugin[J],Z);return $}var Ki=E0.create({service:"config.loader"});function MN($){let Z=T.fnUntraced(function*(X){return yield*$.fs.readFileString(X).pipe(T.catchIf((Q)=>Q.reason._tag==="NotFound",()=>T.succeed(void 0)),T.orDie)}),J=T.fnUntraced(function*(X,Q){let G="path"in Q?Q.path:Q.source,W=yield*T.promise(()=>$U.substitute("path"in Q?{text:X,type:"path",path:Q.path}:{text:X,type:"virtual",...Q})),K=r8.jsonc(W,G),V=r8.schema($.info,jN(K,G),G);if(!("path"in Q))return V;if(yield*T.promise(()=>NN(V,Q.path)),!V.$schema){V.$schema="https://opencode.ai/config.json";let U=X.replace(/^\s*\{/,`{
487
487
  "$schema": "https://opencode.ai/config.json",`);yield*$.fs.writeFileString(Q.path,U).pipe(T.catch(()=>T.void))}return V}),Y=T.fnUntraced(function*(X){Ki.info("loading",{path:X});let Q=yield*Z(X);if(!Q)return{};return yield*J(Q,{path:X})});return{readConfigFile:Z,loadConfig:J,loadFile:Y}}import pY from"path";import{pathToFileURL as Vi}from"url";import ZU from"fs/promises";function wN($){return T.fnUntraced(function*(){let Z=DN({},N1(yield*$(pY.join(F0.Path.config,"config.json"))),N1(yield*$(pY.join(F0.Path.config,"qitqode.json"))),N1(yield*$(pY.join(F0.Path.config,"qitqode.jsonc")))),J=pY.join(F0.Path.config,"config");if(!(yield*T.promise(()=>ZU.access(J).then(()=>!0,()=>!1))))return Z;return yield*T.promise(()=>import(Vi(J).href,{with:{type:"toml"}}).then(async(X)=>{let{provider:Q,model:G,...W}=X.default;if(Q&&G)Z.model=`${Q}/${G}`;Z.$schema="https://opencode.ai/config.json",Z=N1(Z,W),await ZU.writeFile(pY.join(F0.Path.config,"config.json"),JSON.stringify(Z,null,2)),await ZU.unlink(J)}).catch(()=>{})),Z})}import fZ from"path";import lr from"os";function m9($,Z){let J=N1($,Z);if($.instructions&&Z.instructions)J.instructions=Array.from(new Set([...$.instructions,...Z.instructions]));return J}var IZ={};F1(IZ,{redactString:()=>RN,redactCommand:()=>Ai,fromClaude:()=>Fi,Remote:()=>QU,OAuth:()=>XU,Local:()=>YU,Info:()=>Ui,ConfigMCP:()=>IZ});class YU extends O.Class("McpLocalConfig")({type:O.Literal("local").annotate({description:"Type of MCP server connection"}),command:O.mutable(O.Array(O.String)).annotate({description:"Command and arguments to run the MCP server"}),environment:O.optional(O.Record(O.String,O.String)).annotate({description:"Environment variables to set when running the MCP server"}),enabled:O.optional(O.Boolean).annotate({description:"Enable or disable the MCP server on startup"}),timeout:O.optional(O.Number).annotate({description:"Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."})}){static zod=w0(this)}class XU extends O.Class("McpOAuthConfig")({clientId:O.optional(O.String).annotate({description:"OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."}),clientSecret:O.optional(O.String).annotate({description:"OAuth client secret (if required by the authorization server)"}),scope:O.optional(O.String).annotate({description:"OAuth scopes to request during authorization"}),redirectUri:O.optional(O.String).annotate({description:"OAuth redirect URI (default: http://127.0.0.1:19876/mcp/oauth/callback)."})}){static zod=w0(this)}class QU extends O.Class("McpRemoteConfig")({type:O.Literal("remote").annotate({description:"Type of MCP server connection"}),url:O.String.annotate({description:"URL of the remote MCP server"}),enabled:O.optional(O.Boolean).annotate({description:"Enable or disable the MCP server on startup"}),headers:O.optional(O.Record(O.String,O.String)).annotate({description:"Headers to send with the request"}),oauth:O.optional(O.Union([XU,O.Literal(!1)])).annotate({description:"OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection."}),timeout:O.optional(O.Number).annotate({description:"Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."})}){static zod=w0(this)}var Ui=O.Union([YU,QU]).annotate({discriminator:"type"}).pipe(u0(($)=>({zod:w0($)}))),LN=new Set(["http","streamable-http","remote"]),TN=new Set(["stdio","local"]),Hi=["authorization","token","api_key","apikey","key","secret","password","credential"];function JU($){if(!J8($))return;return Object.fromEntries(Object.entries($).filter((Z)=>typeof Z[1]==="string"))}function Bi($){return Hi.some((Z)=>$.toLowerCase().includes(Z))}function zi($){if($===!1)return!1;if(!J8($))return;let Z={...typeof $.clientId==="string"&&{clientId:$.clientId},...typeof $.clientSecret==="string"&&{clientSecret:$.clientSecret},...typeof $.scope==="string"&&{scope:$.scope},...typeof $.redirectUri==="string"&&{redirectUri:$.redirectUri}};return Object.keys(Z).length>0?Z:void 0}function Fi($,Z){if(!J8(Z))return{warning:`skipped Claude Code MCP server "${$}"; server config is not an object.`};if(Z.type==="sse")return{warning:`skipped Claude Code MCP server "${$}"; unsupported transport "sse".`};if(Z.args!==void 0&&!Array.isArray(Z.args))return{warning:`skipped Claude Code MCP server "${$}"; args is not an array.`};let J=Array.isArray(Z.args)?Z.args:[];if(!J.every((W)=>typeof W==="string"))return{warning:`skipped Claude Code MCP server "${$}"; args must contain only strings.`};let Y=Z.disabled===!0?!1:Z.enabled===!1?!1:!0,X=JU(Z.environment)??JU(Z.env),Q=typeof Z.timeout==="number"?Z.timeout:void 0,G=typeof Z.type==="string"?Z.type:void 0;if(typeof Z.command==="string"&&(!G||TN.has(G)))return{config:{type:"local",command:[Z.command,...J],...X&&{environment:X},enabled:Y,...Q!==void 0&&{timeout:Q}}};if(Z.command!==void 0)return{warning:`skipped Claude Code MCP server "${$}"; command is not a string.`};if(typeof Z.url==="string"&&(!G||LN.has(G))){let W=JU(Z.headers),K=zi(Z.oauth);return{config:{type:"remote",url:Z.url,enabled:Y,...W&&{headers:W},...K!==void 0&&{oauth:K},...Q!==void 0&&{timeout:Q}}}}if(Z.url!==void 0)return{warning:`skipped Claude Code MCP server "${$}"; url is not a string.`};if(G&&!TN.has(G)&&!LN.has(G))return{warning:`skipped Claude Code MCP server "${$}"; unsupported transport "${G}".`};return{warning:`skipped Claude Code MCP server "${$}"; missing command or url.`}}function RN($){return $.replace(/(Bearer\s+)[^\s]+/gi,"$1****").replace(/([?&][^=\s&]*(?:authorization|token|api[_-]?key|apikey|key|secret|password|credential)[^=\s&]*=)[^&\s]+/gi,"$1****").replace(/((?:authorization|token|api[_-]?key|apikey|key|secret|password|credential)=)[^\s]+/gi,"$1****")}function Ai($){return $.map((Z,J)=>{if(J>0&&Bi($[J-1]))return"****";return RN(Z)})}var GU=E0.create({service:"config.sources"});function PN($){let Z=(G,W,K,V)=>{if(!K.mcp)return G;return{...G,mcp_origins:{...G.mcp_origins??{},...Object.fromEntries(Object.keys(K.mcp).map((U)=>[U,{type:V,source:W}]))}}},J=T.fnUntraced(function*(G,W,K,V){if(!K?.length)return G;let U=V??(yield*$.resolvePluginScope(W)),H=s8.deduplicatePluginOrigins([...G.plugin_origins??[],...K.map((B)=>({spec:B,source:W,scope:U}))]);return{...G,plugin:H.map((B)=>B.spec),plugin_origins:H}}),Y=T.fnUntraced(function*(G,W,K,V){let U=m9(G,K),H=Z(U,W,K,"qitqode");return yield*J(H,W,K.plugin,V)}),X=T.fnUntraced(function*(G){let W=yield*$.readConfigFile(G);if(!W)return;return yield*T.try({try:()=>JSON.parse(W),catch:()=>Error(`failed to parse ${G}; Claude Code MCP compatibility skipped.`)}).pipe(T.tapError((K)=>T.sync(()=>GU.warn(K.message))),T.option,T.map(O1.getOrUndefined))}),Q=T.fnUntraced(function*(G,W){let K=yield*X(W);if(!J8(K)||!J8(K.mcpServers))return G;let V=G;for(let[U,H]of Object.entries(K.mcpServers)){if(V.mcp?.[U]&&V.mcp_origins?.[U]?.type!=="claude"){GU.info(`skipped Claude Code MCP server "${U}"; native qitqode MCP with same name already exists.`);continue}let z=IZ.fromClaude(U,H);if("warning"in z){GU.warn(z.warning);continue}let F=r8.schema($.info,{mcp:{[U]:z.config}},W);V={...V,mcp:{...V.mcp??{},[U]:F.mcp[U]},mcp_origins:{...V.mcp_origins??{},[U]:{type:"claude",source:W}}}}return V});return{merge:Y,mergeMcpOrigins:Z,mergePluginOrigins:J,mergeClaudeMcp:Q}}function IN($,Z){let J=$;for(let[Y,X]of Object.entries(J.mode??{}))J.agent=N1(J.agent??{},{[Y]:{...X,mode:"primary"}});if(Z.permissionOverride)J.permission=N1(J.permission??{},JSON.parse(Z.permissionOverride));if(J.tools){let Y={};for(let[X,Q]of Object.entries(J.tools)){let G=Q?"allow":"deny";if(X==="write"||X==="edit"||X==="patch"||X==="multiedit"){Y.edit=G;continue}Y[X]=G}J.permission=N1(Y,J.permission??{})}if(!J.username)J.username=Z.username;if(J.autoshare===!0&&!J.share)J.share="auto";if(Z.disableAutoCompact)J.compaction={...J.compaction,auto:!1};if(Z.disablePrune)J.compaction={...J.compaction,prune:!1};return J}var c6={};F1(c6,{loadMode:()=>kr,load:()=>fr,Info:()=>_U,ConfigAgent:()=>c6});import CN from"path";function Oi($,Z){let J=$.replaceAll("\\","/");for(let Y of Z){let X=J.indexOf(Y);if(X===-1)continue;return J.slice(X+Y.length)}}function EN($,Z){let J=Oi($,Z)??CN.basename($),Y=CN.extname(J);return Y.length?J.slice(0,-Y.length):J}var bU={};F1(bU,{shell:()=>Dr,parse:()=>EU,files:()=>Mr,fallbackSanitization:()=>rD,SHELL_REGEX:()=>sD,FrontmatterError:()=>eY,FILE_REGEX:()=>oD});var CU=m6(nD(),1);var oD=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,sD=/!`([^`]+)`/g;function Mr($){return Array.from($.matchAll(oD))}function Dr($){return Array.from($.matchAll(sD))}function rD($){let Z=$.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!Z)return $;let J=Z[1],Y=J.split(/\r?\n/),X=[];for(let G of Y){if(G.trim().startsWith("#")||G.trim()===""){X.push(G);continue}if(G.match(/^\s+/)){X.push(G);continue}let W=G.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*(.*)$/);if(!W){X.push(G);continue}let K=W[1],V=W[2].trim();if(V===""||V===">"||V==="|"||V.startsWith('"')||V.startsWith("'")){X.push(G);continue}if(V.includes(":")){X.push(`${K}: |-`),X.push(` ${V}`);continue}X.push(G)}let Q=X.join(`
488
- `);return $.replace(J,()=>Q)}async function EU($){let Z=await o0.readText($);try{return CU.default(Z,{})}catch(J){let Y=rD(Z);if(Y===Z)throw new eY({path:$,message:`${$}: Failed to parse YAML frontmatter: ${J instanceof Error?J.message:String(J)}`},{cause:J});try{return CU.default(Y,{})}catch(X){throw new eY({path:$,message:`${$}: Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`},{cause:X})}}}var eY=j1.create("ConfigFrontmatterError",D.object({path:D.string(),message:D.string()}));var wr=E0.create({service:"config"});function $X($,Z,J,Y){let X=$.safeParse(Z);if(X.success)return X.data;if(Y?.ignoreInvalid)return;throw new aD({path:J,issues:X.error.issues},{cause:X.error})}async function ZX($){for(let Z of await $4.scan($.glob,{cwd:$.dir,absolute:!0,dot:!0,symlink:!0})){let J=await EU(Z).catch(async(Q)=>{let G=eY.isInstance(Q)?Q.data.message:`Failed to parse ${$.entity} ${Z}`,{Session:W}=await import("./chunk-q2q3dmg3.js");l1.publish(W.Event.Error,{error:new j1.Unknown({message:G}).toObject()}),wr.error(`failed to load ${$.entity}`,{[$.entity]:Z,err:Q});return});if(!J)continue;let X={name:EN(Z,$.namePatterns),...J.data,[$.contentKey]:J.content.trim()};$.store(X,Z)}}var T8=O.String.annotate({[F$]:P.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"})}).pipe(u0(($)=>({zod:w0($)})));var _Z={};F1(_Z,{Rule:()=>R8,Object:()=>eD,Info:()=>Ir,ConfigPermission:()=>_Z,Action:()=>p6});var p6=O.Literals(["ask","allow","deny"]).annotate({identifier:"PermissionActionConfig"}).pipe(u0(($)=>({zod:w0($)}))),eD=O.Record(O.String,p6).annotate({identifier:"PermissionObjectConfig"}).pipe(u0(($)=>({zod:w0($)}))),R8=O.Union([p6,eD]).annotate({identifier:"PermissionRuleConfig"}).pipe(u0(($)=>({zod:w0($)}))),Lr=($)=>{if(typeof $==="object"&&$!==null&&!Array.isArray($))return{__originalKeys:globalThis.Object.keys($),...$};return $},Tr=O.StructWithRest(O.Struct({__originalKeys:O.optional(O.mutable(O.Array(O.String))),read:O.optional(R8),edit:O.optional(R8),glob:O.optional(R8),grep:O.optional(R8),list:O.optional(R8),bash:O.optional(R8),task:O.optional(R8),actor:O.optional(R8),external_directory:O.optional(R8),question:O.optional(p6),webfetch:O.optional(p6),websearch:O.optional(p6),codesearch:O.optional(p6),lsp:O.optional(R8),doom_loop:O.optional(p6),skill:O.optional(R8)}),[O.Record(O.String,R8)]),Rr=O.Union([Tr,p6]).annotate({[tD]:Lr}),Pr=($)=>{if(typeof $==="string")return{"*":$};let Z=$,{__originalKeys:J,...Y}=Z;if(!J)return Y;let X={};for(let Q of J)if(Q in Y)X[Q]=Y[Q];return X},Ir=w0(Rr).transform(Pr).meta({ref:"PermissionConfig"});var $w=O.Number.check(O.isInt()).check(O.isGreaterThan(0)),Cr=O.Union([O.String.check(O.isPattern(/^#[0-9a-fA-F]{6}$/)),O.Literals(["primary","secondary","accent","success","warning","error","info"])]),Er=O.Any.annotate({[F$]:_Z.Info}),br=O.StructWithRest(O.Struct({model:O.optional(T8).annotate({description:"Model for this agent: a literal provider/model (e.g. anthropic/claude-opus-4-8) or a tier/group name (e.g. fast/economical/default/power). Names without a '/' are resolved as model groups, provider-aware, at spawn time."}),variant:O.optional(O.String).annotate({description:"Default model variant for this agent (applies only when using the agent's configured model)."}),temperature:O.optional(O.Number),top_p:O.optional(O.Number),prompt:O.optional(O.String),tools:O.optional(O.Record(O.String,O.Boolean)).annotate({description:"@deprecated Use 'permission' field instead"}),disable:O.optional(O.Boolean),description:O.optional(O.String).annotate({description:"Description of when to use the agent"}),mode:O.optional(O.Literals(["subagent","primary","all"])),hidden:O.optional(O.Boolean).annotate({description:"Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"}),options:O.optional(O.Record(O.String,O.Any)),color:O.optional(Cr).annotate({description:"Hex color code (e.g., #FF5733) or theme color (e.g., primary)"}),steps:O.optional($w).annotate({description:"Maximum number of agentic iterations before forcing text-only response"}),tool_allowlist:O.optional(O.Array(O.String)).annotate({description:"Optional list of tool IDs allowed for this agent. When set, only these tools are available."}),maxSteps:O.optional($w).annotate({description:"@deprecated Use 'steps' field instead."}),permission:O.optional(Er)}),[O.Record(O.String,O.Any)]),_r=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools","tool_allowlist"]),Sr=($)=>{let Z={...$.options};for(let[Y,X]of Object.entries($))if(!_r.has(Y))Z[Y]=X;let J={};for(let[Y,X]of Object.entries($.tools??{})){let Q=X?"allow":"deny";if(Y==="write"||Y==="edit"||Y==="patch"||Y==="multiedit"){J.edit=Q;continue}if(Y==="task"){J.actor=Q;continue}J[Y]=Q}return globalThis.Object.assign(J,$.permission),{...$,options:Z,permission:J,steps:$.steps??$.maxSteps}},_U=w0(br).transform(Sr).meta({ref:"AgentConfig"});async function fr($){let Z={};return await ZX({dir:$,glob:"{agent,agents}/**/*.md",entity:"agent",namePatterns:["/.qitqode/agent/","/.qitqode/agents/","/agent/","/agents/"],contentKey:"prompt",store:(J,Y)=>{Z[J.name]=$X(_U,J,Y)}}),Z}async function kr($){let Z={};return await ZX({dir:$,glob:"{mode,modes}/*.md",entity:"mode",namePatterns:[],contentKey:"prompt",store:(J,Y)=>{let X=$X(_U,J,Y,{ignoreInvalid:!0});if(X)Z[J.name]={...X,mode:"primary"}}}),Z}var i6={};F1(i6,{load:()=>vr,Info:()=>Zw,ConfigCommand:()=>i6});var Zw=O.Struct({template:O.String,description:O.optional(O.String),agent:O.optional(O.String),model:O.optional(T8),subtask:O.optional(O.Boolean)}).pipe(u0(($)=>({zod:w0($)})));async function vr($){let Z={};return await ZX({dir:$,glob:"{command,commands}/**/*.md",entity:"command",namePatterns:["/.qitqode/command/","/.qitqode/commands/","/.claude/command/","/.claude/commands/","/command/","/commands/"],contentKey:"template",store:(J,Y)=>{Z[J.name]=$X(Zw.zod,J,Y)}}),Z}var R5={};F1(R5,{readManagedPreferences:()=>mr,parseManagedPlist:()=>Qw,managedConfigDirs:()=>Xw,managedConfigDir:()=>ur,ConfigManaged:()=>R5});import yr from"os";import SU from"path";var Jw=E0.create({service:"config"}),xr="ai.qitqode.managed",hr="ai.opencode.managed",gr=new Set(["PayloadDisplayName","PayloadIdentifier","PayloadType","PayloadUUID","PayloadVersion","_manualProfile"]);function Yw($="qitqode"){switch(process.platform){case"darwin":return`/Library/Application Support/${$}`;case"win32":return SU.join(process.env.ProgramData||"C:\\ProgramData",$);default:return`/etc/${$}`}}function ur(){return Xw().at(-1)}function Xw(){let $=process.env.QITQODE_TEST_MANAGED_CONFIG_DIR;if($)return[$];return[Yw("opencode"),Yw()]}function Qw($){let Z=JSON.parse($);for(let J of Object.keys(Z))if(gr.has(J))delete Z[J];return JSON.stringify(Z)}async function mr(){if(process.platform!=="darwin")return;let $=yr.userInfo().username,Z=[hr,xr].flatMap((J)=>[SU.join("/Library/Managed Preferences",$,`${J}.plist`),SU.join("/Library/Managed Preferences",`${J}.plist`)]);for(let J of Z){if(!await o0.exists(J))continue;Jw.info("reading macOS managed preferences",{path:J});let Y=await f1.run(["plutil","-convert","json","-o","-",J],{nothrow:!0});if(Y.code!==0){Jw.warn("failed to convert managed preferences plist",{path:J});continue}return{source:`mobileconfig:${J}`,text:Qw(Y.stdout.toString())}}return}var SZ=E0.create({service:"config"}),Gw=["node_modules","package.json","package-lock.json","bun.lock",".gitignore","/plans/"],dr=T.fn("Config.ensureGitignore")(function*($){let Z=yield*D$.Service,J=fZ.join($,".gitignore");if(!(yield*Z.existsSafe(J))){yield*Z.writeFileString(J,Gw.join(`
488
+ `);return $.replace(J,()=>Q)}async function EU($){let Z=await o0.readText($);try{return CU.default(Z,{})}catch(J){let Y=rD(Z);if(Y===Z)throw new eY({path:$,message:`${$}: Failed to parse YAML frontmatter: ${J instanceof Error?J.message:String(J)}`},{cause:J});try{return CU.default(Y,{})}catch(X){throw new eY({path:$,message:`${$}: Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`},{cause:X})}}}var eY=j1.create("ConfigFrontmatterError",D.object({path:D.string(),message:D.string()}));var wr=E0.create({service:"config"});function $X($,Z,J,Y){let X=$.safeParse(Z);if(X.success)return X.data;if(Y?.ignoreInvalid)return;throw new aD({path:J,issues:X.error.issues},{cause:X.error})}async function ZX($){for(let Z of await $4.scan($.glob,{cwd:$.dir,absolute:!0,dot:!0,symlink:!0})){let J=await EU(Z).catch(async(Q)=>{let G=eY.isInstance(Q)?Q.data.message:`Failed to parse ${$.entity} ${Z}`,{Session:W}=await import("./chunk-dwhjgd8j.js");l1.publish(W.Event.Error,{error:new j1.Unknown({message:G}).toObject()}),wr.error(`failed to load ${$.entity}`,{[$.entity]:Z,err:Q});return});if(!J)continue;let X={name:EN(Z,$.namePatterns),...J.data,[$.contentKey]:J.content.trim()};$.store(X,Z)}}var T8=O.String.annotate({[F$]:P.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"})}).pipe(u0(($)=>({zod:w0($)})));var _Z={};F1(_Z,{Rule:()=>R8,Object:()=>eD,Info:()=>Ir,ConfigPermission:()=>_Z,Action:()=>p6});var p6=O.Literals(["ask","allow","deny"]).annotate({identifier:"PermissionActionConfig"}).pipe(u0(($)=>({zod:w0($)}))),eD=O.Record(O.String,p6).annotate({identifier:"PermissionObjectConfig"}).pipe(u0(($)=>({zod:w0($)}))),R8=O.Union([p6,eD]).annotate({identifier:"PermissionRuleConfig"}).pipe(u0(($)=>({zod:w0($)}))),Lr=($)=>{if(typeof $==="object"&&$!==null&&!Array.isArray($))return{__originalKeys:globalThis.Object.keys($),...$};return $},Tr=O.StructWithRest(O.Struct({__originalKeys:O.optional(O.mutable(O.Array(O.String))),read:O.optional(R8),edit:O.optional(R8),glob:O.optional(R8),grep:O.optional(R8),list:O.optional(R8),bash:O.optional(R8),task:O.optional(R8),actor:O.optional(R8),external_directory:O.optional(R8),question:O.optional(p6),webfetch:O.optional(p6),websearch:O.optional(p6),codesearch:O.optional(p6),lsp:O.optional(R8),doom_loop:O.optional(p6),skill:O.optional(R8)}),[O.Record(O.String,R8)]),Rr=O.Union([Tr,p6]).annotate({[tD]:Lr}),Pr=($)=>{if(typeof $==="string")return{"*":$};let Z=$,{__originalKeys:J,...Y}=Z;if(!J)return Y;let X={};for(let Q of J)if(Q in Y)X[Q]=Y[Q];return X},Ir=w0(Rr).transform(Pr).meta({ref:"PermissionConfig"});var $w=O.Number.check(O.isInt()).check(O.isGreaterThan(0)),Cr=O.Union([O.String.check(O.isPattern(/^#[0-9a-fA-F]{6}$/)),O.Literals(["primary","secondary","accent","success","warning","error","info"])]),Er=O.Any.annotate({[F$]:_Z.Info}),br=O.StructWithRest(O.Struct({model:O.optional(T8).annotate({description:"Model for this agent: a literal provider/model (e.g. anthropic/claude-opus-4-8) or a tier/group name (e.g. fast/economical/default/power). Names without a '/' are resolved as model groups, provider-aware, at spawn time."}),variant:O.optional(O.String).annotate({description:"Default model variant for this agent (applies only when using the agent's configured model)."}),temperature:O.optional(O.Number),top_p:O.optional(O.Number),prompt:O.optional(O.String),tools:O.optional(O.Record(O.String,O.Boolean)).annotate({description:"@deprecated Use 'permission' field instead"}),disable:O.optional(O.Boolean),description:O.optional(O.String).annotate({description:"Description of when to use the agent"}),mode:O.optional(O.Literals(["subagent","primary","all"])),hidden:O.optional(O.Boolean).annotate({description:"Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"}),options:O.optional(O.Record(O.String,O.Any)),color:O.optional(Cr).annotate({description:"Hex color code (e.g., #FF5733) or theme color (e.g., primary)"}),steps:O.optional($w).annotate({description:"Maximum number of agentic iterations before forcing text-only response"}),tool_allowlist:O.optional(O.Array(O.String)).annotate({description:"Optional list of tool IDs allowed for this agent. When set, only these tools are available."}),maxSteps:O.optional($w).annotate({description:"@deprecated Use 'steps' field instead."}),permission:O.optional(Er)}),[O.Record(O.String,O.Any)]),_r=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools","tool_allowlist"]),Sr=($)=>{let Z={...$.options};for(let[Y,X]of Object.entries($))if(!_r.has(Y))Z[Y]=X;let J={};for(let[Y,X]of Object.entries($.tools??{})){let Q=X?"allow":"deny";if(Y==="write"||Y==="edit"||Y==="patch"||Y==="multiedit"){J.edit=Q;continue}if(Y==="task"){J.actor=Q;continue}J[Y]=Q}return globalThis.Object.assign(J,$.permission),{...$,options:Z,permission:J,steps:$.steps??$.maxSteps}},_U=w0(br).transform(Sr).meta({ref:"AgentConfig"});async function fr($){let Z={};return await ZX({dir:$,glob:"{agent,agents}/**/*.md",entity:"agent",namePatterns:["/.qitqode/agent/","/.qitqode/agents/","/agent/","/agents/"],contentKey:"prompt",store:(J,Y)=>{Z[J.name]=$X(_U,J,Y)}}),Z}async function kr($){let Z={};return await ZX({dir:$,glob:"{mode,modes}/*.md",entity:"mode",namePatterns:[],contentKey:"prompt",store:(J,Y)=>{let X=$X(_U,J,Y,{ignoreInvalid:!0});if(X)Z[J.name]={...X,mode:"primary"}}}),Z}var i6={};F1(i6,{load:()=>vr,Info:()=>Zw,ConfigCommand:()=>i6});var Zw=O.Struct({template:O.String,description:O.optional(O.String),agent:O.optional(O.String),model:O.optional(T8),subtask:O.optional(O.Boolean)}).pipe(u0(($)=>({zod:w0($)})));async function vr($){let Z={};return await ZX({dir:$,glob:"{command,commands}/**/*.md",entity:"command",namePatterns:["/.qitqode/command/","/.qitqode/commands/","/.claude/command/","/.claude/commands/","/command/","/commands/"],contentKey:"template",store:(J,Y)=>{Z[J.name]=$X(Zw.zod,J,Y)}}),Z}var R5={};F1(R5,{readManagedPreferences:()=>mr,parseManagedPlist:()=>Qw,managedConfigDirs:()=>Xw,managedConfigDir:()=>ur,ConfigManaged:()=>R5});import yr from"os";import SU from"path";var Jw=E0.create({service:"config"}),xr="ai.qitqode.managed",hr="ai.opencode.managed",gr=new Set(["PayloadDisplayName","PayloadIdentifier","PayloadType","PayloadUUID","PayloadVersion","_manualProfile"]);function Yw($="qitqode"){switch(process.platform){case"darwin":return`/Library/Application Support/${$}`;case"win32":return SU.join(process.env.ProgramData||"C:\\ProgramData",$);default:return`/etc/${$}`}}function ur(){return Xw().at(-1)}function Xw(){let $=process.env.QITQODE_TEST_MANAGED_CONFIG_DIR;if($)return[$];return[Yw("opencode"),Yw()]}function Qw($){let Z=JSON.parse($);for(let J of Object.keys(Z))if(gr.has(J))delete Z[J];return JSON.stringify(Z)}async function mr(){if(process.platform!=="darwin")return;let $=yr.userInfo().username,Z=[hr,xr].flatMap((J)=>[SU.join("/Library/Managed Preferences",$,`${J}.plist`),SU.join("/Library/Managed Preferences",`${J}.plist`)]);for(let J of Z){if(!await o0.exists(J))continue;Jw.info("reading macOS managed preferences",{path:J});let Y=await f1.run(["plutil","-convert","json","-o","-",J],{nothrow:!0});if(Y.code!==0){Jw.warn("failed to convert managed preferences plist",{path:J});continue}return{source:`mobileconfig:${J}`,text:Qw(Y.stdout.toString())}}return}var SZ=E0.create({service:"config"}),Gw=["node_modules","package.json","package-lock.json","bun.lock",".gitignore","/plans/"],dr=T.fn("Config.ensureGitignore")(function*($){let Z=yield*D$.Service,J=fZ.join($,".gitignore");if(!(yield*Z.existsSafe(J))){yield*Z.writeFileString(J,Gw.join(`
489
489
  `)+`
490
490
  `).pipe(T.catchIf((V)=>V.reason?._tag==="PermissionDenied",()=>T.void));return}let X=yield*Z.readFileString(J),Q=new Set(X.split(`
491
491
  `).map((V)=>V.trim())),G=Gw.filter((V)=>!Q.has(V));if(G.length===0)return;let W=!X.endsWith(`
@@ -522,7 +522,7 @@ ${Y.map(Lw).join(`
522
522
  `)+`
523
523
  `))}),m=yield*Z.spawn(c),[a,e]=yield*T.all([I$.mkUint8Array(m.stdout),I$.mkString(I$.decodeText(m.stderr))],{concurrency:2});if((yield*m.exitCode)!==0){J$.info("git cat-file --batch failed during snapshot diff, falling back to per-file git show",{stderr:e,refs:h.length});return}let A0=(K0,z0)=>{J$.info(K0,{...z0,refs:h.length});return},P0=new Map,s0=new TextDecoder,o=0;for(let K0 of h){let z0=o;while(z0<a.length&&a[z0]!==10)z0+=1;if(z0>=a.length)return A0("git cat-file --batch returned a truncated header during snapshot diff, falling back to per-file git show");let j0=s0.decode(a.slice(o,z0));o=z0+1;let Q1=P0.get(K0.file)??{before:"",after:""};if(j0.endsWith(" missing")){P0.set(K0.file,Q1);continue}let _0=j0.match(/^[0-9a-f]+ blob (\d+)$/);if(!_0)return A0("git cat-file --batch returned an unexpected header during snapshot diff, falling back to per-file git show",{head:j0});let e0=Number(_0[1]);if(!Number.isInteger(e0)||e0<0||o+e0>=a.length||a[o+e0]!==10)return A0("git cat-file --batch returned truncated content during snapshot diff, falling back to per-file git show",{head:j0});let S0=s0.decode(a.slice(o,o+e0));if(K0.side==="before")Q1.before=S0;if(K0.side==="after")Q1.after=S0;P0.set(K0.file,Q1),o+=e0+1}if(o!==a.length)return A0("git cat-file --batch returned trailing data during snapshot diff, falling back to per-file git show");return P0},T.scoped,T.catch(()=>T.succeed(void 0))),t=[],r=new Map,G0=yield*H([..._5,...K(["diff","--no-ext-diff","--name-status","--no-renames",k,g,"--","."])],{cwd:W.directory});for(let v of G0.text.trim().split(`
524
524
  `)){if(!v)continue;let[h,c]=v.split("\t");if(!h||!c)continue;r.set(c,h.startsWith("A")?"added":h.startsWith("D")?"deleted":"modified")}let h0=(yield*H([..._5,...K(["diff","--no-ext-diff","--no-renames","--numstat",k,g,"--","."])],{cwd:W.directory})).text.trim().split(`
525
- `).filter(Boolean).flatMap((v)=>{let[h,c,m]=v.split("\t");if(!m)return[];let a=h==="-"&&c==="-",e=a?0:parseInt(h),H0=a?0:parseInt(c);return[{file:m,status:r.get(m)??"modified",binary:a,additions:Number.isFinite(e)?e:0,deletions:Number.isFinite(H0)?H0:0}]}),u=yield*B(h0.map((v)=>v.file));if(u.size>0){let v=h0.filter((h)=>!u.has(h.file));h0.length=0,h0.push(...v)}let l=100,$0=(v,h,c)=>VJ(QX(v,v,h,c,"","",{context:Number.MAX_SAFE_INTEGER}));for(let v=0;v<h0.length;v+=l){let h=h0.slice(v,v+l),c=yield*p(h);for(let m of h){let a=c?.get(m.file)??{before:"",after:""},[e,H0]=m.binary?["",""]:c?[a.before,a.after]:yield*d(m);t.push({file:m.file,patch:m.binary?"":$0(m.file,e,H0),additions:m.additions,deletions:m.deletions,status:m.status})}}return t}))});return yield*vw(w(),(k)=>{return J$.error("cleanup loop failed",{cause:xw.pretty(k)}),T.void}),{cleanup:w,track:I,patch:_,restore:E,revert:f,diff:b,diffFull:y}}));return K4.of({init:T.fn("Snapshot.init")(function*(){yield*B0.get(Q)}),cleanup:T.fn("Snapshot.cleanup")(function*(){return yield*B0.useEffect(Q,(G)=>G.cleanup())}),track:T.fn("Snapshot.track")(function*(){return yield*B0.useEffect(Q,(G)=>G.track())}),patch:T.fn("Snapshot.patch")(function*(G){return yield*B0.useEffect(Q,(W)=>W.patch(G))}),restore:T.fn("Snapshot.restore")(function*(G){return yield*B0.useEffect(Q,(W)=>W.restore(G))}),revert:T.fn("Snapshot.revert")(function*(G){return yield*B0.useEffect(Q,(W)=>W.revert(G))}),diff:T.fn("Snapshot.diff")(function*(G){return yield*B0.useEffect(Q,(W)=>W.diff(G))}),diffFull:T.fn("Snapshot.diffFull")(function*(G,W){return yield*B0.useEffect(Q,(K)=>K.diffFull(G,W))})})})),Ma=mw.pipe(T0.provide(gw),T0.provide(D$.defaultLayer),T0.provide(X8.defaultLayer));var Da=O.String.pipe(O.brand("ProviderID")),X1=Da.pipe(u0(($)=>({zod:P.string().pipe(P.custom()),opencode:$.make("opencode"),anthropic:$.make("anthropic"),openai:$.make("openai"),google:$.make("google"),googleVertex:$.make("google-vertex"),githubCopilot:$.make("github-copilot"),amazonBedrock:$.make("amazon-bedrock"),azure:$.make("azure"),openrouter:$.make("openrouter"),mistral:$.make("mistral"),gitlab:$.make("gitlab")}))),wa=O.String.pipe(O.brand("ModelID")),s1=wa.pipe(u0(($)=>({zod:P.string().pipe(P.custom())})));var lw=P.object({errorID:P.string(),errorName:P.string(),logFile:P.string()}).meta({ref:"ErrorDiagnostic"}),U4=j1.create("MessageOutputLengthError",P.object({})),f5=j1.create("MessageAbortedError",P.object({message:P.string()})),dw=j1.create("StructuredOutputError",P.object({message:P.string(),retries:P.number()})),H4=j1.create("ProviderAuthError",P.object({providerID:P.string(),message:P.string()})),L6=j1.create("APIError",P.object({message:P.string(),statusCode:P.number().optional(),isRetryable:P.boolean(),category:P.string().optional(),upstreamCode:P.string().optional(),requestId:P.string().optional(),outputBudgetRecoveryAvailable:P.boolean().optional(),outputBudgetRecoveryTokens:P.number().int().positive().optional(),diagnostic:lw.optional(),responseHeaders:P.record(P.string(),P.string()).optional(),responseBody:P.string().optional(),metadata:P.record(P.string(),P.string()).optional()})),GX=j1.create("ContextOverflowError",P.object({message:P.string(),responseBody:P.string().optional()})),pw=j1.create("InvalidOutputError",P.object({message:P.string()})),cw=j1.create("ContentFilterError",P.object({message:P.string()})),iw=j1.create("ModelError",P.object({message:P.string()})),nw=P.object({type:P.literal("text")}).meta({ref:"OutputFormatText"}),ow=P.object({type:P.literal("json_schema"),schema:P.record(P.string(),P.any()).meta({ref:"JSONSchema"}),retryCount:P.number().int().min(0).default(2)}).meta({ref:"OutputFormatJsonSchema"}),sw=P.discriminatedUnion("type",[nw,ow]).meta({ref:"OutputFormat"}),P8=P.object({id:MZ.zod,sessionID:r0.zod,messageID:i1.zod}),rw=P8.extend({type:P.literal("snapshot"),snapshot:P.string()}).meta({ref:"SnapshotPart"}),aw=P8.extend({type:P.literal("patch"),hash:P.string(),files:P.string().array()}).meta({ref:"PatchPart"}),tw=P8.extend({type:P.literal("text"),text:P.string(),synthetic:P.boolean().optional(),ignored:P.boolean().optional(),time:P.object({start:P.number(),end:P.number().optional()}).optional(),metadata:P.record(P.string(),P.any()).optional()}).meta({ref:"TextPart"}),ew=P8.extend({type:P.literal("reasoning"),text:P.string(),metadata:P.record(P.string(),P.any()).optional(),time:P.object({start:P.number(),end:P.number().optional()})}).meta({ref:"ReasoningPart"}),gU=P.object({text:P.object({value:P.string(),start:P.number().int(),end:P.number().int()}).meta({ref:"FilePartSourceText"})}),$L=gU.extend({type:P.literal("file"),path:P.string()}).meta({ref:"FileSource"}),ZL=gU.extend({type:P.literal("symbol"),path:P.string(),range:X4.Range,name:P.string(),kind:P.number().int()}).meta({ref:"SymbolSource"}),JL=gU.extend({type:P.literal("resource"),clientName:P.string(),uri:P.string()}).meta({ref:"ResourceSource"}),YL=P.discriminatedUnion("type",[$L,ZL,JL]).meta({ref:"FilePartSource"}),uU=P8.extend({type:P.literal("file"),mime:P.string(),filename:P.string().optional(),url:P.string(),source:YL.optional()}).meta({ref:"FilePart"}),XL=P8.extend({type:P.literal("agent"),name:P.string(),source:P.object({value:P.string(),start:P.number().int(),end:P.number().int()}).optional()}).meta({ref:"AgentPart"}),QL=P8.extend({type:P.literal("checkpoint"),checkpointDir:P.string(),checkpointNumber:P.number(),coveredUpTo:i1.zod}).meta({ref:"CheckpointPart"}),GL=P8.extend({type:P.literal("subtask"),prompt:P.string(),description:P.string(),agent:P.string(),model:P.object({providerID:X1.zod,modelID:s1.zod}).optional(),command:P.string().optional()}).meta({ref:"SubtaskPart"}),WL=P8.extend({type:P.literal("compaction"),auto:P.boolean(),overflow:P.boolean().optional(),tail_start_id:i1.zod.optional()}).meta({ref:"CompactionPart"}),KL=P8.extend({type:P.literal("retry"),attempt:P.number(),error:L6.Schema,time:P.object({created:P.number()})}).meta({ref:"RetryPart"}),VL=P8.extend({type:P.literal("step-start"),snapshot:P.string().optional()}).meta({ref:"StepStartPart"}),UL=P.object({total:P.number().optional(),input:P.number(),output:P.number(),reasoning:P.number(),cache:P.object({read:P.number(),write:P.number()})}),HL=P8.extend({type:P.literal("step-finish"),reason:P.string(),snapshot:P.string().optional(),cost:P.number(),costCredits:P.number().optional(),tokens:UL,contextWindow:P.number().optional()}).meta({ref:"StepFinishPart"}),BL=P.object({status:P.literal("pending"),input:P.record(P.string(),P.any()),raw:P.string()}).meta({ref:"ToolStatePending"}),zL=P.object({status:P.literal("running"),input:P.record(P.string(),P.any()),title:P.string().optional(),metadata:P.record(P.string(),P.any()).optional(),time:P.object({start:P.number()})}).meta({ref:"ToolStateRunning"}),FL=P.object({status:P.literal("completed"),input:P.record(P.string(),P.any()),output:P.string(),title:P.string(),metadata:P.record(P.string(),P.any()),time:P.object({start:P.number(),end:P.number(),compacted:P.number().optional()}),attachments:uU.array().optional()}).meta({ref:"ToolStateCompleted"}),AL=P.object({status:P.literal("error"),input:P.record(P.string(),P.any()),error:P.string(),metadata:P.record(P.string(),P.any()).optional(),time:P.object({start:P.number(),end:P.number()})}).meta({ref:"ToolStateError"}),OL=P.discriminatedUnion("status",[BL,zL,FL,AL]).meta({ref:"ToolState"}),qL=P8.extend({type:P.literal("tool"),callID:P.string(),tool:P.string(),state:OL,metadata:P.record(P.string(),P.any()).optional()}).meta({ref:"ToolPart"}),jL=P.object({id:i1.zod,sessionID:r0.zod,agentID:P.string().optional()}),NL=P.object({hookPhase:P.enum(["pre","post"]),hookIteration:P.number().int().nonnegative(),pluginNames:P.array(P.string()),hookIDs:P.array(P.string())}).meta({ref:"Provenance"}),ML=jL.extend({role:P.literal("user"),time:P.object({created:P.number()}),format:sw.optional(),summary:P.object({title:P.string().optional(),body:P.string().optional(),diffs:vZ.FileDiff.array()}).optional(),agent:P.string(),model:P.object({providerID:X1.zod,modelID:s1.zod,variant:P.string().optional()}),system:P.string().optional(),tools:P.record(P.string(),P.boolean()).optional(),provenance:NL.optional(),outputBudgetRecoveryTokens:P.number().int().positive().optional()}).meta({ref:"UserMessage"}),mU=P.discriminatedUnion("type",[tw,GL,ew,uU,qL,VL,HL,rw,aw,XL,KL,QL,WL]).meta({ref:"Part"}),DL=jL.extend({role:P.literal("assistant"),time:P.object({created:P.number(),completed:P.number().optional()}),error:P.discriminatedUnion("name",[H4.Schema,j1.Unknown.Schema,U4.Schema,f5.Schema,dw.Schema,GX.Schema,pw.Schema,cw.Schema,iw.Schema,L6.Schema]).optional(),parentID:i1.zod,modelID:s1.zod,providerID:X1.zod,mode:P.string(),agent:P.string(),path:P.object({cwd:P.string(),root:P.string()}),summary:P.boolean().optional(),cost:P.number(),costCredits:P.number().optional(),tokens:UL,contextWindow:P.number().optional(),structured:P.any().optional(),variant:P.string().optional(),finish:P.string().optional()}).meta({ref:"AssistantMessage"}),lU=P.discriminatedUnion("role",[ML,DL]).meta({ref:"Message"}),La={Updated:X$.define({type:"message.updated",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:lU})}),Removed:X$.define({type:"message.removed",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,messageID:i1.zod})}),PartUpdated:X$.define({type:"message.part.updated",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,part:mU,time:P.number()})}),PartDelta:L1.define("message.part.delta",P.object({sessionID:r0.zod,messageID:i1.zod,partID:MZ.zod,field:P.string(),delta:P.string()})),PartRemoved:X$.define({type:"message.part.removed",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,messageID:i1.zod,partID:MZ.zod})})},Ta=P.object({info:lU,parts:P.array(mU)});var Ra=P.object({id:i1.zod,time:P.number()}),dU={encode($){return Buffer.from(JSON.stringify($)).toString("base64url")},decode($){return Ra.parse(JSON.parse(Buffer.from($,"base64url").toString("utf8")))}},LL=($)=>({...$.data,id:$.id,sessionID:$.session_id,agentID:$.agent_id}),TL=($)=>({...$.data,id:$.id,sessionID:$.session_id,messageID:$.message_id}),Pa=($)=>wL(WX(w$.time_created,$.time),O$(m0(w$.time_created,$.time),WX(w$.id,$.id)));function Ia($){let Z=$.map((Y)=>Y.id),J=new Map;if(Z.length>0){let Y=W1.use((X)=>X.select().from(I8).where(k5(I8.message_id,Z)).orderBy(I8.message_id,I8.id).all());for(let X of Y){let Q=TL(X),G=J.get(X.message_id);if(G)G.push(Q);else J.set(X.message_id,[Q])}}return $.map((Y)=>({info:LL(Y),parts:J.get(Y.id)??[]}))}function RL($){let Z=$.before?dU.decode($.before):void 0,J=$.agentID==="*"?void 0:m0(w$.agent_id,$.agentID??"main"),Y=O$(m0(w$.session_id,$.sessionID),...Z?[Pa(Z)]:[],...J?[J]:[]),X=W1.use((V)=>V.select().from(w$).where(Y).orderBy(o6(w$.time_created),o6(w$.id)).limit($.limit+1).all());if(X.length===0){if(!W1.use((U)=>U.select({id:I1.id}).from(I1).where(m0(I1.id,$.sessionID)).get()))throw new KX({message:`Session not found: ${$.sessionID}`});return{items:[],more:!1}}let Q=X.length>$.limit,G=Q?X.slice(0,$.limit):X,W=Ia(G);W.reverse();let K=G.at(-1);return{items:W,more:Q,cursor:Q&&K?dU.encode({id:K.id,time:K.time_created}):void 0}}function*pU($,Z){let Y;while(!0){let X=RL({sessionID:$,limit:50,before:Y,agentID:Z?.agentID});if(X.items.length===0)break;for(let Q=X.items.length-1;Q>=0;Q--)yield X.items[Q];if(!X.more||!X.cursor)break;Y=X.cursor}}function PL($){return W1.use((J)=>J.select().from(I8).where(m0(I8.message_id,$)).orderBy(I8.id).all()).map(TL)}function Ca($){let Z=W1.use((J)=>J.select().from(w$).where(O$(m0(w$.id,$.messageID),m0(w$.session_id,$.sessionID))).get());if(!Z)throw new KX({message:`Message not found: ${$.messageID}`});return{info:LL(Z),parts:PL($.messageID)}}function cU($){let Z=[];for(let J of $)if(Z.push(J),J.info.role==="user"&&J.parts.some((Y)=>Y.type==="checkpoint"||Y.type==="compaction"))break;return Z.reverse(),Z}var Ea=T.fnUntraced(function*($,Z){let J=cU(pU($,{agentID:Z?.agentID}));if(!Z?.contextFrom)return J;let Y=pU(Z.contextFrom,{agentID:"main"}),X=cU(Y);if(Z.contextWatermark){let Q=X.findIndex((G)=>G.info.id===Z.contextWatermark);if(Q>=0)return[...X.slice(0,Q+1),...J]}return[...X,...J]});var lT=m6(yL(),1),zJ=m6(yL(),1);var ba=Object.defineProperty,_a=($,Z)=>{for(var J in Z)ba($,J,{get:Z[J],enumerable:!0})},iL="AI_InvalidArgumentError",nL=`vercel.ai.error.${iL}`,Sa=Symbol.for(nL),oL,r1=class extends p0{constructor({parameter:$,value:Z,message:J}){super({name:iL,message:`Invalid argument for parameter ${$}: ${J}`});this[oL]=!0,this.parameter=$,this.value=Z}static isInstance($){return p0.hasMarker($,nL)}};oL=Sa;var fa="AI_InvalidStreamPartError",ka=`vercel.ai.error.${fa}`,va=Symbol.for(ka),ya;ya=va;var sL="AI_InvalidToolApprovalError",rL=`vercel.ai.error.${sL}`,xa=Symbol.for(rL),aL,ha=class extends p0{constructor({approvalId:$}){super({name:sL,message:`Tool approval response references unknown approvalId: "${$}". No matching tool-approval-request found in message history.`});this[aL]=!0,this.approvalId=$}static isInstance($){return p0.hasMarker($,rL)}};aL=xa;var tL="AI_InvalidToolInputError",eL=`vercel.ai.error.${tL}`,ga=Symbol.for(eL),$T,GH=class extends p0{constructor({toolInput:$,toolName:Z,cause:J,message:Y=`Invalid input for tool ${Z}: ${r6(J)}`}){super({name:tL,message:Y,cause:J});this[$T]=!0,this.toolInput=$,this.toolName=Z}static isInstance($){return p0.hasMarker($,eL)}};$T=ga;var ZT="AI_ToolCallNotFoundForApprovalError",JT=`vercel.ai.error.${ZT}`,ua=Symbol.for(JT),YT,XT=class extends p0{constructor({toolCallId:$,approvalId:Z}){super({name:ZT,message:`Tool call "${$}" not found for approval request "${Z}".`});this[YT]=!0,this.toolCallId=$,this.approvalId=Z}static isInstance($){return p0.hasMarker($,JT)}};YT=ua;var QT="AI_MissingToolResultsError",GT=`vercel.ai.error.${QT}`,ma=Symbol.for(GT),WT,IL=class extends p0{constructor({toolCallIds:$}){super({name:QT,message:`Tool result${$.length>1?"s are":" is"} missing for tool call${$.length>1?"s":""} ${$.join(", ")}.`});this[WT]=!0,this.toolCallIds=$}static isInstance($){return p0.hasMarker($,GT)}};WT=ma;var la="AI_NoImageGeneratedError",da=`vercel.ai.error.${la}`,pa=Symbol.for(da),ca;ca=pa;var KT="AI_NoObjectGeneratedError",VT=`vercel.ai.error.${KT}`,ia=Symbol.for(VT),UT,E8=class extends p0{constructor({message:$="No object generated.",cause:Z,text:J,response:Y,usage:X,finishReason:Q}){super({name:KT,message:$,cause:Z});this[UT]=!0,this.text=J,this.response=Y,this.usage=X,this.finishReason=Q}static isInstance($){return p0.hasMarker($,VT)}};UT=ia;var HT="AI_NoOutputGeneratedError",BT=`vercel.ai.error.${HT}`,na=Symbol.for(BT),zT,oa=class extends p0{constructor({message:$="No output generated.",cause:Z}={}){super({name:HT,message:$,cause:Z});this[zT]=!0}static isInstance($){return p0.hasMarker($,BT)}};zT=na;var sa="AI_NoSpeechGeneratedError",ra=`vercel.ai.error.${sa}`,aa=Symbol.for(ra),ta;ta=aa;var ea="AI_NoTranscriptGeneratedError",$t=`vercel.ai.error.${ea}`,Zt=Symbol.for($t),Jt;Jt=Zt;var Yt="AI_NoVideoGeneratedError",Xt=`vercel.ai.error.${Yt}`,Qt=Symbol.for(Xt),Gt;Gt=Qt;var FT="AI_NoSuchToolError",AT=`vercel.ai.error.${FT}`,Wt=Symbol.for(AT),OT,tU=class extends p0{constructor({toolName:$,availableTools:Z=void 0,message:J=`Model tried to call unavailable tool '${$}'. ${Z===void 0?"No tools are available.":`Available tools: ${Z.join(", ")}.`}`}){super({name:FT,message:J});this[OT]=!0,this.toolName=$,this.availableTools=Z}static isInstance($){return p0.hasMarker($,AT)}};OT=Wt;var qT="AI_ToolCallRepairError",jT=`vercel.ai.error.${qT}`,Kt=Symbol.for(jT),NT,Vt=class extends p0{constructor({cause:$,originalError:Z,message:J=`Error repairing tool call: ${r6($)}`}){super({name:qT,message:J,cause:$});this[NT]=!0,this.originalError=Z}static isInstance($){return p0.hasMarker($,jT)}};NT=Kt;var Ut=class extends p0{constructor($){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${$.version} for provider "${$.provider}" and model "${$.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=$.version,this.provider=$.provider,this.modelId=$.modelId}},MT="AI_UIMessageStreamError",DT=`vercel.ai.error.${MT}`,Ht=Symbol.for(DT),wT,UJ=class extends p0{constructor({chunkType:$,chunkId:Z,message:J}){super({name:MT,message:J});this[wT]=!0,this.chunkType=$,this.chunkId=Z}static isInstance($){return p0.hasMarker($,DT)}};wT=Ht;var Bt="AI_InvalidDataContentError",zt=`vercel.ai.error.${Bt}`,Ft=Symbol.for(zt),At;At=Ft;var LT="AI_InvalidMessageRoleError",TT=`vercel.ai.error.${LT}`,Ot=Symbol.for(TT),RT,qt=class extends p0{constructor({role:$,message:Z=`Invalid message role: '${$}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:LT,message:Z});this[RT]=!0,this.role=$}static isInstance($){return p0.hasMarker($,TT)}};RT=Ot;var PT="AI_MessageConversionError",IT=`vercel.ai.error.${PT}`,jt=Symbol.for(IT),CT,Nt=class extends p0{constructor({originalMessage:$,message:Z}){super({name:PT,message:Z});this[CT]=!0,this.originalMessage=$}static isInstance($){return p0.hasMarker($,IT)}};CT=jt;var ET="AI_RetryError",bT=`vercel.ai.error.${ET}`,Mt=Symbol.for(bT),_T,O4=class extends p0{constructor({message:$,reason:Z,errors:J}){super({name:ET,message:$});this[_T]=!0,this.reason=Z,this.errors=J,this.lastError=J[J.length-1]}static isInstance($){return p0.hasMarker($,bT)}};_T=Mt;function y5($){return $===void 0?[]:Array.isArray($)?$:[$]}async function v5($){for(let Z of y5($.callbacks)){if(Z==null)continue;try{await Z($.event)}catch(J){}}}function Dt({warning:$,provider:Z,model:J}){let Y=`AI SDK Warning (${Z} / ${J}):`;switch($.type){case"unsupported":{let X=`${Y} The feature "${$.feature}" is not supported.`;if($.details)X+=` ${$.details}`;return X}case"compatibility":{let X=`${Y} The feature "${$.feature}" is used in a compatibility mode.`;if($.details)X+=` ${$.details}`;return X}case"other":return`${Y} ${$.message}`;default:return`${Y} ${JSON.stringify($,null,2)}`}}var wt="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",CL=!1,D4=($)=>{if($.warnings.length===0)return;let Z=globalThis.AI_SDK_LOG_WARNINGS;if(Z===!1)return;if(typeof Z==="function"){Z($);return}if(!CL)CL=!0,console.info(wt);for(let J of $.warnings)console.warn(Dt({warning:J,provider:$.provider,model:$.model}))};function Lt({provider:$,modelId:Z}){D4({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:$,model:Z})}function Tt($){if($.specificationVersion==="v3")return $;return Lt({provider:$.provider,modelId:$.modelId}),new Proxy($,{get(Z,J){switch(J){case"specificationVersion":return"v3";case"doGenerate":return async(...Y)=>{let X=await Z.doGenerate(...Y);return{...X,finishReason:ST(X.finishReason),usage:fT(X.usage)}};case"doStream":return async(...Y)=>{let X=await Z.doStream(...Y);return{...X,stream:Rt(X.stream)}};default:return Z[J]}}})}function Rt($){return $.pipeThrough(new TransformStream({transform(Z,J){switch(Z.type){case"finish":J.enqueue({...Z,finishReason:ST(Z.finishReason),usage:fT(Z.usage)});break;default:J.enqueue(Z);break}}}))}function ST($){return{unified:$==="unknown"?"other":$,raw:void 0}}function fT($){return{inputTokens:{total:$.inputTokens,noCache:void 0,cacheRead:$.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:$.outputTokens,text:void 0,reasoning:$.reasoningTokens}}}function w4($){if(typeof $!=="string"){if($.specificationVersion!=="v3"&&$.specificationVersion!=="v2"){let Z=$;throw new Ut({version:Z.specificationVersion,provider:Z.provider,modelId:Z.modelId})}return Tt($)}return Pt().languageModel($)}function Pt(){var $;return($=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?$:cL}function kT($){if($==null)return;if(typeof $==="number")return $;return $.totalMs}function It($){if($==null||typeof $==="number")return;return $.stepMs}function Ct($){if($==null||typeof $==="number")return;return $.chunkMs}var Et=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var bt=($)=>{let Z=typeof $==="string"?FJ($):$,J=(Z[6]&127)<<21|(Z[7]&127)<<14|(Z[8]&127)<<7|Z[9]&127;return Z.slice(J+10)};function _t($){return typeof $==="string"&&$.startsWith("SUQz")||typeof $!=="string"&&$.length>10&&$[0]===73&&$[1]===68&&$[2]===51?bt($):$}function St({data:$,signatures:Z}){let J=_t($),Y=typeof J==="string"?FJ(J.substring(0,Math.min(J.length,24))):J;for(let X of Z)if(Y.length>=X.bytesPrefix.length&&X.bytesPrefix.every((Q,G)=>Q===null||Y[G]===Q))return X.mediaType;return}var vT="6.0.168",yT=async({url:$,maxBytes:Z,abortSignal:J})=>{var Y;let X=$.toString();aU(X);try{let Q=await fetch(X,{headers:OX({},`ai-sdk/${vT}`,uL()),signal:J});if(Q.redirected)aU(Q.url);if(!Q.ok)throw new z4({url:X,statusCode:Q.status,statusText:Q.statusText});return{data:await gL({response:Q,url:X,maxBytes:Z!=null?Z:hL}),mediaType:(Y=Q.headers.get("content-type"))!=null?Y:void 0}}catch(Q){if(z4.isInstance(Q))throw Q;throw new z4({url:X,cause:Q})}},ft=($=yT)=>(Z)=>Promise.all(Z.map(async(J)=>J.isUrlSupportedByModel?null:$(J)));function kt($){try{let[Z,J]=$.split(",");return{mediaType:Z.split(";")[0].split(":")[1],base64Content:J}}catch(Z){return{mediaType:void 0,base64Content:void 0}}}var xT=D.union([D.string(),D.instanceof(Uint8Array),D.instanceof(ArrayBuffer),D.custom(($)=>{var Z,J;return(J=(Z=globalThis.Buffer)==null?void 0:Z.isBuffer($))!=null?J:!1},{message:"Must be a Buffer"})]);function hT($){if($ instanceof Uint8Array)return{data:$,mediaType:void 0};if($ instanceof ArrayBuffer)return{data:new Uint8Array($),mediaType:void 0};if(typeof $==="string")try{$=new URL($)}catch(Z){}if($ instanceof URL&&$.protocol==="data:"){let{mediaType:Z,base64Content:J}=kt($.toString());if(Z==null||J==null)throw new p0({name:"InvalidDataContentError",message:`Invalid data URL format in content ${$.toString()}`});return{data:J,mediaType:Z}}return{data:$,mediaType:void 0}}function vt($){if(typeof $==="string")return $;if($ instanceof ArrayBuffer)return HX(new Uint8Array($));return HX($)}async function WH({prompt:$,supportedUrls:Z,download:J=ft()}){let Y=await xt($.messages,J,Z),X=new Map;for(let V of $.messages)if(V.role==="assistant"&&Array.isArray(V.content)){for(let U of V.content)if(U.type==="tool-approval-request"&&"approvalId"in U&&"toolCallId"in U)X.set(U.approvalId,U.toolCallId)}let Q=new Set;for(let V of $.messages)if(V.role==="tool"){for(let U of V.content)if(U.type==="tool-approval-response"){let H=X.get(U.approvalId);if(H)Q.add(H)}}let G=[...$.system!=null?typeof $.system==="string"?[{role:"system",content:$.system}]:y5($.system).map((V)=>({role:"system",content:V.content,providerOptions:V.providerOptions})):[],...$.messages.map((V)=>yt({message:V,downloadedAssets:Y}))],W=[];for(let V of G){if(V.role!=="tool"){W.push(V);continue}let U=W.at(-1);if((U==null?void 0:U.role)==="tool")U.content.push(...V.content);else W.push(V)}let K=new Set;for(let V of W)switch(V.role){case"assistant":{for(let U of V.content)if(U.type==="tool-call"&&!U.providerExecuted)K.add(U.toolCallId);break}case"tool":{for(let U of V.content)if(U.type==="tool-result")K.delete(U.toolCallId);break}case"user":case"system":for(let U of Q)K.delete(U);if(K.size>0)throw new IL({toolCallIds:Array.from(K)});break}for(let V of Q)K.delete(V);if(K.size>0)throw new IL({toolCallIds:Array.from(K)});return W.filter((V)=>V.role!=="tool"||V.content.length>0)}function yt({message:$,downloadedAssets:Z}){let J=$.role;switch(J){case"system":return{role:"system",content:$.content,providerOptions:$.providerOptions};case"user":{if(typeof $.content==="string")return{role:"user",content:[{type:"text",text:$.content}],providerOptions:$.providerOptions};return{role:"user",content:$.content.map((Y)=>ht(Y,Z)).filter((Y)=>Y.type!=="text"||Y.text!==""),providerOptions:$.providerOptions}}case"assistant":{if(typeof $.content==="string")return{role:"assistant",content:[{type:"text",text:$.content}],providerOptions:$.providerOptions};return{role:"assistant",content:$.content.filter((Y)=>Y.type!=="text"||Y.text!==""||Y.providerOptions!=null).filter((Y)=>Y.type!=="tool-approval-request").map((Y)=>{let X=Y.providerOptions;switch(Y.type){case"file":{let{data:Q,mediaType:G}=hT(Y.data);return{type:"file",data:Q,filename:Y.filename,mediaType:G!=null?G:Y.mediaType,providerOptions:X}}case"reasoning":return{type:"reasoning",text:Y.text,providerOptions:X};case"text":return{type:"text",text:Y.text,providerOptions:X};case"tool-call":return{type:"tool-call",toolCallId:Y.toolCallId,toolName:Y.toolName,input:Y.input,providerExecuted:Y.providerExecuted,providerOptions:X};case"tool-result":return{type:"tool-result",toolCallId:Y.toolCallId,toolName:Y.toolName,output:EL(Y.output),providerOptions:X}}}),providerOptions:$.providerOptions}}case"tool":return{role:"tool",content:$.content.filter((Y)=>Y.type!=="tool-approval-response"||Y.providerExecuted).map((Y)=>{switch(Y.type){case"tool-result":return{type:"tool-result",toolCallId:Y.toolCallId,toolName:Y.toolName,output:EL(Y.output),providerOptions:Y.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:Y.approvalId,approved:Y.approved,reason:Y.reason}}}),providerOptions:$.providerOptions};default:throw new qt({role:J})}}async function xt($,Z,J){let Y=$.filter((Q)=>Q.role==="user").map((Q)=>Q.content).filter((Q)=>Array.isArray(Q)).flat().filter((Q)=>Q.type==="image"||Q.type==="file").map((Q)=>{var G;let W=(G=Q.mediaType)!=null?G:Q.type==="image"?"image/*":void 0,K=Q.type==="image"?Q.image:Q.data;if(typeof K==="string")try{K=new URL(K)}catch(V){}return{mediaType:W,data:K}}).filter((Q)=>Q.data instanceof URL).map((Q)=>({url:Q.data,isUrlSupportedByModel:Q.mediaType!=null&&lL({url:Q.data.toString(),mediaType:Q.mediaType,supportedUrls:J})})),X=await Z(Y);return Object.fromEntries(X.map((Q,G)=>Q==null?null:[Y[G].url.toString(),{data:Q.data,mediaType:Q.mediaType}]).filter((Q)=>Q!=null))}function ht($,Z){var J;if($.type==="text")return{type:"text",text:$.text,providerOptions:$.providerOptions};let Y,X=$.type;switch(X){case"image":Y=$.image;break;case"file":Y=$.data;break;default:throw Error(`Unsupported part type: ${X}`)}let{data:Q,mediaType:G}=hT(Y),W=G!=null?G:$.mediaType,K=Q;if(K instanceof URL){let V=Z[K.toString()];if(V)K=V.data,W!=null||(W=V.mediaType)}switch(X){case"image":{if(K instanceof Uint8Array||typeof K==="string")W=(J=St({data:K,signatures:Et}))!=null?J:W;return{type:"file",mediaType:W!=null?W:"image/*",filename:void 0,data:K,providerOptions:$.providerOptions}}case"file":{if(W==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:W,filename:$.filename,data:K,providerOptions:$.providerOptions}}}}function EL($){if($.type!=="content")return $;return{type:"content",value:$.value.map((Z)=>{if(Z.type!=="media")return Z;if(Z.mediaType.startsWith("image/"))return{type:"image-data",data:Z.data,mediaType:Z.mediaType};return{type:"file-data",data:Z.data,mediaType:Z.mediaType}})}}async function BJ({toolCallId:$,input:Z,output:J,tool:Y,errorMode:X}){if(X==="text")return{type:"error-text",value:r6(J)};else if(X==="json")return{type:"error-json",value:bL(J)};if(Y==null?void 0:Y.toModelOutput)return await Y.toModelOutput({toolCallId:$,input:Z,output:J});return typeof J==="string"?{type:"text",value:J}:{type:"json",value:bL(J)}}function bL($){return $===void 0?null:$}function BX({maxOutputTokens:$,temperature:Z,topP:J,topK:Y,presencePenalty:X,frequencyPenalty:Q,seed:G,stopSequences:W}){if($!=null){if(!Number.isInteger($))throw new r1({parameter:"maxOutputTokens",value:$,message:"maxOutputTokens must be an integer"});if($<1)throw new r1({parameter:"maxOutputTokens",value:$,message:"maxOutputTokens must be >= 1"})}if(Z!=null){if(typeof Z!=="number")throw new r1({parameter:"temperature",value:Z,message:"temperature must be a number"})}if(J!=null){if(typeof J!=="number")throw new r1({parameter:"topP",value:J,message:"topP must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new r1({parameter:"topK",value:Y,message:"topK must be a number"})}if(X!=null){if(typeof X!=="number")throw new r1({parameter:"presencePenalty",value:X,message:"presencePenalty must be a number"})}if(Q!=null){if(typeof Q!=="number")throw new r1({parameter:"frequencyPenalty",value:Q,message:"frequencyPenalty must be a number"})}if(G!=null){if(!Number.isInteger(G))throw new r1({parameter:"seed",value:G,message:"seed must be an integer"})}return{maxOutputTokens:$,temperature:Z,topP:J,topK:Y,presencePenalty:X,frequencyPenalty:Q,stopSequences:W,seed:G}}function gt($){return $!=null&&Object.keys($).length>0}async function ut({tools:$,toolChoice:Z,activeTools:J}){if(!gt($))return{tools:void 0,toolChoice:void 0};let Y=J!=null?Object.entries($).filter(([Q])=>J.includes(Q)):Object.entries($),X=[];for(let[Q,G]of Y){let W=G.type;switch(W){case void 0:case"dynamic":case"function":X.push({type:"function",name:Q,description:G.description,inputSchema:await v8(G.inputSchema).jsonSchema,...G.inputExamples!=null?{inputExamples:G.inputExamples}:{},providerOptions:G.providerOptions,...G.strict!=null?{strict:G.strict}:{}});break;case"provider":X.push({type:"provider",name:Q,id:G.id,args:G.args});break;default:throw Error(`Unsupported tool type: ${W}`)}}return{tools:X,toolChoice:Z==null?{type:"auto"}:typeof Z==="string"?{type:Z}:{type:"tool",toolName:Z.toolName}}}var zX=D.lazy(()=>D.union([D.null(),D.string(),D.number(),D.boolean(),D.record(D.string(),zX.optional()),D.array(zX)])),N0=D.record(D.string(),D.record(D.string(),zX.optional())),gT=D.object({type:D.literal("text"),text:D.string(),providerOptions:N0.optional()}),mt=D.object({type:D.literal("image"),image:D.union([xT,D.instanceof(URL)]),mediaType:D.string().optional(),providerOptions:N0.optional()}),uT=D.object({type:D.literal("file"),data:D.union([xT,D.instanceof(URL)]),filename:D.string().optional(),mediaType:D.string(),providerOptions:N0.optional()}),lt=D.object({type:D.literal("reasoning"),text:D.string(),providerOptions:N0.optional()}),dt=D.object({type:D.literal("tool-call"),toolCallId:D.string(),toolName:D.string(),input:D.unknown(),providerOptions:N0.optional(),providerExecuted:D.boolean().optional()}),pt=D.discriminatedUnion("type",[D.object({type:D.literal("text"),value:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("json"),value:zX,providerOptions:N0.optional()}),D.object({type:D.literal("execution-denied"),reason:D.string().optional(),providerOptions:N0.optional()}),D.object({type:D.literal("error-text"),value:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("error-json"),value:zX,providerOptions:N0.optional()}),D.object({type:D.literal("content"),value:D.array(D.union([D.object({type:D.literal("text"),text:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("media"),data:D.string(),mediaType:D.string()}),D.object({type:D.literal("file-data"),data:D.string(),mediaType:D.string(),filename:D.string().optional(),providerOptions:N0.optional()}),D.object({type:D.literal("file-url"),url:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("file-id"),fileId:D.union([D.string(),D.record(D.string(),D.string())]),providerOptions:N0.optional()}),D.object({type:D.literal("image-data"),data:D.string(),mediaType:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("image-url"),url:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("image-file-id"),fileId:D.union([D.string(),D.record(D.string(),D.string())]),providerOptions:N0.optional()}),D.object({type:D.literal("custom"),providerOptions:N0.optional()})]))})]),mT=D.object({type:D.literal("tool-result"),toolCallId:D.string(),toolName:D.string(),output:pt,providerOptions:N0.optional()}),ct=D.object({type:D.literal("tool-approval-request"),approvalId:D.string(),toolCallId:D.string()}),it=D.object({type:D.literal("tool-approval-response"),approvalId:D.string(),approved:D.boolean(),reason:D.string().optional()}),nt=D.object({role:D.literal("system"),content:D.string(),providerOptions:N0.optional()}),ot=D.object({role:D.literal("user"),content:D.union([D.string(),D.array(D.union([gT,mt,uT]))]),providerOptions:N0.optional()}),st=D.object({role:D.literal("assistant"),content:D.union([D.string(),D.array(D.union([gT,uT,lt,dt,mT,ct]))]),providerOptions:N0.optional()}),rt=D.object({role:D.literal("tool"),content:D.array(D.union([mT,it])),providerOptions:N0.optional()}),at=D.union([nt,ot,st,rt]);async function KH($){if($.prompt==null&&$.messages==null)throw new yZ({prompt:$,message:"prompt or messages must be defined"});if($.prompt!=null&&$.messages!=null)throw new yZ({prompt:$,message:"prompt and messages cannot be defined at the same time"});if($.system!=null&&typeof $.system!=="string"&&!y5($.system).every((Y)=>typeof Y==="object"&&Y!==null&&("role"in Y)&&Y.role==="system"))throw new yZ({prompt:$,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let Z;if($.prompt!=null&&typeof $.prompt==="string")Z=[{role:"user",content:$.prompt}];else if($.prompt!=null&&Array.isArray($.prompt))Z=$.prompt;else if($.messages!=null)Z=$.messages;else throw new yZ({prompt:$,message:"prompt or messages must be defined"});if(Z.length===0)throw new yZ({prompt:$,message:"messages must not be empty"});let J=await y8({value:Z,schema:D.array(at)});if(!J.success)throw new yZ({prompt:$,message:"The messages do not match the ModelMessage[] schema.",cause:J.error});return{messages:Z,system:$.system}}function VH($){if(!pL.isInstance($))return $;let Z=(process==null?void 0:"development")==="production",J="https://ai-sdk.dev/unauthenticated-ai-gateway";if(Z)return new p0({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${J}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
525
+ `).filter(Boolean).flatMap((v)=>{let[h,c,m]=v.split("\t");if(!m)return[];let a=h==="-"&&c==="-",e=a?0:parseInt(h),H0=a?0:parseInt(c);return[{file:m,status:r.get(m)??"modified",binary:a,additions:Number.isFinite(e)?e:0,deletions:Number.isFinite(H0)?H0:0}]}),u=yield*B(h0.map((v)=>v.file));if(u.size>0){let v=h0.filter((h)=>!u.has(h.file));h0.length=0,h0.push(...v)}let l=100,$0=(v,h,c)=>VJ(QX(v,v,h,c,"","",{context:Number.MAX_SAFE_INTEGER}));for(let v=0;v<h0.length;v+=l){let h=h0.slice(v,v+l),c=yield*p(h);for(let m of h){let a=c?.get(m.file)??{before:"",after:""},[e,H0]=m.binary?["",""]:c?[a.before,a.after]:yield*d(m);t.push({file:m.file,patch:m.binary?"":$0(m.file,e,H0),additions:m.additions,deletions:m.deletions,status:m.status})}}return t}))});return yield*vw(w(),(k)=>{return J$.error("cleanup loop failed",{cause:xw.pretty(k)}),T.void}),{cleanup:w,track:I,patch:_,restore:E,revert:f,diff:b,diffFull:y}}));return K4.of({init:T.fn("Snapshot.init")(function*(){yield*B0.get(Q)}),cleanup:T.fn("Snapshot.cleanup")(function*(){return yield*B0.useEffect(Q,(G)=>G.cleanup())}),track:T.fn("Snapshot.track")(function*(){return yield*B0.useEffect(Q,(G)=>G.track())}),patch:T.fn("Snapshot.patch")(function*(G){return yield*B0.useEffect(Q,(W)=>W.patch(G))}),restore:T.fn("Snapshot.restore")(function*(G){return yield*B0.useEffect(Q,(W)=>W.restore(G))}),revert:T.fn("Snapshot.revert")(function*(G){return yield*B0.useEffect(Q,(W)=>W.revert(G))}),diff:T.fn("Snapshot.diff")(function*(G){return yield*B0.useEffect(Q,(W)=>W.diff(G))}),diffFull:T.fn("Snapshot.diffFull")(function*(G,W){return yield*B0.useEffect(Q,(K)=>K.diffFull(G,W))})})})),Ma=mw.pipe(T0.provide(gw),T0.provide(D$.defaultLayer),T0.provide(X8.defaultLayer));var Da=O.String.pipe(O.brand("ProviderID")),X1=Da.pipe(u0(($)=>({zod:P.string().pipe(P.custom()),opencode:$.make("opencode"),anthropic:$.make("anthropic"),openai:$.make("openai"),google:$.make("google"),googleVertex:$.make("google-vertex"),githubCopilot:$.make("github-copilot"),amazonBedrock:$.make("amazon-bedrock"),azure:$.make("azure"),openrouter:$.make("openrouter"),mistral:$.make("mistral"),gitlab:$.make("gitlab")}))),wa=O.String.pipe(O.brand("ModelID")),s1=wa.pipe(u0(($)=>({zod:P.string().pipe(P.custom())})));var lw=P.object({errorID:P.string(),errorName:P.string(),logFile:P.string()}).meta({ref:"ErrorDiagnostic"}),U4=j1.create("MessageOutputLengthError",P.object({})),f5=j1.create("MessageAbortedError",P.object({message:P.string()})),dw=j1.create("StructuredOutputError",P.object({message:P.string(),retries:P.number()})),H4=j1.create("ProviderAuthError",P.object({providerID:P.string(),message:P.string()})),L6=j1.create("APIError",P.object({message:P.string(),statusCode:P.number().optional(),isRetryable:P.boolean(),category:P.string().optional(),upstreamCode:P.string().optional(),requestId:P.string().optional(),outputBudgetRecoveryAvailable:P.boolean().optional(),outputBudgetRecoveryTokens:P.number().int().positive().optional(),diagnostic:lw.optional(),responseHeaders:P.record(P.string(),P.string()).optional(),responseBody:P.string().optional(),metadata:P.record(P.string(),P.string()).optional()})),GX=j1.create("ContextOverflowError",P.object({message:P.string(),responseBody:P.string().optional()})),pw=j1.create("InvalidOutputError",P.object({message:P.string()})),cw=j1.create("ContentFilterError",P.object({message:P.string()})),iw=j1.create("ModelError",P.object({message:P.string()})),nw=P.object({type:P.literal("text")}).meta({ref:"OutputFormatText"}),ow=P.object({type:P.literal("json_schema"),schema:P.record(P.string(),P.any()).meta({ref:"JSONSchema"}),retryCount:P.number().int().min(0).default(2)}).meta({ref:"OutputFormatJsonSchema"}),sw=P.discriminatedUnion("type",[nw,ow]).meta({ref:"OutputFormat"}),P8=P.object({id:MZ.zod,sessionID:r0.zod,messageID:i1.zod}),rw=P8.extend({type:P.literal("snapshot"),snapshot:P.string()}).meta({ref:"SnapshotPart"}),aw=P8.extend({type:P.literal("patch"),hash:P.string(),files:P.string().array()}).meta({ref:"PatchPart"}),tw=P8.extend({type:P.literal("text"),text:P.string(),synthetic:P.boolean().optional(),ignored:P.boolean().optional(),time:P.object({start:P.number(),end:P.number().optional()}).optional(),metadata:P.record(P.string(),P.any()).optional()}).meta({ref:"TextPart"}),ew=P8.extend({type:P.literal("reasoning"),text:P.string(),metadata:P.record(P.string(),P.any()).optional(),time:P.object({start:P.number(),end:P.number().optional()})}).meta({ref:"ReasoningPart"}),gU=P.object({text:P.object({value:P.string(),start:P.number().int(),end:P.number().int()}).meta({ref:"FilePartSourceText"})}),$L=gU.extend({type:P.literal("file"),path:P.string()}).meta({ref:"FileSource"}),ZL=gU.extend({type:P.literal("symbol"),path:P.string(),range:X4.Range,name:P.string(),kind:P.number().int()}).meta({ref:"SymbolSource"}),JL=gU.extend({type:P.literal("resource"),clientName:P.string(),uri:P.string()}).meta({ref:"ResourceSource"}),YL=P.discriminatedUnion("type",[$L,ZL,JL]).meta({ref:"FilePartSource"}),uU=P8.extend({type:P.literal("file"),mime:P.string(),filename:P.string().optional(),url:P.string(),source:YL.optional()}).meta({ref:"FilePart"}),XL=P8.extend({type:P.literal("agent"),name:P.string(),source:P.object({value:P.string(),start:P.number().int(),end:P.number().int()}).optional()}).meta({ref:"AgentPart"}),QL=P8.extend({type:P.literal("checkpoint"),checkpointDir:P.string(),checkpointNumber:P.number(),coveredUpTo:i1.zod}).meta({ref:"CheckpointPart"}),GL=P8.extend({type:P.literal("subtask"),prompt:P.string(),description:P.string(),agent:P.string(),model:P.object({providerID:X1.zod,modelID:s1.zod}).optional(),command:P.string().optional()}).meta({ref:"SubtaskPart"}),WL=P8.extend({type:P.literal("compaction"),auto:P.boolean(),overflow:P.boolean().optional(),tail_start_id:i1.zod.optional()}).meta({ref:"CompactionPart"}),KL=P8.extend({type:P.literal("retry"),attempt:P.number(),error:L6.Schema,time:P.object({created:P.number()})}).meta({ref:"RetryPart"}),VL=P8.extend({type:P.literal("step-start"),snapshot:P.string().optional()}).meta({ref:"StepStartPart"}),UL=P.object({total:P.number().optional(),input:P.number(),output:P.number(),reasoning:P.number(),cache:P.object({read:P.number(),write:P.number()})}),HL=P8.extend({type:P.literal("step-finish"),reason:P.string(),snapshot:P.string().optional(),cost:P.number(),costCredits:P.number().optional(),tokens:UL,contextWindow:P.number().optional()}).meta({ref:"StepFinishPart"}),BL=P.object({status:P.literal("pending"),input:P.record(P.string(),P.any()),raw:P.string()}).meta({ref:"ToolStatePending"}),zL=P.object({status:P.literal("running"),input:P.record(P.string(),P.any()),title:P.string().optional(),metadata:P.record(P.string(),P.any()).optional(),time:P.object({start:P.number()})}).meta({ref:"ToolStateRunning"}),FL=P.object({status:P.literal("completed"),input:P.record(P.string(),P.any()),output:P.string(),title:P.string(),metadata:P.record(P.string(),P.any()),time:P.object({start:P.number(),end:P.number(),compacted:P.number().optional()}),attachments:uU.array().optional()}).meta({ref:"ToolStateCompleted"}),AL=P.object({status:P.literal("error"),input:P.record(P.string(),P.any()),error:P.string(),metadata:P.record(P.string(),P.any()).optional(),time:P.object({start:P.number(),end:P.number()})}).meta({ref:"ToolStateError"}),OL=P.discriminatedUnion("status",[BL,zL,FL,AL]).meta({ref:"ToolState"}),qL=P8.extend({type:P.literal("tool"),callID:P.string(),tool:P.string(),state:OL,metadata:P.record(P.string(),P.any()).optional()}).meta({ref:"ToolPart"}),jL=P.object({id:i1.zod,sessionID:r0.zod,agentID:P.string().optional()}),NL=P.object({hookPhase:P.enum(["pre","post"]),hookIteration:P.number().int().nonnegative(),pluginNames:P.array(P.string()),hookIDs:P.array(P.string())}).meta({ref:"Provenance"}),ML=jL.extend({role:P.literal("user"),time:P.object({created:P.number()}),format:sw.optional(),summary:P.object({title:P.string().optional(),body:P.string().optional(),diffs:vZ.FileDiff.array()}).optional(),agent:P.string(),model:P.object({providerID:X1.zod,modelID:s1.zod,variant:P.string().optional()}),system:P.string().optional(),tools:P.record(P.string(),P.boolean()).optional(),provenance:NL.optional(),outputBudgetRecoveryTokens:P.number().int().positive().optional()}).meta({ref:"UserMessage"}),mU=P.discriminatedUnion("type",[tw,GL,ew,uU,qL,VL,HL,rw,aw,XL,KL,QL,WL]).meta({ref:"Part"}),DL=jL.extend({role:P.literal("assistant"),time:P.object({created:P.number(),completed:P.number().optional()}),error:P.discriminatedUnion("name",[H4.Schema,j1.Unknown.Schema,U4.Schema,f5.Schema,dw.Schema,GX.Schema,pw.Schema,cw.Schema,iw.Schema,L6.Schema]).optional(),parentID:i1.zod,modelID:s1.zod,providerID:X1.zod,mode:P.string(),agent:P.string(),path:P.object({cwd:P.string(),root:P.string()}),summary:P.boolean().optional(),cost:P.number(),costCredits:P.number().optional(),tokens:UL,contextWindow:P.number().optional(),structured:P.any().optional(),variant:P.string().optional(),finish:P.string().optional()}).meta({ref:"AssistantMessage"}),lU=P.discriminatedUnion("role",[ML,DL]).meta({ref:"Message"}),La={Updated:X$.define({type:"message.updated",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:lU})}),Removed:X$.define({type:"message.removed",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,messageID:i1.zod})}),PartUpdated:X$.define({type:"message.part.updated",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,part:mU,time:P.number()})}),PartDelta:L1.define("message.part.delta",P.object({sessionID:r0.zod,messageID:i1.zod,partID:MZ.zod,field:P.string(),delta:P.string()})),PartRemoved:X$.define({type:"message.part.removed",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,messageID:i1.zod,partID:MZ.zod})})},Ta=P.object({info:lU,parts:P.array(mU)});var Ra=P.object({id:i1.zod,time:P.number()}),dU={encode($){return Buffer.from(JSON.stringify($)).toString("base64url")},decode($){return Ra.parse(JSON.parse(Buffer.from($,"base64url").toString("utf8")))}},LL=($)=>({...$.data,id:$.id,sessionID:$.session_id,agentID:$.agent_id}),TL=($)=>({...$.data,id:$.id,sessionID:$.session_id,messageID:$.message_id}),Pa=($)=>wL(WX(w$.time_created,$.time),O$(m0(w$.time_created,$.time),WX(w$.id,$.id)));function Ia($){let Z=$.map((Y)=>Y.id),J=new Map;if(Z.length>0){let Y=W1.use((X)=>X.select().from(I8).where(k5(I8.message_id,Z)).orderBy(I8.message_id,I8.id).all());for(let X of Y){let Q=TL(X),G=J.get(X.message_id);if(G)G.push(Q);else J.set(X.message_id,[Q])}}return $.map((Y)=>({info:LL(Y),parts:J.get(Y.id)??[]}))}function RL($){let Z=$.before?dU.decode($.before):void 0,J=$.agentID==="*"?void 0:m0(w$.agent_id,$.agentID??"main"),Y=O$(m0(w$.session_id,$.sessionID),...Z?[Pa(Z)]:[],...J?[J]:[]),X=W1.use((V)=>V.select().from(w$).where(Y).orderBy(o6(w$.time_created),o6(w$.id)).limit($.limit+1).all());if(X.length===0){if(!W1.use((U)=>U.select({id:I1.id}).from(I1).where(m0(I1.id,$.sessionID)).get()))throw new KX({message:`Session not found: ${$.sessionID}`});return{items:[],more:!1}}let Q=X.length>$.limit,G=Q?X.slice(0,$.limit):X,W=Ia(G);W.reverse();let K=G.at(-1);return{items:W,more:Q,cursor:Q&&K?dU.encode({id:K.id,time:K.time_created}):void 0}}function*pU($,Z){let Y;while(!0){let X=RL({sessionID:$,limit:50,before:Y,agentID:Z?.agentID});if(X.items.length===0)break;for(let Q=X.items.length-1;Q>=0;Q--)yield X.items[Q];if(!X.more||!X.cursor)break;Y=X.cursor}}function PL($){return W1.use((J)=>J.select().from(I8).where(m0(I8.message_id,$)).orderBy(I8.id).all()).map(TL)}function Ca($){let Z=W1.use((J)=>J.select().from(w$).where(O$(m0(w$.id,$.messageID),m0(w$.session_id,$.sessionID))).get());if(!Z)throw new KX({message:`Message not found: ${$.messageID}`});return{info:LL(Z),parts:PL($.messageID)}}function cU($){let Z=[];for(let J of $)if(Z.push(J),J.info.role==="user"&&J.parts.some((Y)=>Y.type==="checkpoint"||Y.type==="compaction"))break;return Z.reverse(),Z}var Ea=T.fnUntraced(function*($,Z){let J=cU(pU($,{agentID:Z?.agentID}));if(!Z?.contextFrom)return J;let Y=pU(Z.contextFrom,{agentID:"main"}),X=cU(Y);if(Z.contextWatermark){let Q=X.findIndex((G)=>G.info.id===Z.contextWatermark);if(Q>=0)return[...X.slice(0,Q+1),...J]}return[...X,...J]});var lT=m6(yL(),1),zJ=m6(yL(),1);var ba=Object.defineProperty,_a=($,Z)=>{for(var J in Z)ba($,J,{get:Z[J],enumerable:!0})},iL="AI_InvalidArgumentError",nL=`vercel.ai.error.${iL}`,Sa=Symbol.for(nL),oL,r1=class extends p0{constructor({parameter:$,value:Z,message:J}){super({name:iL,message:`Invalid argument for parameter ${$}: ${J}`});this[oL]=!0,this.parameter=$,this.value=Z}static isInstance($){return p0.hasMarker($,nL)}};oL=Sa;var fa="AI_InvalidStreamPartError",ka=`vercel.ai.error.${fa}`,va=Symbol.for(ka),ya;ya=va;var sL="AI_InvalidToolApprovalError",rL=`vercel.ai.error.${sL}`,xa=Symbol.for(rL),aL,ha=class extends p0{constructor({approvalId:$}){super({name:sL,message:`Tool approval response references unknown approvalId: "${$}". No matching tool-approval-request found in message history.`});this[aL]=!0,this.approvalId=$}static isInstance($){return p0.hasMarker($,rL)}};aL=xa;var tL="AI_InvalidToolInputError",eL=`vercel.ai.error.${tL}`,ga=Symbol.for(eL),$T,GH=class extends p0{constructor({toolInput:$,toolName:Z,cause:J,message:Y=`Invalid input for tool ${Z}: ${r6(J)}`}){super({name:tL,message:Y,cause:J});this[$T]=!0,this.toolInput=$,this.toolName=Z}static isInstance($){return p0.hasMarker($,eL)}};$T=ga;var ZT="AI_ToolCallNotFoundForApprovalError",JT=`vercel.ai.error.${ZT}`,ua=Symbol.for(JT),YT,XT=class extends p0{constructor({toolCallId:$,approvalId:Z}){super({name:ZT,message:`Tool call "${$}" not found for approval request "${Z}".`});this[YT]=!0,this.toolCallId=$,this.approvalId=Z}static isInstance($){return p0.hasMarker($,JT)}};YT=ua;var QT="AI_MissingToolResultsError",GT=`vercel.ai.error.${QT}`,ma=Symbol.for(GT),WT,IL=class extends p0{constructor({toolCallIds:$}){super({name:QT,message:`Tool result${$.length>1?"s are":" is"} missing for tool call${$.length>1?"s":""} ${$.join(", ")}.`});this[WT]=!0,this.toolCallIds=$}static isInstance($){return p0.hasMarker($,GT)}};WT=ma;var la="AI_NoImageGeneratedError",da=`vercel.ai.error.${la}`,pa=Symbol.for(da),ca;ca=pa;var KT="AI_NoObjectGeneratedError",VT=`vercel.ai.error.${KT}`,ia=Symbol.for(VT),UT,E8=class extends p0{constructor({message:$="No object generated.",cause:Z,text:J,response:Y,usage:X,finishReason:Q}){super({name:KT,message:$,cause:Z});this[UT]=!0,this.text=J,this.response=Y,this.usage=X,this.finishReason=Q}static isInstance($){return p0.hasMarker($,VT)}};UT=ia;var HT="AI_NoOutputGeneratedError",BT=`vercel.ai.error.${HT}`,na=Symbol.for(BT),zT,oa=class extends p0{constructor({message:$="No output generated.",cause:Z}={}){super({name:HT,message:$,cause:Z});this[zT]=!0}static isInstance($){return p0.hasMarker($,BT)}};zT=na;var sa="AI_NoSpeechGeneratedError",ra=`vercel.ai.error.${sa}`,aa=Symbol.for(ra),ta;ta=aa;var ea="AI_NoTranscriptGeneratedError",$t=`vercel.ai.error.${ea}`,Zt=Symbol.for($t),Jt;Jt=Zt;var Yt="AI_NoVideoGeneratedError",Xt=`vercel.ai.error.${Yt}`,Qt=Symbol.for(Xt),Gt;Gt=Qt;var FT="AI_NoSuchToolError",AT=`vercel.ai.error.${FT}`,Wt=Symbol.for(AT),OT,tU=class extends p0{constructor({toolName:$,availableTools:Z=void 0,message:J=`Model tried to call unavailable tool '${$}'. ${Z===void 0?"No tools are available.":`Available tools: ${Z.join(", ")}.`}`}){super({name:FT,message:J});this[OT]=!0,this.toolName=$,this.availableTools=Z}static isInstance($){return p0.hasMarker($,AT)}};OT=Wt;var qT="AI_ToolCallRepairError",jT=`vercel.ai.error.${qT}`,Kt=Symbol.for(jT),NT,Vt=class extends p0{constructor({cause:$,originalError:Z,message:J=`Error repairing tool call: ${r6($)}`}){super({name:qT,message:J,cause:$});this[NT]=!0,this.originalError=Z}static isInstance($){return p0.hasMarker($,jT)}};NT=Kt;var Ut=class extends p0{constructor($){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${$.version} for provider "${$.provider}" and model "${$.modelId}". AI SDK 5 only supports models that implement specification version "v2".`});this.version=$.version,this.provider=$.provider,this.modelId=$.modelId}},MT="AI_UIMessageStreamError",DT=`vercel.ai.error.${MT}`,Ht=Symbol.for(DT),wT,UJ=class extends p0{constructor({chunkType:$,chunkId:Z,message:J}){super({name:MT,message:J});this[wT]=!0,this.chunkType=$,this.chunkId=Z}static isInstance($){return p0.hasMarker($,DT)}};wT=Ht;var Bt="AI_InvalidDataContentError",zt=`vercel.ai.error.${Bt}`,Ft=Symbol.for(zt),At;At=Ft;var LT="AI_InvalidMessageRoleError",TT=`vercel.ai.error.${LT}`,Ot=Symbol.for(TT),RT,qt=class extends p0{constructor({role:$,message:Z=`Invalid message role: '${$}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:LT,message:Z});this[RT]=!0,this.role=$}static isInstance($){return p0.hasMarker($,TT)}};RT=Ot;var PT="AI_MessageConversionError",IT=`vercel.ai.error.${PT}`,jt=Symbol.for(IT),CT,Nt=class extends p0{constructor({originalMessage:$,message:Z}){super({name:PT,message:Z});this[CT]=!0,this.originalMessage=$}static isInstance($){return p0.hasMarker($,IT)}};CT=jt;var ET="AI_RetryError",bT=`vercel.ai.error.${ET}`,Mt=Symbol.for(bT),_T,O4=class extends p0{constructor({message:$,reason:Z,errors:J}){super({name:ET,message:$});this[_T]=!0,this.reason=Z,this.errors=J,this.lastError=J[J.length-1]}static isInstance($){return p0.hasMarker($,bT)}};_T=Mt;function y5($){return $===void 0?[]:Array.isArray($)?$:[$]}async function v5($){for(let Z of y5($.callbacks)){if(Z==null)continue;try{await Z($.event)}catch(J){}}}function Dt({warning:$,provider:Z,model:J}){let Y=`AI SDK Warning (${Z} / ${J}):`;switch($.type){case"unsupported":{let X=`${Y} The feature "${$.feature}" is not supported.`;if($.details)X+=` ${$.details}`;return X}case"compatibility":{let X=`${Y} The feature "${$.feature}" is used in a compatibility mode.`;if($.details)X+=` ${$.details}`;return X}case"other":return`${Y} ${$.message}`;default:return`${Y} ${JSON.stringify($,null,2)}`}}var wt="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",CL=!1,D4=($)=>{if($.warnings.length===0)return;let Z=globalThis.AI_SDK_LOG_WARNINGS;if(Z===!1)return;if(typeof Z==="function"){Z($);return}if(!CL)CL=!0,console.info(wt);for(let J of $.warnings)console.warn(Dt({warning:J,provider:$.provider,model:$.model}))};function Lt({provider:$,modelId:Z}){D4({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:$,model:Z})}function Tt($){if($.specificationVersion==="v3")return $;return Lt({provider:$.provider,modelId:$.modelId}),new Proxy($,{get(Z,J){switch(J){case"specificationVersion":return"v3";case"doGenerate":return async(...Y)=>{let X=await Z.doGenerate(...Y);return{...X,finishReason:ST(X.finishReason),usage:fT(X.usage)}};case"doStream":return async(...Y)=>{let X=await Z.doStream(...Y);return{...X,stream:Rt(X.stream)}};default:return Z[J]}}})}function Rt($){return $.pipeThrough(new TransformStream({transform(Z,J){switch(Z.type){case"finish":J.enqueue({...Z,finishReason:ST(Z.finishReason),usage:fT(Z.usage)});break;default:J.enqueue(Z);break}}}))}function ST($){return{unified:$==="unknown"?"other":$,raw:void 0}}function fT($){return{inputTokens:{total:$.inputTokens,noCache:void 0,cacheRead:$.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:$.outputTokens,text:void 0,reasoning:$.reasoningTokens}}}function w4($){if(typeof $!=="string"){if($.specificationVersion!=="v3"&&$.specificationVersion!=="v2"){let Z=$;throw new Ut({version:Z.specificationVersion,provider:Z.provider,modelId:Z.modelId})}return Tt($)}return Pt().languageModel($)}function Pt(){var $;return($=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?$:cL}function kT($){if($==null)return;if(typeof $==="number")return $;return $.totalMs}function It($){if($==null||typeof $==="number")return;return $.stepMs}function Ct($){if($==null||typeof $==="number")return;return $.chunkMs}var Et=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}];var bt=($)=>{let Z=typeof $==="string"?FJ($):$,J=(Z[6]&127)<<21|(Z[7]&127)<<14|(Z[8]&127)<<7|Z[9]&127;return Z.slice(J+10)};function _t($){return typeof $==="string"&&$.startsWith("SUQz")||typeof $!=="string"&&$.length>10&&$[0]===73&&$[1]===68&&$[2]===51?bt($):$}function St({data:$,signatures:Z}){let J=_t($),Y=typeof J==="string"?FJ(J.substring(0,Math.min(J.length,24))):J;for(let X of Z)if(Y.length>=X.bytesPrefix.length&&X.bytesPrefix.every((Q,G)=>Q===null||Y[G]===Q))return X.mediaType;return}var vT="6.0.168",yT=async({url:$,maxBytes:Z,abortSignal:J})=>{var Y;let X=$.toString();aU(X);try{let Q=await fetch(X,{headers:OX({},`ai-sdk/${vT}`,uL()),signal:J});if(Q.redirected)aU(Q.url);if(!Q.ok)throw new z4({url:X,statusCode:Q.status,statusText:Q.statusText});return{data:await gL({response:Q,url:X,maxBytes:Z!=null?Z:hL}),mediaType:(Y=Q.headers.get("content-type"))!=null?Y:void 0}}catch(Q){if(z4.isInstance(Q))throw Q;throw new z4({url:X,cause:Q})}},ft=($=yT)=>(Z)=>Promise.all(Z.map(async(J)=>J.isUrlSupportedByModel?null:$(J)));function kt($){try{let[Z,J]=$.split(",");return{mediaType:Z.split(";")[0].split(":")[1],base64Content:J}}catch(Z){return{mediaType:void 0,base64Content:void 0}}}var xT=D.union([D.string(),D.instanceof(Uint8Array),D.instanceof(ArrayBuffer),D.custom(($)=>{var Z,J;return(J=(Z=globalThis.Buffer)==null?void 0:Z.isBuffer($))!=null?J:!1},{message:"Must be a Buffer"})]);function hT($){if($ instanceof Uint8Array)return{data:$,mediaType:void 0};if($ instanceof ArrayBuffer)return{data:new Uint8Array($),mediaType:void 0};if(typeof $==="string")try{$=new URL($)}catch(Z){}if($ instanceof URL&&$.protocol==="data:"){let{mediaType:Z,base64Content:J}=kt($.toString());if(Z==null||J==null)throw new p0({name:"InvalidDataContentError",message:`Invalid data URL format in content ${$.toString()}`});return{data:J,mediaType:Z}}return{data:$,mediaType:void 0}}function vt($){if(typeof $==="string")return $;if($ instanceof ArrayBuffer)return HX(new Uint8Array($));return HX($)}async function WH({prompt:$,supportedUrls:Z,download:J=ft()}){let Y=await xt($.messages,J,Z),X=new Map;for(let V of $.messages)if(V.role==="assistant"&&Array.isArray(V.content)){for(let U of V.content)if(U.type==="tool-approval-request"&&"approvalId"in U&&"toolCallId"in U)X.set(U.approvalId,U.toolCallId)}let Q=new Set;for(let V of $.messages)if(V.role==="tool"){for(let U of V.content)if(U.type==="tool-approval-response"){let H=X.get(U.approvalId);if(H)Q.add(H)}}let G=[...$.system!=null?typeof $.system==="string"?[{role:"system",content:$.system}]:y5($.system).map((V)=>({role:"system",content:V.content,providerOptions:V.providerOptions})):[],...$.messages.map((V)=>yt({message:V,downloadedAssets:Y}))],W=[];for(let V of G){if(V.role!=="tool"){W.push(V);continue}let U=W.at(-1);if((U==null?void 0:U.role)==="tool")U.content.push(...V.content);else W.push(V)}let K=new Set;for(let V of W)switch(V.role){case"assistant":{for(let U of V.content)if(U.type==="tool-call"&&!U.providerExecuted)K.add(U.toolCallId);break}case"tool":{for(let U of V.content)if(U.type==="tool-result")K.delete(U.toolCallId);break}case"user":case"system":for(let U of Q)K.delete(U);if(K.size>0)throw new IL({toolCallIds:Array.from(K)});break}for(let V of Q)K.delete(V);if(K.size>0)throw new IL({toolCallIds:Array.from(K)});return W.filter((V)=>V.role!=="tool"||V.content.length>0)}function yt({message:$,downloadedAssets:Z}){let J=$.role;switch(J){case"system":return{role:"system",content:$.content,providerOptions:$.providerOptions};case"user":{if(typeof $.content==="string")return{role:"user",content:[{type:"text",text:$.content}],providerOptions:$.providerOptions};return{role:"user",content:$.content.map((Y)=>ht(Y,Z)).filter((Y)=>Y.type!=="text"||Y.text!==""),providerOptions:$.providerOptions}}case"assistant":{if(typeof $.content==="string")return{role:"assistant",content:[{type:"text",text:$.content}],providerOptions:$.providerOptions};return{role:"assistant",content:$.content.filter((Y)=>Y.type!=="text"||Y.text!==""||Y.providerOptions!=null).filter((Y)=>Y.type!=="tool-approval-request").map((Y)=>{let X=Y.providerOptions;switch(Y.type){case"file":{let{data:Q,mediaType:G}=hT(Y.data);return{type:"file",data:Q,filename:Y.filename,mediaType:G!=null?G:Y.mediaType,providerOptions:X}}case"reasoning":return{type:"reasoning",text:Y.text,providerOptions:X};case"text":return{type:"text",text:Y.text,providerOptions:X};case"tool-call":return{type:"tool-call",toolCallId:Y.toolCallId,toolName:Y.toolName,input:Y.input,providerExecuted:Y.providerExecuted,providerOptions:X};case"tool-result":return{type:"tool-result",toolCallId:Y.toolCallId,toolName:Y.toolName,output:EL(Y.output),providerOptions:X}}}),providerOptions:$.providerOptions}}case"tool":return{role:"tool",content:$.content.filter((Y)=>Y.type!=="tool-approval-response"||Y.providerExecuted).map((Y)=>{switch(Y.type){case"tool-result":return{type:"tool-result",toolCallId:Y.toolCallId,toolName:Y.toolName,output:EL(Y.output),providerOptions:Y.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:Y.approvalId,approved:Y.approved,reason:Y.reason}}}),providerOptions:$.providerOptions};default:throw new qt({role:J})}}async function xt($,Z,J){let Y=$.filter((Q)=>Q.role==="user").map((Q)=>Q.content).filter((Q)=>Array.isArray(Q)).flat().filter((Q)=>Q.type==="image"||Q.type==="file").map((Q)=>{var G;let W=(G=Q.mediaType)!=null?G:Q.type==="image"?"image/*":void 0,K=Q.type==="image"?Q.image:Q.data;if(typeof K==="string")try{K=new URL(K)}catch(V){}return{mediaType:W,data:K}}).filter((Q)=>Q.data instanceof URL).map((Q)=>({url:Q.data,isUrlSupportedByModel:Q.mediaType!=null&&lL({url:Q.data.toString(),mediaType:Q.mediaType,supportedUrls:J})})),X=await Z(Y);return Object.fromEntries(X.map((Q,G)=>Q==null?null:[Y[G].url.toString(),{data:Q.data,mediaType:Q.mediaType}]).filter((Q)=>Q!=null))}function ht($,Z){var J;if($.type==="text")return{type:"text",text:$.text,providerOptions:$.providerOptions};let Y,X=$.type;switch(X){case"image":Y=$.image;break;case"file":Y=$.data;break;default:throw Error(`Unsupported part type: ${X}`)}let{data:Q,mediaType:G}=hT(Y),W=G!=null?G:$.mediaType,K=Q;if(K instanceof URL){let V=Z[K.toString()];if(V)K=V.data,W!=null||(W=V.mediaType)}switch(X){case"image":{if(K instanceof Uint8Array||typeof K==="string")W=(J=St({data:K,signatures:Et}))!=null?J:W;return{type:"file",mediaType:W!=null?W:"image/*",filename:void 0,data:K,providerOptions:$.providerOptions}}case"file":{if(W==null)throw Error("Media type is missing for file part");return{type:"file",mediaType:W,filename:$.filename,data:K,providerOptions:$.providerOptions}}}}function EL($){if($.type!=="content")return $;return{type:"content",value:$.value.map((Z)=>{if(Z.type!=="media")return Z;if(Z.mediaType.startsWith("image/"))return{type:"image-data",data:Z.data,mediaType:Z.mediaType};return{type:"file-data",data:Z.data,mediaType:Z.mediaType}})}}async function BJ({toolCallId:$,input:Z,output:J,tool:Y,errorMode:X}){if(X==="text")return{type:"error-text",value:r6(J)};else if(X==="json")return{type:"error-json",value:bL(J)};if(Y==null?void 0:Y.toModelOutput)return await Y.toModelOutput({toolCallId:$,input:Z,output:J});return typeof J==="string"?{type:"text",value:J}:{type:"json",value:bL(J)}}function bL($){return $===void 0?null:$}function BX({maxOutputTokens:$,temperature:Z,topP:J,topK:Y,presencePenalty:X,frequencyPenalty:Q,seed:G,stopSequences:W}){if($!=null){if(!Number.isInteger($))throw new r1({parameter:"maxOutputTokens",value:$,message:"maxOutputTokens must be an integer"});if($<1)throw new r1({parameter:"maxOutputTokens",value:$,message:"maxOutputTokens must be >= 1"})}if(Z!=null){if(typeof Z!=="number")throw new r1({parameter:"temperature",value:Z,message:"temperature must be a number"})}if(J!=null){if(typeof J!=="number")throw new r1({parameter:"topP",value:J,message:"topP must be a number"})}if(Y!=null){if(typeof Y!=="number")throw new r1({parameter:"topK",value:Y,message:"topK must be a number"})}if(X!=null){if(typeof X!=="number")throw new r1({parameter:"presencePenalty",value:X,message:"presencePenalty must be a number"})}if(Q!=null){if(typeof Q!=="number")throw new r1({parameter:"frequencyPenalty",value:Q,message:"frequencyPenalty must be a number"})}if(G!=null){if(!Number.isInteger(G))throw new r1({parameter:"seed",value:G,message:"seed must be an integer"})}return{maxOutputTokens:$,temperature:Z,topP:J,topK:Y,presencePenalty:X,frequencyPenalty:Q,stopSequences:W,seed:G}}function gt($){return $!=null&&Object.keys($).length>0}async function ut({tools:$,toolChoice:Z,activeTools:J}){if(!gt($))return{tools:void 0,toolChoice:void 0};let Y=J!=null?Object.entries($).filter(([Q])=>J.includes(Q)):Object.entries($),X=[];for(let[Q,G]of Y){let W=G.type;switch(W){case void 0:case"dynamic":case"function":X.push({type:"function",name:Q,description:G.description,inputSchema:await v8(G.inputSchema).jsonSchema,...G.inputExamples!=null?{inputExamples:G.inputExamples}:{},providerOptions:G.providerOptions,...G.strict!=null?{strict:G.strict}:{}});break;case"provider":X.push({type:"provider",name:Q,id:G.id,args:G.args});break;default:throw Error(`Unsupported tool type: ${W}`)}}return{tools:X,toolChoice:Z==null?{type:"auto"}:typeof Z==="string"?{type:Z}:{type:"tool",toolName:Z.toolName}}}var zX=D.lazy(()=>D.union([D.null(),D.string(),D.number(),D.boolean(),D.record(D.string(),zX.optional()),D.array(zX)])),N0=D.record(D.string(),D.record(D.string(),zX.optional())),gT=D.object({type:D.literal("text"),text:D.string(),providerOptions:N0.optional()}),mt=D.object({type:D.literal("image"),image:D.union([xT,D.instanceof(URL)]),mediaType:D.string().optional(),providerOptions:N0.optional()}),uT=D.object({type:D.literal("file"),data:D.union([xT,D.instanceof(URL)]),filename:D.string().optional(),mediaType:D.string(),providerOptions:N0.optional()}),lt=D.object({type:D.literal("reasoning"),text:D.string(),providerOptions:N0.optional()}),dt=D.object({type:D.literal("tool-call"),toolCallId:D.string(),toolName:D.string(),input:D.unknown(),providerOptions:N0.optional(),providerExecuted:D.boolean().optional()}),pt=D.discriminatedUnion("type",[D.object({type:D.literal("text"),value:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("json"),value:zX,providerOptions:N0.optional()}),D.object({type:D.literal("execution-denied"),reason:D.string().optional(),providerOptions:N0.optional()}),D.object({type:D.literal("error-text"),value:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("error-json"),value:zX,providerOptions:N0.optional()}),D.object({type:D.literal("content"),value:D.array(D.union([D.object({type:D.literal("text"),text:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("media"),data:D.string(),mediaType:D.string()}),D.object({type:D.literal("file-data"),data:D.string(),mediaType:D.string(),filename:D.string().optional(),providerOptions:N0.optional()}),D.object({type:D.literal("file-url"),url:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("file-id"),fileId:D.union([D.string(),D.record(D.string(),D.string())]),providerOptions:N0.optional()}),D.object({type:D.literal("image-data"),data:D.string(),mediaType:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("image-url"),url:D.string(),providerOptions:N0.optional()}),D.object({type:D.literal("image-file-id"),fileId:D.union([D.string(),D.record(D.string(),D.string())]),providerOptions:N0.optional()}),D.object({type:D.literal("custom"),providerOptions:N0.optional()})]))})]),mT=D.object({type:D.literal("tool-result"),toolCallId:D.string(),toolName:D.string(),output:pt,providerOptions:N0.optional()}),ct=D.object({type:D.literal("tool-approval-request"),approvalId:D.string(),toolCallId:D.string()}),it=D.object({type:D.literal("tool-approval-response"),approvalId:D.string(),approved:D.boolean(),reason:D.string().optional()}),nt=D.object({role:D.literal("system"),content:D.string(),providerOptions:N0.optional()}),ot=D.object({role:D.literal("user"),content:D.union([D.string(),D.array(D.union([gT,mt,uT]))]),providerOptions:N0.optional()}),st=D.object({role:D.literal("assistant"),content:D.union([D.string(),D.array(D.union([gT,uT,lt,dt,mT,ct]))]),providerOptions:N0.optional()}),rt=D.object({role:D.literal("tool"),content:D.array(D.union([mT,it])),providerOptions:N0.optional()}),at=D.union([nt,ot,st,rt]);async function KH($){if($.prompt==null&&$.messages==null)throw new yZ({prompt:$,message:"prompt or messages must be defined"});if($.prompt!=null&&$.messages!=null)throw new yZ({prompt:$,message:"prompt and messages cannot be defined at the same time"});if($.system!=null&&typeof $.system!=="string"&&!y5($.system).every((Y)=>typeof Y==="object"&&Y!==null&&("role"in Y)&&Y.role==="system"))throw new yZ({prompt:$,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let Z;if($.prompt!=null&&typeof $.prompt==="string")Z=[{role:"user",content:$.prompt}];else if($.prompt!=null&&Array.isArray($.prompt))Z=$.prompt;else if($.messages!=null)Z=$.messages;else throw new yZ({prompt:$,message:"prompt or messages must be defined"});if(Z.length===0)throw new yZ({prompt:$,message:"messages must not be empty"});let J=await y8({value:Z,schema:D.array(at)});if(!J.success)throw new yZ({prompt:$,message:"The messages do not match the ModelMessage[] schema.",cause:J.error});return{messages:Z,system:$.system}}function VH($){if(!pL.isInstance($))return $;let Z=(process==null?void 0:"test")==="production",J="https://ai-sdk.dev/unauthenticated-ai-gateway";if(Z)return new p0({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${J}`});return Object.assign(Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
526
526
 
527
527
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
528
528
 
@@ -660,9 +660,9 @@ data: {"type":"message_stop"}`))K=!0,G.cancel(),H.close();if(V.length>512)V=V.sl
660
660
  <p>You can close this window and return to your terminal.</p>
661
661
  </body>
662
662
  </html>
663
- `),this.cleanup()})}async start(){let $=this.options.host||"127.0.0.1",Z=this.options.port||0;await this.server.listen({host:$,port:Z})}async waitForCallback(){let $=this.options.timeout||60000;return this.timeoutHandle=setTimeout(()=>{this.rejectCallback?.(Error("OAuth callback timeout")),this.cleanup()},$),new Promise((Z,J)=>{this.resolveCallback=Z,this.rejectCallback=J})}getPort(){let $=this.server.server.address();if(!$||typeof $==="string")throw Error("Server not started or using Unix socket");return $.port}getCallbackUrl(){let $=this.options.host||"127.0.0.1",Z=this.getPort();return`http://${$}:${Z}/callback`}cleanup(){if(this.timeoutHandle)clearTimeout(this.timeoutHandle),this.timeoutHandle=void 0;setTimeout(()=>{this.server.close()},100)}async close(){if(this.timeoutHandle)clearTimeout(this.timeoutHandle),this.timeoutHandle=void 0;await this.server.close()}}class UK{options;constructor($){this.options=$}async authorize(){let $=BA(43),Z=_u($),J=BA(32);if(this.options.method==="auto")return this.authorizeWithCallback(Z,J,$);else return this.authorizeWithManualCode(Z,J,$)}async authorizeWithCallback($,Z,J){let Y=new iQ({port:0,host:"127.0.0.1",timeout:this.options.timeout||60000});try{let X=Y.waitForCallback(),Q=Y.getCallbackUrl(),G=this.buildAuthorizationUrl(Q,$,Z);await(await import("./chunk-hwnc2sa5.js")).default(G);let K=await X;if(K.state!==Z)throw Error("State mismatch - possible CSRF attack");return{code:K.code,state:K.state,codeVerifier:J}}finally{await Y.close()}}authorizeWithManualCode($,Z,J){throw this.buildAuthorizationUrl("http://127.0.0.1/callback",$,Z),Error("Manual code entry not yet implemented - use auto method")}buildAuthorizationUrl($,Z,J){let Y=new URLSearchParams({client_id:this.options.clientId,redirect_uri:$,response_type:"code",state:J,scope:this.options.scopes.join(" "),code_challenge:Z,code_challenge_method:"S256"});return`${this.options.instanceUrl.replace(/\/$/,"")}/oauth/authorize?${Y.toString()}`}async exchangeAuthorizationCode($,Z,J){let X=`${this.options.instanceUrl.replace(/\/$/,"")}/oauth/token`,Q=new URLSearchParams({client_id:this.options.clientId,code:$,grant_type:"authorization_code",redirect_uri:J,code_verifier:Z}),G=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!G.ok){let K=await G.text();throw Error(`Token exchange failed: ${G.status} ${G.statusText} - ${K}`)}return await G.json()}async exchangeRefreshToken($){let J=`${this.options.instanceUrl.replace(/\/$/,"")}/oauth/token`,Y=new URLSearchParams({client_id:this.options.clientId,refresh_token:$,grant_type:"refresh_token"}),X=await fetch(J,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!X.ok){let G=await X.text();throw Error(`Token refresh failed: ${X.status} ${X.statusText} - ${G}`)}return await X.json()}}import R$ from"fs";import O7 from"path";import Su from"os";var sQ=process.env.GITLAB_OAUTH_CLIENT_ID||"1d89f9fdb23ee96d4e603201f6861dab6e143c5c3c00469a018a2d94bdc03d4e",uq0="https://gitlab.com",zA=["api"];function nQ(){return process.env.GITLAB_INSTANCE_URL||uq0}function Y$($,Z){try{let J=Su.homedir(),Y=O7.join(J,".local","share","opencode","log");if(!R$.existsSync(Y))R$.mkdirSync(Y,{recursive:!0});let X=O7.join(Y,"gitlab-auth.log"),Q=new Date().toISOString(),G=Z?`[${Q}] ${$}: ${JSON.stringify(Z)}
663
+ `),this.cleanup()})}async start(){let $=this.options.host||"127.0.0.1",Z=this.options.port||0;await this.server.listen({host:$,port:Z})}async waitForCallback(){let $=this.options.timeout||60000;return this.timeoutHandle=setTimeout(()=>{this.rejectCallback?.(Error("OAuth callback timeout")),this.cleanup()},$),new Promise((Z,J)=>{this.resolveCallback=Z,this.rejectCallback=J})}getPort(){let $=this.server.server.address();if(!$||typeof $==="string")throw Error("Server not started or using Unix socket");return $.port}getCallbackUrl(){let $=this.options.host||"127.0.0.1",Z=this.getPort();return`http://${$}:${Z}/callback`}cleanup(){if(this.timeoutHandle)clearTimeout(this.timeoutHandle),this.timeoutHandle=void 0;setTimeout(()=>{this.server.close()},100)}async close(){if(this.timeoutHandle)clearTimeout(this.timeoutHandle),this.timeoutHandle=void 0;await this.server.close()}}class UK{options;constructor($){this.options=$}async authorize(){let $=BA(43),Z=_u($),J=BA(32);if(this.options.method==="auto")return this.authorizeWithCallback(Z,J,$);else return this.authorizeWithManualCode(Z,J,$)}async authorizeWithCallback($,Z,J){let Y=new iQ({port:0,host:"127.0.0.1",timeout:this.options.timeout||60000});try{let X=Y.waitForCallback(),Q=Y.getCallbackUrl(),G=this.buildAuthorizationUrl(Q,$,Z);await(await import("./chunk-0ppnq3a4.js")).default(G);let K=await X;if(K.state!==Z)throw Error("State mismatch - possible CSRF attack");return{code:K.code,state:K.state,codeVerifier:J}}finally{await Y.close()}}authorizeWithManualCode($,Z,J){throw this.buildAuthorizationUrl("http://127.0.0.1/callback",$,Z),Error("Manual code entry not yet implemented - use auto method")}buildAuthorizationUrl($,Z,J){let Y=new URLSearchParams({client_id:this.options.clientId,redirect_uri:$,response_type:"code",state:J,scope:this.options.scopes.join(" "),code_challenge:Z,code_challenge_method:"S256"});return`${this.options.instanceUrl.replace(/\/$/,"")}/oauth/authorize?${Y.toString()}`}async exchangeAuthorizationCode($,Z,J){let X=`${this.options.instanceUrl.replace(/\/$/,"")}/oauth/token`,Q=new URLSearchParams({client_id:this.options.clientId,code:$,grant_type:"authorization_code",redirect_uri:J,code_verifier:Z}),G=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!G.ok){let K=await G.text();throw Error(`Token exchange failed: ${G.status} ${G.statusText} - ${K}`)}return await G.json()}async exchangeRefreshToken($){let J=`${this.options.instanceUrl.replace(/\/$/,"")}/oauth/token`,Y=new URLSearchParams({client_id:this.options.clientId,refresh_token:$,grant_type:"refresh_token"}),X=await fetch(J,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!X.ok){let G=await X.text();throw Error(`Token refresh failed: ${X.status} ${X.statusText} - ${G}`)}return await X.json()}}import R$ from"fs";import O7 from"path";import Su from"os";var sQ=process.env.GITLAB_OAUTH_CLIENT_ID||"1d89f9fdb23ee96d4e603201f6861dab6e143c5c3c00469a018a2d94bdc03d4e",uq0="https://gitlab.com",zA=["api"];function nQ(){return process.env.GITLAB_INSTANCE_URL||uq0}function Y$($,Z){try{let J=Su.homedir(),Y=O7.join(J,".local","share","opencode","log");if(!R$.existsSync(Y))R$.mkdirSync(Y,{recursive:!0});let X=O7.join(Y,"gitlab-auth.log"),Q=new Date().toISOString(),G=Z?`[${Q}] ${$}: ${JSON.stringify(Z)}
664
664
  `:`[${Q}] ${$}
665
- `;R$.appendFileSync(X,G)}catch{}}function FA(){let $=Su.homedir(),Z=process.env.XDG_DATA_HOME;if(Z)return O7.join(Z,"opencode","auth.json");if(process.platform!=="win32")return O7.join($,".local","share","opencode","auth.json");return O7.join($,".opencode","auth.json")}async function fu($,Z,J,Y){let X=FA(),Q=O7.dirname(X);if(!R$.existsSync(Q))R$.mkdirSync(Q,{recursive:!0});let G={};if(R$.existsSync(X)){let W=R$.readFileSync(X,"utf-8");G=JSON.parse(W)}G.gitlab={type:"oauth",access:$,refresh:Z,expires:J,enterpriseUrl:Y},R$.writeFileSync(X,JSON.stringify(G,null,2)),R$.chmodSync(X,384)}async function mq0($,Z){let J=FA(),Y=O7.dirname(J);if(!R$.existsSync(Y))R$.mkdirSync(Y,{recursive:!0});let X={};if(R$.existsSync(J)){let Q=R$.readFileSync(J,"utf-8");X=JSON.parse(Q)}X.gitlab={type:"api",key:$,enterpriseUrl:Z},R$.writeFileSync(J,JSON.stringify(X,null,2)),R$.chmodSync(J,384)}var oQ=null;async function lq0($,Z,J){let Y=Date.now(),X=300000;if(!($.expires<=Y+300000))return Y$("Token is still valid",{expiresAt:new Date($.expires).toISOString(),expiresIn:Math.round(($.expires-Y)/1000/60)+" minutes"}),{apiKey:$.access,instanceUrl:$.enterpriseUrl||J};if(oQ){Y$("Token refresh already in progress, waiting..."),await oQ;let W=await Z();if(W&&W.type==="oauth")return{apiKey:W.access,instanceUrl:W.enterpriseUrl||J};throw Error("Failed to get refreshed auth data")}Y$("Token expired or expiring soon, refreshing...",{expiresAt:new Date($.expires).toISOString(),expired:$.expires<=Y}),oQ=(async()=>{try{let W=$.enterpriseUrl||J,K=new UK({instanceUrl:W,clientId:sQ,scopes:zA,method:"auto"});Y$("Calling exchangeRefreshToken...");let V=await K.exchangeRefreshToken($.refresh),U=Date.now()+V.expires_in*1000;Y$("Token refresh successful",{newExpiresAt:new Date(U).toISOString(),expiresIn:Math.round(V.expires_in/60)+" minutes"}),await fu(V.access_token,V.refresh_token,U,W),Y$("New tokens saved successfully")}catch(W){if(Y$("Token refresh failed",{error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0}),W instanceof Error&&W.message.includes("401")){Y$("Refresh token appears to be revoked (401), clearing auth data");let K=FA();if(R$.existsSync(K)){let V=R$.readFileSync(K,"utf-8"),U=JSON.parse(V);delete U.gitlab,R$.writeFileSync(K,JSON.stringify(U,null,2))}}throw W}})();try{await oQ}finally{oQ=null}let G=await Z();if(G&&G.type==="oauth")return{apiKey:G.access,instanceUrl:G.enterpriseUrl||J};throw Error("Failed to get refreshed auth data after token refresh")}var ku=async($)=>{return{auth:{provider:"gitlab",async loader(J){let Y=await J();if(!Y)return{};if(Y.type==="oauth")try{return{...await lq0(Y,J,nQ()),clientId:sQ}}catch(X){return Y$("Failed to refresh token in loader",{error:X instanceof Error?X.message:String(X)}),{apiKey:Y.access,instanceUrl:Y.enterpriseUrl||nQ(),clientId:sQ}}if(Y.type==="api"){let X=Y.enterpriseUrl||nQ();return{apiKey:Y.key,instanceUrl:X}}return{}},methods:[{type:"oauth",label:"GitLab OAuth",prompts:[],async authorize(){let J=nQ(),Y;try{let N=new URL(J);Y=`${N.protocol}//${N.host}`}catch{throw Error(`Invalid GitLab instance URL: ${J}`)}let{generateSecret:X,generateCodeChallengeFromVerifier:Q}=await import("./chunk-8mthftwc.js"),G=X(43),W=Q(G),K=X(32),V=new iQ({port:8080,host:"127.0.0.1",timeout:120000});await V.start();let U=V.getCallbackUrl(),H=V.waitForCallback(),B=new URLSearchParams({client_id:sQ,redirect_uri:U,response_type:"code",state:K,scope:zA.join(" "),code_challenge:W,code_challenge_method:"S256"}),z=`${Y}/oauth/authorize?${B.toString()}`,{exec:F}=await import("child_process"),A=process.platform;return F(`${A==="darwin"?"open":A==="win32"?"start":"xdg-open"} "${z}"`),{method:"auto",url:z,instructions:"Your browser will open for authentication. The callback will be handled automatically.",async callback(){Y$("callback() called");try{Y$("Waiting for callback...");let N=await H;if(Y$("Received callback",{hasCode:!!N.code,hasState:!!N.state}),N.state!==K)return Y$("State mismatch",{expected:K,received:N.state}),await V.close(),{type:"failed"};Y$("State verified"),Y$("Exchanging code for tokens...");let q=await new UK({instanceUrl:Y,clientId:sQ,scopes:zA,method:"auto"}).exchangeAuthorizationCode(N.code,G,U);Y$("Token exchange successful"),await V.close();let M=Date.now()+q.expires_in*1000;return Y$("Tokens received",{expiresAt:new Date(M).toISOString()}),Y$("Saving auth data..."),await fu(q.access_token,q.refresh_token,M,Y),Y$("Auth data saved successfully"),{type:"success",provider:Y,access:q.access_token,refresh:q.refresh_token,expires:M}}catch(N){Y$("Error in callback",{error:N instanceof Error?N.message:String(N),stack:N instanceof Error?N.stack:void 0});try{await V.close()}catch(L){}return{type:"failed"}}}}}},{type:"api",label:"GitLab Personal Access Token",prompts:[{type:"text",key:"token",message:"Personal Access Token",placeholder:"glpat-xxxxxxxxxxxxxxxxxxxx",validate:(J)=>{if(!J)return"Token is required";if(!J.startsWith("glpat-"))return"Token should start with glpat-";return}}],async authorize(J){let Y=nQ(),X=J?.token;if(!X)return{type:"failed"};let Q;try{let G=new URL(Y);Q=`${G.protocol}//${G.host}`}catch{return{type:"failed"}}try{if(!(await fetch(`${Q}/api/v4/user`,{headers:{Authorization:`Bearer ${X}`}})).ok)return{type:"failed"};return Y$("Saving PAT auth data..."),await mq0(X,Q),Y$("PAT auth data saved successfully"),{type:"success",key:X,provider:Q}}catch{return{type:"failed"}}}}]}}};import dq0 from"http";function vu($){if($===null||$.length===0)return null;try{let Z=Buffer.from($,"base64url").toString("utf8"),J=JSON.parse(Z);if(J.v!==1||typeof J.n!=="string"||J.n.length===0||typeof J.i!=="string"||J.i.length===0||typeof J.r!=="boolean")return null;return{issuer:J.i,requireIssuer:J.r}}catch{return null}}async function xu($={}){let Z=$.callbackPath??"/callback",J=$.createServer?$.createServer():dq0.createServer();return{redirectUri:`http://127.0.0.1:${await pq0(J)}${Z}`,async waitForCode(Q){return cq0(J,Q,$,Z)},close(){J.closeAllConnections?.(),J.close()}}}async function pq0($){return new Promise((Z)=>{$.listen(0,"127.0.0.1",()=>{let J=$.address();Z(J.port)})})}function cq0($,Z,J,Y){let X=nq0(Z);return new Promise((Q,G)=>{let W=!1,K=(V)=>{if(!W)W=!0,V()};if($.on("request",(V,U)=>{let H=new URL(V.url??"/","http://127.0.0.1");if(H.pathname!==Y){U.writeHead(404),U.end("Not found");return}let B=H.searchParams.get("error");if(B!==null){let z=H.searchParams.get("error_description")??B;U.writeHead(400),U.end(`Authorization failed: ${z}`),K(()=>G(Error(`OAuth authorization failed: ${B} \u2014 ${z}`)));return}try{let z=yu({code:H.searchParams.get("code"),state:H.searchParams.get("state"),iss:H.searchParams.get("iss")},X);U.writeHead(200,{"Content-Type":"text/html"}),U.end(oq0(J.landingPage)),K(()=>Q(z))}catch(z){U.writeHead(400),U.end(z instanceof Error?z.message:"Invalid OAuth callback"),K(()=>G(z instanceof Error?z:Error(String(z))))}}),J.readLine!==void 0)J.readLine().then((V)=>{let U=iq0(V);if(U===null){K(()=>G(Error("OAuth callback missing authorization code")));return}try{let H=yu(U,X);K(()=>Q(H))}catch(H){K(()=>G(H instanceof Error?H:Error(String(H))))}}).catch(()=>{return});if(J.openBrowser!==void 0)J.openBrowser(Z).catch((V)=>{K(()=>G(V))})})}function iq0($){let Z=$.replaceAll("\r","").replaceAll(`
665
+ `;R$.appendFileSync(X,G)}catch{}}function FA(){let $=Su.homedir(),Z=process.env.XDG_DATA_HOME;if(Z)return O7.join(Z,"opencode","auth.json");if(process.platform!=="win32")return O7.join($,".local","share","opencode","auth.json");return O7.join($,".opencode","auth.json")}async function fu($,Z,J,Y){let X=FA(),Q=O7.dirname(X);if(!R$.existsSync(Q))R$.mkdirSync(Q,{recursive:!0});let G={};if(R$.existsSync(X)){let W=R$.readFileSync(X,"utf-8");G=JSON.parse(W)}G.gitlab={type:"oauth",access:$,refresh:Z,expires:J,enterpriseUrl:Y},R$.writeFileSync(X,JSON.stringify(G,null,2)),R$.chmodSync(X,384)}async function mq0($,Z){let J=FA(),Y=O7.dirname(J);if(!R$.existsSync(Y))R$.mkdirSync(Y,{recursive:!0});let X={};if(R$.existsSync(J)){let Q=R$.readFileSync(J,"utf-8");X=JSON.parse(Q)}X.gitlab={type:"api",key:$,enterpriseUrl:Z},R$.writeFileSync(J,JSON.stringify(X,null,2)),R$.chmodSync(J,384)}var oQ=null;async function lq0($,Z,J){let Y=Date.now(),X=300000;if(!($.expires<=Y+300000))return Y$("Token is still valid",{expiresAt:new Date($.expires).toISOString(),expiresIn:Math.round(($.expires-Y)/1000/60)+" minutes"}),{apiKey:$.access,instanceUrl:$.enterpriseUrl||J};if(oQ){Y$("Token refresh already in progress, waiting..."),await oQ;let W=await Z();if(W&&W.type==="oauth")return{apiKey:W.access,instanceUrl:W.enterpriseUrl||J};throw Error("Failed to get refreshed auth data")}Y$("Token expired or expiring soon, refreshing...",{expiresAt:new Date($.expires).toISOString(),expired:$.expires<=Y}),oQ=(async()=>{try{let W=$.enterpriseUrl||J,K=new UK({instanceUrl:W,clientId:sQ,scopes:zA,method:"auto"});Y$("Calling exchangeRefreshToken...");let V=await K.exchangeRefreshToken($.refresh),U=Date.now()+V.expires_in*1000;Y$("Token refresh successful",{newExpiresAt:new Date(U).toISOString(),expiresIn:Math.round(V.expires_in/60)+" minutes"}),await fu(V.access_token,V.refresh_token,U,W),Y$("New tokens saved successfully")}catch(W){if(Y$("Token refresh failed",{error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0}),W instanceof Error&&W.message.includes("401")){Y$("Refresh token appears to be revoked (401), clearing auth data");let K=FA();if(R$.existsSync(K)){let V=R$.readFileSync(K,"utf-8"),U=JSON.parse(V);delete U.gitlab,R$.writeFileSync(K,JSON.stringify(U,null,2))}}throw W}})();try{await oQ}finally{oQ=null}let G=await Z();if(G&&G.type==="oauth")return{apiKey:G.access,instanceUrl:G.enterpriseUrl||J};throw Error("Failed to get refreshed auth data after token refresh")}var ku=async($)=>{return{auth:{provider:"gitlab",async loader(J){let Y=await J();if(!Y)return{};if(Y.type==="oauth")try{return{...await lq0(Y,J,nQ()),clientId:sQ}}catch(X){return Y$("Failed to refresh token in loader",{error:X instanceof Error?X.message:String(X)}),{apiKey:Y.access,instanceUrl:Y.enterpriseUrl||nQ(),clientId:sQ}}if(Y.type==="api"){let X=Y.enterpriseUrl||nQ();return{apiKey:Y.key,instanceUrl:X}}return{}},methods:[{type:"oauth",label:"GitLab OAuth",prompts:[],async authorize(){let J=nQ(),Y;try{let N=new URL(J);Y=`${N.protocol}//${N.host}`}catch{throw Error(`Invalid GitLab instance URL: ${J}`)}let{generateSecret:X,generateCodeChallengeFromVerifier:Q}=await import("./chunk-qk5bfcv8.js"),G=X(43),W=Q(G),K=X(32),V=new iQ({port:8080,host:"127.0.0.1",timeout:120000});await V.start();let U=V.getCallbackUrl(),H=V.waitForCallback(),B=new URLSearchParams({client_id:sQ,redirect_uri:U,response_type:"code",state:K,scope:zA.join(" "),code_challenge:W,code_challenge_method:"S256"}),z=`${Y}/oauth/authorize?${B.toString()}`,{exec:F}=await import("child_process"),A=process.platform;return F(`${A==="darwin"?"open":A==="win32"?"start":"xdg-open"} "${z}"`),{method:"auto",url:z,instructions:"Your browser will open for authentication. The callback will be handled automatically.",async callback(){Y$("callback() called");try{Y$("Waiting for callback...");let N=await H;if(Y$("Received callback",{hasCode:!!N.code,hasState:!!N.state}),N.state!==K)return Y$("State mismatch",{expected:K,received:N.state}),await V.close(),{type:"failed"};Y$("State verified"),Y$("Exchanging code for tokens...");let q=await new UK({instanceUrl:Y,clientId:sQ,scopes:zA,method:"auto"}).exchangeAuthorizationCode(N.code,G,U);Y$("Token exchange successful"),await V.close();let M=Date.now()+q.expires_in*1000;return Y$("Tokens received",{expiresAt:new Date(M).toISOString()}),Y$("Saving auth data..."),await fu(q.access_token,q.refresh_token,M,Y),Y$("Auth data saved successfully"),{type:"success",provider:Y,access:q.access_token,refresh:q.refresh_token,expires:M}}catch(N){Y$("Error in callback",{error:N instanceof Error?N.message:String(N),stack:N instanceof Error?N.stack:void 0});try{await V.close()}catch(L){}return{type:"failed"}}}}}},{type:"api",label:"GitLab Personal Access Token",prompts:[{type:"text",key:"token",message:"Personal Access Token",placeholder:"glpat-xxxxxxxxxxxxxxxxxxxx",validate:(J)=>{if(!J)return"Token is required";if(!J.startsWith("glpat-"))return"Token should start with glpat-";return}}],async authorize(J){let Y=nQ(),X=J?.token;if(!X)return{type:"failed"};let Q;try{let G=new URL(Y);Q=`${G.protocol}//${G.host}`}catch{return{type:"failed"}}try{if(!(await fetch(`${Q}/api/v4/user`,{headers:{Authorization:`Bearer ${X}`}})).ok)return{type:"failed"};return Y$("Saving PAT auth data..."),await mq0(X,Q),Y$("PAT auth data saved successfully"),{type:"success",key:X,provider:Q}}catch{return{type:"failed"}}}}]}}};import dq0 from"http";function vu($){if($===null||$.length===0)return null;try{let Z=Buffer.from($,"base64url").toString("utf8"),J=JSON.parse(Z);if(J.v!==1||typeof J.n!=="string"||J.n.length===0||typeof J.i!=="string"||J.i.length===0||typeof J.r!=="boolean")return null;return{issuer:J.i,requireIssuer:J.r}}catch{return null}}async function xu($={}){let Z=$.callbackPath??"/callback",J=$.createServer?$.createServer():dq0.createServer();return{redirectUri:`http://127.0.0.1:${await pq0(J)}${Z}`,async waitForCode(Q){return cq0(J,Q,$,Z)},close(){J.closeAllConnections?.(),J.close()}}}async function pq0($){return new Promise((Z)=>{$.listen(0,"127.0.0.1",()=>{let J=$.address();Z(J.port)})})}function cq0($,Z,J,Y){let X=nq0(Z);return new Promise((Q,G)=>{let W=!1,K=(V)=>{if(!W)W=!0,V()};if($.on("request",(V,U)=>{let H=new URL(V.url??"/","http://127.0.0.1");if(H.pathname!==Y){U.writeHead(404),U.end("Not found");return}let B=H.searchParams.get("error");if(B!==null){let z=H.searchParams.get("error_description")??B;U.writeHead(400),U.end(`Authorization failed: ${z}`),K(()=>G(Error(`OAuth authorization failed: ${B} \u2014 ${z}`)));return}try{let z=yu({code:H.searchParams.get("code"),state:H.searchParams.get("state"),iss:H.searchParams.get("iss")},X);U.writeHead(200,{"Content-Type":"text/html"}),U.end(oq0(J.landingPage)),K(()=>Q(z))}catch(z){U.writeHead(400),U.end(z instanceof Error?z.message:"Invalid OAuth callback"),K(()=>G(z instanceof Error?z:Error(String(z))))}}),J.readLine!==void 0)J.readLine().then((V)=>{let U=iq0(V);if(U===null){K(()=>G(Error("OAuth callback missing authorization code")));return}try{let H=yu(U,X);K(()=>Q(H))}catch(H){K(()=>G(H instanceof Error?H:Error(String(H))))}}).catch(()=>{return});if(J.openBrowser!==void 0)J.openBrowser(Z).catch((V)=>{K(()=>G(V))})})}function iq0($){let Z=$.replaceAll("\r","").replaceAll(`
666
666
  `,"").trim();if(Z.length===0)return null;try{let J=new URL(Z);return{code:J.searchParams.get("code"),state:J.searchParams.get("state"),iss:J.searchParams.get("iss")}}catch{return{code:Z,state:null,iss:null}}}function nq0($){let J=new URL($).searchParams.get("state"),Y=vu(J);return{state:J,issuer:Y?.issuer??null,requireIssuer:Y?.requireIssuer??!1}}function yu($,Z){if($.code===null||$.code.length===0)throw Error("OAuth callback missing authorization code");if(Z.state!==null){if($.state===null||$.state.length===0)throw Error("OAuth callback missing state");if($.state!==Z.state)throw Error("OAuth callback state mismatch")}if(Z.requireIssuer){if($.iss===null||$.iss.length===0)throw Error("OAuth callback missing issuer")}if($.iss!==null&&$.iss.length>0&&Z.issuer!==null&&$.iss!==Z.issuer)throw Error("OAuth callback issuer mismatch");return $.code}function AA($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function oq0($){let Z=$?.title??"Connected",J=$?.body??"You can close this tab and return to your terminal.";return["<!DOCTYPE html>",`<html><head><meta charset=utf-8><title>${AA(Z)}</title></head>`,'<body style="font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0">','<div style="text-align:center">',`<h1>${AA(Z)}</h1>`,`<p style="color:#666">${AA(J)}</p>`,"</div></body></html>"].join("")}import hu from"crypto";function gu(){return hu.randomBytes(32).toString("base64url")}function uu($){return hu.createHash("sha256").update($).digest("base64url")}var sq0="https://poe.com/oauth/authorize",rq0="https://api.poe.com/token";function OA($){let Z=$.fetch??globalThis.fetch;return{authorize:()=>tq0($,Z)}}function aq0(){return gu()}async function tq0($,Z){let J=$.authorizationEndpoint??sq0,Y=$.tokenEndpoint??rq0,X=aq0(),Q=uu(X),G=await xu({openBrowser:$.openBrowser,readLine:$.readLine,createServer:$.createServer,landingPage:$.landingPage??{title:"Connected to Poe",body:"You can close this tab and return to your terminal."}}),W=G.redirectUri,K=eq0({endpoint:J,clientId:$.clientId,redirectUri:W,codeChallenge:Q});return{authorizationUrl:K,waitForResult:async()=>{try{let U=await G.waitForCode(K);return await $j0({tokenEndpoint:Y,code:U,codeVerifier:X,clientId:$.clientId,redirectUri:W,fetchFn:Z})}finally{G.close()}}}}function eq0($){let Z=new URL($.endpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",$.clientId),Z.searchParams.set("scope","apikey:create"),Z.searchParams.set("code_challenge",$.codeChallenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.redirectUri),Z.toString()}async function $j0($){let Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,code_verifier:$.codeVerifier,client_id:$.clientId,redirect_uri:$.redirectUri}),J=await $.fetchFn($.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z.toString()});if(!J.ok){let X=await J.text(),Q=Zj0(X);throw Error(Q??`Token exchange failed (${J.status}): ${X}`)}let Y=await J.json();if(typeof Y.api_key!=="string"||Y.api_key.length===0)throw Error("Token response missing api_key field");return{apiKey:Y.api_key,expiresIn:typeof Y.api_key_expires_in==="number"?Y.api_key_expires_in:null}}function Zj0($){try{let Z=JSON.parse($);if(typeof Z.error_description==="string")return Z.error_description;if(typeof Z.error==="string")return Z.error}catch{}return null}var Jj0="client_728290227fc048cc9262091a1ea197ea";function Yj0($){if($==null)return Number.MAX_SAFE_INTEGER;return Date.now()+$*1000}async function Xj0(){let Z=await OA({clientId:Jj0,landingPage:{title:"Connected to Poe",body:"You can close this tab and return to OpenCode."},openBrowser:async(J)=>{await mu(J)}}).authorize();return{url:Z.authorizationUrl,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{let J=await Z.waitForResult();return{type:"success",access:J.apiKey,refresh:J.apiKey,expires:Yj0(J.expiresIn)}}}}async function HK($){return{auth:{provider:"poe",async loader(Z){let J=await Z();if(J.type==="api")return{apiKey:J.key};if(J.type!=="oauth")return{};if(J.expires<Date.now())throw Error("Poe API key expired. Run `opencode providers login` again.");return{apiKey:J.access}},methods:[{label:"Login with Poe (browser)",type:"oauth",authorize:Xj0},{label:"Manually enter API Key",type:"api"}]}}}async function lu($){return{auth:{provider:"cloudflare-workers-ai",methods:[{type:"api",label:"API key",prompts:!process.env.CLOUDFLARE_ACCOUNT_ID?[{type:"text",key:"accountId",message:"Enter your Cloudflare Account ID",placeholder:"e.g. 1234567890abcdef1234567890abcdef"}]:[]}]}}}async function du($){return{auth:{provider:"cloudflare-ai-gateway",methods:[{type:"api",label:"Gateway API token",prompts:[...!process.env.CLOUDFLARE_ACCOUNT_ID?[{type:"text",key:"accountId",message:"Enter your Cloudflare Account ID",placeholder:"e.g. 1234567890abcdef1234567890abcdef"}]:[],...!process.env.CLOUDFLARE_GATEWAY_ID?[{type:"text",key:"gatewayId",message:"Enter your Cloudflare AI Gateway ID",placeholder:"e.g. my-gateway"}]:[]]}]},"chat.params":async(J,Y)=>{if(J.model.providerID!=="cloudflare-ai-gateway")return;if(!J.model.api.id.toLowerCase().startsWith("openai/"))return;if(!J.model.capabilities.reasoning)return;Y.maxOutputTokens=void 0}}}import FZ from"path";import Qj0 from"fs/promises";function BK($){return FZ.join(F0.Path.data,"memory","sessions",$)}function rQ($){return FZ.join(BK($),"checkpoint.md")}function aQ($){return FZ.join(F0.Path.data,"memory","projects",$,"MEMORY.md")}function dh0(){return FZ.join(F0.Path.data,"memory","global","MEMORY.md")}async function ph0($){let Z=aQ($),J=FZ.join(FZ.dirname(Z),"memory.md");if(await Bun.file(Z).exists())return;if(await Bun.file(J).exists())await Qj0.rename(J,Z).catch((Y)=>{if(Y.code!=="ENOENT")throw Y})}function ch0($){return FZ.join(BK($),"notes.md")}function Gj0($){return FZ.join(BK($),"tasks")}function pu($,Z){return FZ.join(Gj0($),Z,"progress.md")}var cu=80,Wj0=["### Execution context","### Live resources","### Session metadata"],Kj0=["### Discovered","### Dead ends"];function iu($,Z,J){let Y=[],X=$.split(`
667
667
  `).find((K)=>K.trim().length>0)??"";if(/^# Checkpoint #\d+/.test(X))Y.push({file:Z,rule:"topic-anti-pattern-checkpoint-header",severity:"error",detail:`First line is "${X}". Replace with "Topic: <\u226480-char one-line summary>" with NO leading "#".`});let Q=$.match(/^Topic:\s*(.+?)$/m);if(!Q)Y.push({file:Z,rule:"topic-missing",severity:"error",detail:'Missing required first-line "Topic: <summary>". Add it as the first non-blank line.'});else{let K=Q[1].trim();if(K.length>cu)Y.push({file:Z,rule:"topic-too-long",severity:"warn",detail:`Topic line is ${K.length} chars (limit ${cu}). Rewrite shorter.`})}let G=J.map((K)=>({section:K,idx:$.indexOf(K)}));for(let K of G)if(K.idx===-1)Y.push({file:Z,rule:"subsection-missing",severity:"error",detail:`Missing "${K.section}" sub-section. Add the header (use "(none)" placeholder if no entries).`});let W=G.filter((K)=>K.idx!==-1);for(let K=1;K<W.length;K++)if(W[K].idx<W[K-1].idx){Y.push({file:Z,rule:"subsection-out-of-order",severity:"error",detail:`Sub-sections must appear in order: ${J.join(", ")}.`});break}return Y}function nu($,Z){return iu($,Z,Wj0)}function ou($){let Z=$.match(/^(?:Topic:.*\n+)?### discovered\s*\n([\s\S]*?)(?=\n### |$)/i);if(!Z)return[];let J=Z[1],Y=[],X=J.split(`
668
668
  `),Q;for(let G of X){let W=G.match(/^- (.+)$/);if(W){if(Q)Y.push({title:Q.title,block:Q.lines.join(`
@@ -794,15 +794,15 @@ Exact commands you ran or commands the user/task asked to be runnable later. Kee
794
794
  `)}async function kj0($,Z){let Y=`---
795
795
  written-at: ${Date.now()}
796
796
  ---
797
- `,X=Z.match(/^---\n[\s\S]*?\n---\n/),Q=X?Y+Z.slice(X[0].length):Y+Z;await Bun.write($,Q)}async function jm($){return{"actor.postStop":{matcher:{agentType:{excludeOnly:["checkpoint-writer","title","summary","dream","distill","compaction","main"]}},run:async(Z,J)=>{let Y=Z.task_id;if(!Y)return;if(Z.canWrite===!1)return;let X=Z.sessionID,Q=pu(X,Y),G;try{G=await Bun.file(Q).text()}catch{G=void 0}if(G===void 0){J.continue=!0,J.reason=qm({kind:"missing",taskId:Y,filePath:Q});return}let W=fj0.filter((K)=>!G.includes(K));if(W.length>0){J.continue=!0,J.reason=qm({kind:"incomplete",taskId:Y,filePath:Q,missing:W});return}try{await bj0.mkdir(_j0.dirname(Q),{recursive:!0}),await kj0(Q,G)}catch(K){Sj0.error("frontmatter injection failed",{err:K,filePath:Q})}}}}}var IA;((Zu0)=>{function $(Q){let G=s8.pluginSpecifier(Q);return{spec:G,options:s8.pluginOptions(Q),deprecated:Nm(G)}}async function Z(Q,G){let W="";try{W=await wm(Q.spec)}catch(V){return{ok:!1,stage:"install",error:V}}if(!W)return{ok:!1,stage:"install",error:Error(`Plugin ${Q.spec} target is empty`)};let K;try{K=await Lm(Q.spec,W,G)}catch(V){return{ok:!1,stage:"entry",error:V}}if(!K.entry)return{ok:!1,stage:"missing",value:{...Q,source:K.source,target:K.target,pkg:K.pkg,message:`Plugin ${Q.spec} does not expose a ${G} entrypoint`}};if(K.source==="npm")try{await Dm(K.target,E$,K.pkg)}catch(V){return{ok:!1,stage:"compatibility",error:V}}return{ok:!0,value:{...Q,source:K.source,target:K.target,entry:K.entry,pkg:K.pkg}}}Zu0.resolve=Z;async function J(Q){let G;try{G=await import(Q.entry)}catch(W){return{ok:!1,error:W}}if(!G)return{ok:!1,error:Error(`Plugin ${Q.spec} module is empty`)};return{ok:!0,value:{...Q,mod:G}}}Zu0.load=J;async function Y(Q,G,W,K,V,U){let H=Q.plan;if(H.deprecated)return;U?.start?.(Q,W);let B=await Z(H,G);if(!B.ok){if(B.stage==="missing"){if(V){let F=await V(B.value,Q.origin,W);if(F!==void 0)return F}U?.missing?.(Q,W,B.value.message,B.value);return}U?.error?.(Q,W,B.stage,B.error);return}let z=await J(B.value);if(!z.ok){U?.error?.(Q,W,"load",z.error,B.value);return}if(!K)return z.value;return K(z.value,Q.origin,W)}async function X(Q){let G=Q.items.map((U)=>({origin:U,plan:$(U.spec)})),W=[];for(let U of G)W.push(Y(U,Q.kind,!1,Q.finish,Q.missing,Q.report));let K=await Promise.all(W);if(Q.wait){let U;for(let H=0;H<G.length;H++){if(K[H]!==void 0)continue;let B=G[H];if(!B||Mm(B.plan.spec)!=="file")continue;U??=Q.wait(),await U,K[H]=await Y(B,Q.kind,!0,Q.finish,Q.missing,Q.report)}}let V=[];for(let U of K)if(U!==void 0)V.push(U);return V}Zu0.loadExternal=X})(IA||={});var Rm={worktree:Tm(async()=>(await import("./chunk-e999xtfj.js")).WorktreeAdaptor)},OK=new Map;async function Xu0($,Z){let J=OK.get($)?.get(Z);if(J)return J;let Y=Rm[Z];if(Y)return Y();throw Error(`Unknown workspace adaptor: ${Z}`)}async function Qu0($){let Z=await Promise.all(Object.entries(Rm).map(async([Y,X])=>{let Q=await X();return{type:Y,name:Q.name,description:Q.description}})),J=[...OK.get($)?.entries()??[]].map(([Y,X])=>({type:Y,name:X.name,description:X.description}));return[...Z,...J]}function Pm($,Z,J){let Y=OK.get($)??new Map;Y.set(Z,J),OK.set($,Y)}import vj0 from"fs/promises";import J9 from"path";import{pathToFileURL as Im,fileURLToPath as yj0}from"url";var z$=E0.create({service:"plugin"}),EA={Executed:L1.define("hook.executed",D.object({event:D.enum(["actor.preStop","actor.postStop"]),hookID:D.string(),pluginName:D.string(),actorID:D.string(),agentType:D.string(),durationMs:D.number(),outcome:D.enum(["success","error","skipped"]),continueRequested:D.boolean(),reasonLength:D.number()})),ReActReentered:L1.define("hook.react.reentered",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string(),iteration:D.number(),triggeredByPlugins:D.array(D.string()),reasonPreview:D.string()})),ReActMaxReached:L1.define("hook.react.max_reached",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string()}))};class qK extends S1.Service()("@qitqode/Plugin"){}var xj0=[c2,i2,p2,t2,ku,HK,lu,du,Am,jm];function Cm($){return typeof $==="function"}function hj0($){if(Cm($))return $;if(!$||typeof $!=="object"||!("server"in $))return;if(!Cm($.server))return;return $.server}function gj0($){let Z=new Set,J=[];for(let Y of Object.values($)){if(Z.has(Y))continue;Z.add(Y);let X=hj0(Y);if(!X)throw TypeError("Plugin export is not a function");J.push(X)}return J}async function uj0($,Z,J,Y){let X=bm($.mod,$.spec,"server","detect");if(X){await _m($.source,$.spec,$.target,CA(X.id,$.spec),$.pkg);let Q=CA(X.id,$.spec)??$.pkg?.pkg??$.spec,G=await X.server(Z,$.options);J.push(G),Y.push({hook:G,pluginName:Q,hookIDFor:(W)=>`${Q}#${W}`});return}for(let Q of gj0($.mod)){let G=Q.name,W=G&&G!=="default"&&G!==""?G:$.pkg?.pkg??$.spec,K=await Q(Z,$.options);J.push(K),Y.push({hook:K,pluginName:W,hookIDFor:(V)=>`${W}#${V}`})}}var Sm=T0.effect(qK,T.gen(function*(){let $=yield*l1.Service,Z=yield*X8.Service,J=yield*B0.make(T.fn("Plugin.state")(function*(F){let A=[],j=[],N=yield*T7.make();function L(f){N.fork($.publish(Y9.Event.Error,{error:new j1.Unknown({message:f}).toObject()}))}let{Server:q}=yield*T.promise(()=>import("./chunk-c47vp7ne.js")),M=LH({baseUrl:"http://localhost:4096",directory:F.directory,headers:b0.QITQODE_SERVER_PASSWORD?{Authorization:`Basic ${Buffer.from(`${b0.QITQODE_SERVER_USERNAME??"qitqode"}:${b0.QITQODE_SERVER_PASSWORD}`).toString("base64")}`}:void 0,fetch:async(...f)=>(await q.Default()).app.fetch(...f)}),C=yield*Z.get(),R={client:M,project:F.project,worktree:F.worktree,directory:F.directory,experimental_workspace:{register(f,b){Pm(F.project.id,f,b)}},get serverUrl(){return q.url??new URL("http://localhost:4096")},$:typeof Bun>"u"?void 0:Bun.$};for(let f of xj0){z$.info("loading internal plugin",{name:f.name});let b=yield*T.tryPromise({try:()=>f(R),catch:(y)=>{z$.error("failed to load internal plugin",{name:f.name,error:y})}}).pipe(T.option);if(b._tag==="Some")A.push(b.value),j.push({hook:b.value,pluginName:f.name,hookIDFor:(y)=>`${f.name}#${y}`})}let w={},I=yield*T.tryPromise(()=>import("./chunk-bm7xpjh6.js")).pipe(T.option);if(I._tag==="Some")Object.assign(w,I.value.modules??{});else{let f=J9.join(J9.dirname(yj0(import.meta.url)),"..","ext"),y=(yield*T.promise(()=>vj0.readdir(f).catch(()=>[]))).filter((k)=>k.endsWith(".ts")&&!k.endsWith(".d.ts")&&k!=="_manifest.ts");for(let k of y){let g=yield*T.tryPromise({try:()=>import(Im(J9.join(f,k)).href),catch:(d)=>z$.error("failed to import extension",{name:k,error:d})}).pipe(T.option);if(g._tag==="Some")w[k.replace(/\.ts$/,"")]=g.value}}for(let[f,b]of Object.entries(w)){let y=Object.entries(b).find(([g,d])=>typeof d==="function"&&g.endsWith("Plugin"))?.[1];if(!y)continue;z$.info("loading extension",{name:f});let k=yield*T.tryPromise({try:()=>y(R),catch:(g)=>z$.error("failed to load extension",{name:f,error:g})}).pipe(T.option);if(k._tag==="Some")A.push(k.value),j.push({hook:k.value,pluginName:f,hookIDFor:(g)=>`${f}#${g}`})}let _=b0.QITQODE_PURE?[]:C.plugin_origins??[];if(b0.QITQODE_PURE&&C.plugin_origins?.length)z$.info("skipping external plugins in pure mode",{count:C.plugin_origins.length});if(_.length)yield*Z.waitForDependencies();let E=yield*T.promise(()=>IA.loadExternal({items:_,kind:"server",report:{start(f){z$.info("loading plugin",{path:f.plan.spec})},missing(f,b,y){z$.warn("plugin has no server entrypoint",{path:f.plan.spec,message:y})},error(f,b,y,k,g){let d=f.plan.spec,p=k instanceof Error?k.cause??k:k,t=y==="load"?V6(k):V6(p);if(y==="install"){let r=Em(d);z$.error("failed to install plugin",{pkg:r.pkg,version:r.version,error:t}),L(`Failed to install plugin ${r.pkg}@${r.version}: ${t}`);return}if(y==="compatibility"){z$.warn("plugin incompatible",{path:d,error:t}),L(`Plugin ${d} skipped: ${t}`);return}if(y==="entry"){z$.error("failed to resolve plugin server entry",{path:d,error:t}),L(`Failed to load plugin ${d}: ${t}`);return}z$.error("failed to load plugin",{path:d,target:g?.entry,error:t}),L(`Failed to load plugin ${d}: ${t}`)}}}));for(let f of E){if(!f)continue;yield*T.tryPromise({try:()=>uj0(f,R,A,j),catch:(b)=>{let y=V6(b);return z$.error("failed to load plugin",{path:f.spec,error:y}),y}}).pipe(T.catch(()=>{return T.void}))}for(let f of A)yield*T.tryPromise({try:()=>Promise.resolve(f.config?.(C)),catch:(b)=>{z$.error("plugin config hook failed",{error:b})}}).pipe(T.ignore);return yield*$.subscribeAll().pipe(I$.runForEach((f)=>T.sync(()=>{for(let b of A)b.event?.({event:f})})),T.forkScoped),{hooks:A,hooksWithMeta:j}})),Y=yield*B0.make(T.fn("Plugin.fileHooks")(function*(){let F=[],A=[],j=yield*Z.get(),N=yield*Z.directories();for(let L of N){let q=$4.scanSync("{hook,hooks}/*.{js,ts}",{cwd:L,absolute:!0,dot:!0,symlink:!0});for(let M of q){let C=yield*T.tryPromise({try:()=>import(`${Im(M).href}?v=${Date.now()}`),catch:(w)=>w}).pipe(T.catch((w)=>{return z$.error("failed to load file hook",{path:M,error:V6(w)}),T.succeed(void 0)}));if(!C)continue;let R=C.default??C;if(R&&typeof R==="object"){let w=J9.basename(M,J9.extname(M));F.push(R),A.push({hook:R,pluginName:`file:${w}`,hookIDFor:(I)=>`file:${w}#${I}`}),z$.info("loaded file hook",{path:M,name:w})}}}return{hooks:F,meta:A}})),X=(F,A)=>T.gen(function*(){let j=yield*B0.get(J),N=yield*B0.get(Y),L=[],q=[],M=[],C=!1;for(let w of[...j.hooksWithMeta,...N.meta]){let I=w.hook[A];if(!I)continue;let _=typeof I==="function"?I:I.run,E=typeof I==="function"?void 0:I.matcher;if(!U2(E,F)){yield*$.publish(EA.Executed,{event:A,hookID:w.hookIDFor(A),pluginName:w.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:0,outcome:"skipped",continueRequested:!1,reasonLength:0});continue}let f=Date.now(),b={continue:!1},y="success";yield*T.tryPromise({try:()=>_(F,b),catch:(g)=>g}).pipe(T.tapError((g)=>T.gen(function*(){y="error",z$.error(`${A} hook failed`,{pluginName:w.pluginName,hookID:w.hookIDFor(A),error:g}),yield*$.publish(Y9.Event.Error,{sessionID:F.sessionID,error:new j1.Unknown({message:`${A} hook (${w.pluginName}) failed: ${V6(g)}`}).toObject()})})),T.ignore);let k=Date.now()-f;if(yield*$.publish(EA.Executed,{event:A,hookID:w.hookIDFor(A),pluginName:w.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:k,outcome:y,continueRequested:b.continue===!0,reasonLength:b.reason?.length??0}),b.continue===!0&&b.reason&&b.reason.length>0)C=!0,L.push(b.reason),q.push(w.pluginName),M.push(w.hookIDFor(A));else if(b.continue===!0)z$.warn(`${A} hook returned continue=true without reason; ignored`,{pluginName:w.pluginName})}return{continue:C,reason:L.length>0?L.join(`
797
+ `,X=Z.match(/^---\n[\s\S]*?\n---\n/),Q=X?Y+Z.slice(X[0].length):Y+Z;await Bun.write($,Q)}async function jm($){return{"actor.postStop":{matcher:{agentType:{excludeOnly:["checkpoint-writer","title","summary","dream","distill","compaction","main"]}},run:async(Z,J)=>{let Y=Z.task_id;if(!Y)return;if(Z.canWrite===!1)return;let X=Z.sessionID,Q=pu(X,Y),G;try{G=await Bun.file(Q).text()}catch{G=void 0}if(G===void 0){J.continue=!0,J.reason=qm({kind:"missing",taskId:Y,filePath:Q});return}let W=fj0.filter((K)=>!G.includes(K));if(W.length>0){J.continue=!0,J.reason=qm({kind:"incomplete",taskId:Y,filePath:Q,missing:W});return}try{await bj0.mkdir(_j0.dirname(Q),{recursive:!0}),await kj0(Q,G)}catch(K){Sj0.error("frontmatter injection failed",{err:K,filePath:Q})}}}}}var IA;((Zu0)=>{function $(Q){let G=s8.pluginSpecifier(Q);return{spec:G,options:s8.pluginOptions(Q),deprecated:Nm(G)}}async function Z(Q,G){let W="";try{W=await wm(Q.spec)}catch(V){return{ok:!1,stage:"install",error:V}}if(!W)return{ok:!1,stage:"install",error:Error(`Plugin ${Q.spec} target is empty`)};let K;try{K=await Lm(Q.spec,W,G)}catch(V){return{ok:!1,stage:"entry",error:V}}if(!K.entry)return{ok:!1,stage:"missing",value:{...Q,source:K.source,target:K.target,pkg:K.pkg,message:`Plugin ${Q.spec} does not expose a ${G} entrypoint`}};if(K.source==="npm")try{await Dm(K.target,E$,K.pkg)}catch(V){return{ok:!1,stage:"compatibility",error:V}}return{ok:!0,value:{...Q,source:K.source,target:K.target,entry:K.entry,pkg:K.pkg}}}Zu0.resolve=Z;async function J(Q){let G;try{G=await import(Q.entry)}catch(W){return{ok:!1,error:W}}if(!G)return{ok:!1,error:Error(`Plugin ${Q.spec} module is empty`)};return{ok:!0,value:{...Q,mod:G}}}Zu0.load=J;async function Y(Q,G,W,K,V,U){let H=Q.plan;if(H.deprecated)return;U?.start?.(Q,W);let B=await Z(H,G);if(!B.ok){if(B.stage==="missing"){if(V){let F=await V(B.value,Q.origin,W);if(F!==void 0)return F}U?.missing?.(Q,W,B.value.message,B.value);return}U?.error?.(Q,W,B.stage,B.error);return}let z=await J(B.value);if(!z.ok){U?.error?.(Q,W,"load",z.error,B.value);return}if(!K)return z.value;return K(z.value,Q.origin,W)}async function X(Q){let G=Q.items.map((U)=>({origin:U,plan:$(U.spec)})),W=[];for(let U of G)W.push(Y(U,Q.kind,!1,Q.finish,Q.missing,Q.report));let K=await Promise.all(W);if(Q.wait){let U;for(let H=0;H<G.length;H++){if(K[H]!==void 0)continue;let B=G[H];if(!B||Mm(B.plan.spec)!=="file")continue;U??=Q.wait(),await U,K[H]=await Y(B,Q.kind,!0,Q.finish,Q.missing,Q.report)}}let V=[];for(let U of K)if(U!==void 0)V.push(U);return V}Zu0.loadExternal=X})(IA||={});var Rm={worktree:Tm(async()=>(await import("./chunk-hz3h6e19.js")).WorktreeAdaptor)},OK=new Map;async function Xu0($,Z){let J=OK.get($)?.get(Z);if(J)return J;let Y=Rm[Z];if(Y)return Y();throw Error(`Unknown workspace adaptor: ${Z}`)}async function Qu0($){let Z=await Promise.all(Object.entries(Rm).map(async([Y,X])=>{let Q=await X();return{type:Y,name:Q.name,description:Q.description}})),J=[...OK.get($)?.entries()??[]].map(([Y,X])=>({type:Y,name:X.name,description:X.description}));return[...Z,...J]}function Pm($,Z,J){let Y=OK.get($)??new Map;Y.set(Z,J),OK.set($,Y)}import vj0 from"fs/promises";import J9 from"path";import{pathToFileURL as Im,fileURLToPath as yj0}from"url";var z$=E0.create({service:"plugin"}),EA={Executed:L1.define("hook.executed",D.object({event:D.enum(["actor.preStop","actor.postStop"]),hookID:D.string(),pluginName:D.string(),actorID:D.string(),agentType:D.string(),durationMs:D.number(),outcome:D.enum(["success","error","skipped"]),continueRequested:D.boolean(),reasonLength:D.number()})),ReActReentered:L1.define("hook.react.reentered",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string(),iteration:D.number(),triggeredByPlugins:D.array(D.string()),reasonPreview:D.string()})),ReActMaxReached:L1.define("hook.react.max_reached",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string()}))};class qK extends S1.Service()("@qitqode/Plugin"){}var xj0=[c2,i2,p2,t2,ku,HK,lu,du,Am,jm];function Cm($){return typeof $==="function"}function hj0($){if(Cm($))return $;if(!$||typeof $!=="object"||!("server"in $))return;if(!Cm($.server))return;return $.server}function gj0($){let Z=new Set,J=[];for(let Y of Object.values($)){if(Z.has(Y))continue;Z.add(Y);let X=hj0(Y);if(!X)throw TypeError("Plugin export is not a function");J.push(X)}return J}async function uj0($,Z,J,Y){let X=bm($.mod,$.spec,"server","detect");if(X){await _m($.source,$.spec,$.target,CA(X.id,$.spec),$.pkg);let Q=CA(X.id,$.spec)??$.pkg?.pkg??$.spec,G=await X.server(Z,$.options);J.push(G),Y.push({hook:G,pluginName:Q,hookIDFor:(W)=>`${Q}#${W}`});return}for(let Q of gj0($.mod)){let G=Q.name,W=G&&G!=="default"&&G!==""?G:$.pkg?.pkg??$.spec,K=await Q(Z,$.options);J.push(K),Y.push({hook:K,pluginName:W,hookIDFor:(V)=>`${W}#${V}`})}}var Sm=T0.effect(qK,T.gen(function*(){let $=yield*l1.Service,Z=yield*X8.Service,J=yield*B0.make(T.fn("Plugin.state")(function*(F){let A=[],j=[],N=yield*T7.make();function L(f){N.fork($.publish(Y9.Event.Error,{error:new j1.Unknown({message:f}).toObject()}))}let{Server:q}=yield*T.promise(()=>import("./chunk-b034nf8g.js")),M=LH({baseUrl:"http://localhost:4096",directory:F.directory,headers:b0.QITQODE_SERVER_PASSWORD?{Authorization:`Basic ${Buffer.from(`${b0.QITQODE_SERVER_USERNAME??"qitqode"}:${b0.QITQODE_SERVER_PASSWORD}`).toString("base64")}`}:void 0,fetch:async(...f)=>(await q.Default()).app.fetch(...f)}),C=yield*Z.get(),R={client:M,project:F.project,worktree:F.worktree,directory:F.directory,experimental_workspace:{register(f,b){Pm(F.project.id,f,b)}},get serverUrl(){return q.url??new URL("http://localhost:4096")},$:typeof Bun>"u"?void 0:Bun.$};for(let f of xj0){z$.info("loading internal plugin",{name:f.name});let b=yield*T.tryPromise({try:()=>f(R),catch:(y)=>{z$.error("failed to load internal plugin",{name:f.name,error:y})}}).pipe(T.option);if(b._tag==="Some")A.push(b.value),j.push({hook:b.value,pluginName:f.name,hookIDFor:(y)=>`${f.name}#${y}`})}let w={},I=yield*T.tryPromise(()=>import("./chunk-wbw9zv3h.js")).pipe(T.option);if(I._tag==="Some")Object.assign(w,I.value.modules??{});else{let f=J9.join(J9.dirname(yj0(import.meta.url)),"..","ext"),y=(yield*T.promise(()=>vj0.readdir(f).catch(()=>[]))).filter((k)=>k.endsWith(".ts")&&!k.endsWith(".d.ts")&&k!=="_manifest.ts");for(let k of y){let g=yield*T.tryPromise({try:()=>import(Im(J9.join(f,k)).href),catch:(d)=>z$.error("failed to import extension",{name:k,error:d})}).pipe(T.option);if(g._tag==="Some")w[k.replace(/\.ts$/,"")]=g.value}}for(let[f,b]of Object.entries(w)){let y=Object.entries(b).find(([g,d])=>typeof d==="function"&&g.endsWith("Plugin"))?.[1];if(!y)continue;z$.info("loading extension",{name:f});let k=yield*T.tryPromise({try:()=>y(R),catch:(g)=>z$.error("failed to load extension",{name:f,error:g})}).pipe(T.option);if(k._tag==="Some")A.push(k.value),j.push({hook:k.value,pluginName:f,hookIDFor:(g)=>`${f}#${g}`})}let _=b0.QITQODE_PURE?[]:C.plugin_origins??[];if(b0.QITQODE_PURE&&C.plugin_origins?.length)z$.info("skipping external plugins in pure mode",{count:C.plugin_origins.length});if(_.length)yield*Z.waitForDependencies();let E=yield*T.promise(()=>IA.loadExternal({items:_,kind:"server",report:{start(f){z$.info("loading plugin",{path:f.plan.spec})},missing(f,b,y){z$.warn("plugin has no server entrypoint",{path:f.plan.spec,message:y})},error(f,b,y,k,g){let d=f.plan.spec,p=k instanceof Error?k.cause??k:k,t=y==="load"?V6(k):V6(p);if(y==="install"){let r=Em(d);z$.error("failed to install plugin",{pkg:r.pkg,version:r.version,error:t}),L(`Failed to install plugin ${r.pkg}@${r.version}: ${t}`);return}if(y==="compatibility"){z$.warn("plugin incompatible",{path:d,error:t}),L(`Plugin ${d} skipped: ${t}`);return}if(y==="entry"){z$.error("failed to resolve plugin server entry",{path:d,error:t}),L(`Failed to load plugin ${d}: ${t}`);return}z$.error("failed to load plugin",{path:d,target:g?.entry,error:t}),L(`Failed to load plugin ${d}: ${t}`)}}}));for(let f of E){if(!f)continue;yield*T.tryPromise({try:()=>uj0(f,R,A,j),catch:(b)=>{let y=V6(b);return z$.error("failed to load plugin",{path:f.spec,error:y}),y}}).pipe(T.catch(()=>{return T.void}))}for(let f of A)yield*T.tryPromise({try:()=>Promise.resolve(f.config?.(C)),catch:(b)=>{z$.error("plugin config hook failed",{error:b})}}).pipe(T.ignore);return yield*$.subscribeAll().pipe(I$.runForEach((f)=>T.sync(()=>{for(let b of A)b.event?.({event:f})})),T.forkScoped),{hooks:A,hooksWithMeta:j}})),Y=yield*B0.make(T.fn("Plugin.fileHooks")(function*(){let F=[],A=[],j=yield*Z.get(),N=yield*Z.directories();for(let L of N){let q=$4.scanSync("{hook,hooks}/*.{js,ts}",{cwd:L,absolute:!0,dot:!0,symlink:!0});for(let M of q){let C=yield*T.tryPromise({try:()=>import(`${Im(M).href}?v=${Date.now()}`),catch:(w)=>w}).pipe(T.catch((w)=>{return z$.error("failed to load file hook",{path:M,error:V6(w)}),T.succeed(void 0)}));if(!C)continue;let R=C.default??C;if(R&&typeof R==="object"){let w=J9.basename(M,J9.extname(M));F.push(R),A.push({hook:R,pluginName:`file:${w}`,hookIDFor:(I)=>`file:${w}#${I}`}),z$.info("loaded file hook",{path:M,name:w})}}}return{hooks:F,meta:A}})),X=(F,A)=>T.gen(function*(){let j=yield*B0.get(J),N=yield*B0.get(Y),L=[],q=[],M=[],C=!1;for(let w of[...j.hooksWithMeta,...N.meta]){let I=w.hook[A];if(!I)continue;let _=typeof I==="function"?I:I.run,E=typeof I==="function"?void 0:I.matcher;if(!U2(E,F)){yield*$.publish(EA.Executed,{event:A,hookID:w.hookIDFor(A),pluginName:w.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:0,outcome:"skipped",continueRequested:!1,reasonLength:0});continue}let f=Date.now(),b={continue:!1},y="success";yield*T.tryPromise({try:()=>_(F,b),catch:(g)=>g}).pipe(T.tapError((g)=>T.gen(function*(){y="error",z$.error(`${A} hook failed`,{pluginName:w.pluginName,hookID:w.hookIDFor(A),error:g}),yield*$.publish(Y9.Event.Error,{sessionID:F.sessionID,error:new j1.Unknown({message:`${A} hook (${w.pluginName}) failed: ${V6(g)}`}).toObject()})})),T.ignore);let k=Date.now()-f;if(yield*$.publish(EA.Executed,{event:A,hookID:w.hookIDFor(A),pluginName:w.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:k,outcome:y,continueRequested:b.continue===!0,reasonLength:b.reason?.length??0}),b.continue===!0&&b.reason&&b.reason.length>0)C=!0,L.push(b.reason),q.push(w.pluginName),M.push(w.hookIDFor(A));else if(b.continue===!0)z$.warn(`${A} hook returned continue=true without reason; ignored`,{pluginName:w.pluginName})}return{continue:C,reason:L.length>0?L.join(`
798
798
 
799
799
  `):void 0,contributingPluginNames:q,contributingHookIDs:M}}),Q=T.fn("Plugin.triggerActorPreStop")(function*(F){return yield*X(F,"actor.preStop")}),G=T.fn("Plugin.triggerActorPostStop")(function*(F){return yield*X(F,"actor.postStop")}),W=5000,K=3,V=new Map,U=T.fn("Plugin.trigger")(function*(F,A,j){if(!F)return j;let N=yield*B0.get(J),L=yield*B0.get(Y);for(let q of N.hooksWithMeta){let M=q.hook[F];if(!M)continue;yield*T.promise(async()=>M(A,j))}for(let q of L.meta){let M=q.hook[F];if(!M)continue;let C=q.hookIDFor(F);if((V.get(C)??0)>=3){z$.warn("hook circuit-breaker open, skipping",{hook:C});continue}let R=structuredClone(j);if(!(yield*T.tryPromise({try:async()=>{await Promise.race([Promise.resolve(M(A,j)),new Promise((I,_)=>setTimeout(()=>_(Error("hook timed out after 5000ms")),5000))])},catch:(I)=>I}).pipe(T.map(()=>!1),T.catch((I)=>{Object.assign(j,R);let _=(V.get(C)??0)+1;return V.set(C,_),z$.error("file hook failed, output rolled back",{hook:C,event:F,error:V6(I),consecutiveFailures:_,circuitOpen:_>=3}),T.succeed(!0)}))))V.delete(C)}return j}),H=T.fn("Plugin.list")(function*(){return(yield*B0.get(J)).hooks}),B=T.fn("Plugin.init")(function*(){yield*B0.get(J),yield*B0.get(Y)}),z=T.fn("Plugin.reloadFileHooks")(function*(){yield*B0.invalidate(Y)});return qK.of({trigger:U,list:H,init:B,reloadFileHooks:z,triggerActorPreStop:Q,triggerActorPostStop:G})})),mj0=Sm.pipe(T0.provide(l1.layer),T0.provide(X8.defaultLayer));import UN0 from"path";var RK=m6(km(),1);var X9={};F1(X9,{variants:()=>G5,topP:()=>am,topK:()=>tm,temperature:()=>rm,smallOptions:()=>$l,schema:()=>Xl,providerOptions:()=>Zl,options:()=>em,message:()=>hm,maxOutputTokens:()=>Jl,OUTPUT_TOKEN_MAX:()=>MK});var ym=32000;function lj0($){if($.startsWith("image/"))return"image";if($.startsWith("audio/"))return"audio";if($.startsWith("video/"))return"video";if($==="application/pdf")return"pdf";return}function dj0($){let Z=$.id.toLowerCase(),J=$.api.id.toLowerCase();if(Z.includes("claude")||J.includes("claude")||$.providerID==="anthropic")return!0;if(Z.includes("gpt")||J.includes("gpt"))return!0;return $.capabilities.input.image}function NK($){switch($){case"@ai-sdk/github-copilot":return"copilot";case"@ai-sdk/azure":return"azure";case"@ai-sdk/openai":return"openai";case"@ai-sdk/amazon-bedrock":return"bedrock";case"@ai-sdk/anthropic":case"@ai-sdk/google-vertex/anthropic":return"anthropic";case"@ai-sdk/google-vertex":return"vertex";case"@ai-sdk/google":return"google";case"@ai-sdk/gateway":return"gateway";case"@openrouter/ai-sdk-provider":return"openrouter"}return}function pj0($,Z,J){if(Z.api.npm==="@ai-sdk/anthropic"||Z.api.npm==="@ai-sdk/amazon-bedrock")$=$.map((Y)=>{if(typeof Y.content==="string"){if(Y.content==="")return;return Y}if(!Array.isArray(Y.content))return Y;let X=Y.content.filter((Q)=>{if(Q.type==="text"||Q.type==="reasoning")return Q.text!=="";return!0});if(X.length===0)return;return{...Y,content:X}}).filter((Y)=>Y!==void 0&&Y.content!=="");if(Z.api.id.includes("claude")){let Y=(X)=>X.replace(/[^a-zA-Z0-9_-]/g,"_");$=$.map((X)=>{if(X.role==="assistant"&&Array.isArray(X.content))return{...X,content:X.content.map((Q)=>{if(Q.type==="tool-call"||Q.type==="tool-result")return{...Q,toolCallId:Y(Q.toolCallId)};return Q})};if(X.role==="tool"&&Array.isArray(X.content))return{...X,content:X.content.map((Q)=>{if(Q.type==="tool-result")return{...Q,toolCallId:Y(Q.toolCallId)};return Q})};return X})}if(["@ai-sdk/anthropic","@ai-sdk/google-vertex/anthropic"].includes(Z.api.npm))$=$.flatMap((Y)=>{if(Y.role!=="assistant"||!Array.isArray(Y.content))return[Y];let X=Y.content,Q=X.findIndex((G)=>G.type==="tool-call");if(Q===-1)return[Y];if(!X.slice(Q).some((G)=>G.type!=="tool-call"))return[Y];return[{...Y,content:X.filter((G)=>G.type!=="tool-call")},{...Y,content:X.filter((G)=>G.type==="tool-call")}]});if(Z.providerID==="mistral"||Z.api.id.toLowerCase().includes("mistral")||Z.api.id.toLowerCase().includes("devstral")){let Y=(Q)=>{return Q.replace(/[^a-zA-Z0-9]/g,"").substring(0,9).padEnd(9,"0")},X=[];for(let Q=0;Q<$.length;Q++){let G=$[Q],W=$[Q+1];if(G.role==="assistant"&&Array.isArray(G.content))X.push({...G,content:G.content.map((K)=>{if(K.type==="tool-call"||K.type==="tool-result")return{...K,toolCallId:Y(K.toolCallId)};return K})});else if(G.role==="tool"&&Array.isArray(G.content))X.push({...G,content:G.content.map((K)=>{if(K.type==="tool-result")return{...K,toolCallId:Y(K.toolCallId)};return K})});else X.push(G);if(G.role==="tool"&&W?.role==="user")X.push({role:"assistant",content:[{type:"text",text:"Done."}]})}return X}if(typeof Z.capabilities.interleaved==="object"&&Z.capabilities.interleaved.field){let Y=Z.capabilities.interleaved.field;return $.map((X)=>{if(X.role==="assistant"&&Array.isArray(X.content)){let G=X.content.filter((K)=>K.type==="reasoning").map((K)=>K.text).join(""),W=X.content.filter((K)=>K.type!=="reasoning");if(G)return{...X,content:W,providerOptions:{...X.providerOptions,openaiCompatible:{...X.providerOptions?.openaiCompatible,[Y]:G}}};return{...X,content:W}}return X})}return $}function cj0($){if($.api.npm==="@ai-sdk/anthropic"||$.api.npm==="@ai-sdk/google-vertex/anthropic")return!0;if($.providerID==="anthropic"||$.providerID==="google-vertex-anthropic")return!0;if($.api.npm==="@ai-sdk/amazon-bedrock")return!0;if($.api.npm==="@openrouter/ai-sdk-provider"||$.api.npm==="@ai-sdk/github-copilot"||$.api.npm==="@ai-sdk/alibaba")return $.api.id.includes("claude")||$.api.id.includes("anthropic")||$.id.includes("claude")||$.id.includes("anthropic");return!1}function ij0($,Z){let J=Z.cachePromptTTL==="1h"?{ttl:"1h"}:{},Y={anthropic:{cacheControl:{type:"ephemeral",...J}},openrouter:{cacheControl:{type:"ephemeral",...J}},bedrock:{cachePoint:{type:"default"}},openaiCompatible:{cache_control:{type:"ephemeral"}},copilot:{copilot_cache_control:{type:"ephemeral"}},alibaba:{cacheControl:{type:"ephemeral"}}},X=[],Q=$.filter((K)=>K.role==="system");if(Q.length>0)X.push(Q[Q.length-1]);let G=$.filter((K)=>K.role!=="system"),W=G.findLastIndex((K)=>K.role==="user");if(W>=1){X.push(G[W-1]);let K=Math.floor(W/2);if(K>0&&K<W-1)X.push(G[K])}else if(W===0)X.push(G[0]);for(let K of vm(X)){if(!(Z.providerID==="anthropic"||Z.providerID.includes("bedrock")||Z.api.npm==="@ai-sdk/amazon-bedrock")&&Array.isArray(K.content)&&K.content.length>0){let H=K.content[K.content.length-1];if(H&&typeof H==="object"&&H.type!=="tool-approval-request"&&H.type!=="tool-approval-response"){H.providerOptions=N1(H.providerOptions??{},Y);continue}}K.providerOptions=N1(K.providerOptions??{},Y)}return $}function nj0($,Z){return $.map((J)=>{if(J.role!=="user"||!Array.isArray(J.content))return J;let Y=J.content.map((X)=>{if(X.type!=="file"&&X.type!=="image")return X;if(X.type==="image"){let U=String(X.image);if(U.startsWith("data:")){let H=U.match(/^data:([^;]+);base64,(.*)$/);if(H&&(!H[2]||H[2].length===0))return{type:"text",text:"ERROR: Image file is empty or corrupted. Please provide a valid image."}}}let Q=X.type==="image"?String(X.image).split(";")[0].replace("data:",""):X.mediaType,G=X.type==="file"?X.filename:void 0,W=lj0(Q);if(!W)return X;if(W==="image"?dj0(Z):Z.capabilities.input[W])return X;return{type:"text",text:`ERROR: Cannot read ${G?`"${G}"`:W} (this model does not support ${W} input). Inform the user.`}});return{...J,content:Y}})}function oj0($){if(!$.startsWith("data:"))return;let Z=$.slice($.indexOf(",")+1);if(!Z)return 0;let J=Z.endsWith("==")?2:Z.endsWith("=")?1:0;return Math.floor(Z.length*3/4)-J}function sj0($,Z,J){if(Z===void 0&&J===void 0)return $;let Y=$.reduce((Q,G)=>G.role==="user"&&Array.isArray(G.content)?Q+G.content.filter((W)=>W.type==="image").length:Q,0),X=Z===void 0?0:Math.max(0,Y-Z);return $.map((Q)=>{if(Q.role!=="user"||!Array.isArray(Q.content))return Q;let G=Q.content.map((W)=>{if(W.type!=="image")return W;if(X>0)return X--,{type:"text",text:`[Image omitted: exceeds the configured limit of ${Z} prompt image(s).]`};if(J!==void 0){let K=oj0(String(W.image));if(K!==void 0&&K>J)return{type:"text",text:`[Image omitted: exceeds the configured ${J}-byte prompt image size limit.]`}}return W});return{...Q,content:G}})}function xm($,Z,J,Y={}){if($=nj0($,Z),$=sj0($,Y.maxImages,Y.maxSize),$=pj0($,Z,J),cj0(Z))$=ij0($,Z);let X=NK(Z.api.npm);if(X&&X!==Z.providerID){let Q=(G)=>{if(!G)return G;if(!(Z.providerID in G))return G;let W={...G};return W[X]=W[Z.providerID],delete W[Z.providerID],W};$=$.map((G)=>{if(!Array.isArray(G.content))return{...G,providerOptions:Q(G.providerOptions)};return{...G,providerOptions:Q(G.providerOptions),content:G.content.map((W)=>{if(W.type==="tool-approval-request"||W.type==="tool-approval-response")return{...W};return{...W,providerOptions:Q(W.providerOptions)}})}})}return $}var MK=b0.QITQODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX||ym;function hm($,Z,J){return xm($,Z,J,{maxImages:b0.QITQODE_MAX_PROMPT_IMAGES,maxSize:b0.QITQODE_MAX_PROMPT_IMAGE_SIZE})}function gm($){return $()}var U6=["low","medium","high"],um=["none","minimal",...U6,"xhigh"];function mm($){if($)return Object.fromEntries($.map((Z)=>[Z,{thinking:{type:"adaptive"},effort:Z}]));return{high:{thinking:{type:"enabled",budgetTokens:16000}},max:{thinking:{type:"enabled",budgetTokens:31999}}}}function rj0($){if(["opus-4-7","opus-4.7","opus-4-8","opus-4.8"].some((Z)=>$.includes(Z)))return["low","medium","high","xhigh","max"];if(["opus-4-6","opus-4.6","sonnet-4-6","sonnet-4.6"].some((Z)=>$.includes(Z)))return["low","medium","high","max"];return null}function lm($){if(!$.capabilities.reasoning)return{};let Z=$.id.toLowerCase(),J=rj0($.api.id);if(Z.includes("deepseek")||Z.includes("minimax")||Z.includes("glm")||Z.includes("mistral")||Z.includes("kimi")||Z.includes("k2p5")||Z.includes("qwen")||Z.includes("big-pickle"))return{};if(Z.includes("grok")&&Z.includes("grok-3-mini")){if($.api.npm==="@openrouter/ai-sdk-provider")return{low:{reasoning:{effort:"low"}},high:{reasoning:{effort:"high"}}};return{low:{reasoningEffort:"low"},high:{reasoningEffort:"high"}}}if(Z.includes("grok"))return{};switch($.api.npm){case"@openrouter/ai-sdk-provider":if(!$.id.includes("gpt")&&!$.id.includes("gemini-3")&&!$.id.includes("claude"))return{};return Object.fromEntries(um.map((K)=>[K,{reasoning:{effort:K}}]));case"@ai-sdk/gateway":if($.id.includes("anthropic"))return mm(J);if($.id.includes("google")){if(Z.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16000}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};return Object.fromEntries(["low","high"].map((K)=>[K,{includeThoughts:!0,thinkingLevel:K}]))}return Object.fromEntries(um.map((K)=>[K,{reasoningEffort:K}]));case"@ai-sdk/github-copilot":if($.id.includes("gemini"))return{};if($.id.includes("claude"))return Object.fromEntries(U6.map((K)=>[K,{reasoningEffort:K}]));let Y=gm(()=>{if(Z.includes("5.1-codex-max")||Z.includes("5.2")||Z.includes("5.3"))return[...U6,"xhigh"];let K=[...U6];if(Z.includes("gpt-5")&&$.release_date>="2025-12-04")K.push("xhigh");return K});return Object.fromEntries(Y.map((K)=>[K,{reasoningEffort:K,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/cerebras":case"@ai-sdk/togetherai":case"@ai-sdk/xai":case"@ai-sdk/deepinfra":case"venice-ai-sdk-provider":case"@ai-sdk/openai-compatible":return Object.fromEntries(U6.map((K)=>[K,{reasoningEffort:K}]));case"@ai-sdk/azure":if(Z==="o1-mini")return{};let X=["low","medium","high"];if(Z.includes("gpt-5-")||Z==="gpt-5")X.unshift("minimal");return Object.fromEntries(X.map((K)=>[K,{reasoningEffort:K,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/openai":if(Z==="gpt-5-pro")return{};let Q=gm(()=>{if(Z.includes("codex")){if(Z.includes("5.2")||Z.includes("5.3"))return[...U6,"xhigh"];return U6}let K=[...U6];if(Z.includes("gpt-5-")||Z==="gpt-5")K.unshift("minimal");if($.release_date>="2025-11-13")K.unshift("none");if($.release_date>="2025-12-04")K.push("xhigh");return K});return Object.fromEntries(Q.map((K)=>[K,{reasoningEffort:K,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/anthropic":case"@ai-sdk/google-vertex/anthropic":if($.providerID==="github-copilot"){if($.api.id.includes("opus-4.7"))return Object.fromEntries(["medium"].map((K)=>[K,{reasoningEffort:K}]))}if(J)return Object.fromEntries(J.map((K)=>[K,{thinking:{type:"adaptive",...["opus-4-7","opus-4.7","opus-4-8","opus-4.8"].some((V)=>$.api.id.includes(V))?{display:"summarized"}:{}},effort:K}]));return{high:{thinking:{type:"enabled",budgetTokens:Math.max(1,Math.min(16000,Math.floor($.limit.output/2-1)))}},max:{thinking:{type:"enabled",budgetTokens:Math.max(1,Math.min(31999,$.limit.output-1))}}};case"@ai-sdk/amazon-bedrock":if(J)return Object.fromEntries(J.map((K)=>[K,{reasoningConfig:{type:"adaptive",maxReasoningEffort:K,...["opus-4-7","opus-4.7","opus-4-8","opus-4.8"].some((V)=>$.api.id.includes(V))?{display:"summarized"}:{}}}]));if($.api.id.includes("anthropic"))return{high:{reasoningConfig:{type:"enabled",budgetTokens:16000}},max:{reasoningConfig:{type:"enabled",budgetTokens:31999}}};return Object.fromEntries(U6.map((K)=>[K,{reasoningConfig:{type:"enabled",maxReasoningEffort:K}}]));case"@ai-sdk/google-vertex":case"@ai-sdk/google":if(Z.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16000}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};let G=["low","high"];if(Z.includes("3.1"))G=["low","medium","high"];return Object.fromEntries(G.map((K)=>[K,{thinkingConfig:{includeThoughts:!0,thinkingLevel:K}}]));case"@ai-sdk/mistral":return{};case"@ai-sdk/cohere":return{};case"@ai-sdk/groq":let W=["none",...U6];return Object.fromEntries(W.map((K)=>[K,{reasoningEffort:K}]));case"@ai-sdk/perplexity":return{};case"@jerome-benoit/sap-ai-provider-v2":if($.api.id.includes("anthropic"))return mm(J);if($.api.id.includes("gemini")&&Z.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16000}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};if($.api.id.includes("gpt")||/\bo[1-9]/.test($.api.id))return Object.fromEntries(U6.map((K)=>[K,{reasoningEffort:K}]));return{}}return{}}function G5($){return lm($)}function dm($){let Z=$.id.toLowerCase();if(Z.includes("qwen"))return 0.55;if(Z.includes("claude"))return;if(Z.includes("gemini"))return 1;if(Z.includes("glm-4.6"))return 1;if(Z.includes("glm-4.7"))return 1;if(Z.includes("minimax-m2"))return 1;if(Z.includes("kimi-k2")){if(["thinking","k2.","k2p","k2-5"].some((J)=>Z.includes(J)))return 1;return 0.6}return}function pm($){let Z=$.id.toLowerCase();if(Z.includes("qwen"))return 1;if(["minimax-m2","gemini","kimi-k2.5","kimi-k2p5","kimi-k2-5"].some((J)=>Z.includes(J)))return 0.95;return}function cm($){let Z=$.id.toLowerCase();if(Z.includes("minimax-m2")){if(["m2.","m25","m21"].some((J)=>Z.includes(J)))return 40;return 20}if(Z.includes("gemini"))return 64;return}function im($){let Z={};if($.model.providerID==="openai"||$.model.api.npm==="@ai-sdk/openai"||$.model.api.npm==="@ai-sdk/github-copilot")Z.store=!1;if($.model.api.npm==="@ai-sdk/azure")Z.store=!0,Z.promptCacheKey=$.sessionID;if($.model.api.npm==="@openrouter/ai-sdk-provider"||$.model.api.npm==="@llmgateway/ai-sdk-provider"){if(Z.usage={include:!0},$.model.api.id.includes("gemini-3"))Z.reasoning={effort:"high"}}if($.model.providerID==="baseten"||$.model.providerID==="opencode"&&["kimi-k2-thinking","glm-4.6"].includes($.model.api.id))Z.chat_template_args={enable_thinking:!0};if(["zai","zhipuai"].some((Y)=>$.model.providerID.includes(Y))&&$.model.api.npm==="@ai-sdk/openai-compatible")Z.thinking={type:"enabled",clear_thinking:!1};if($.model.providerID==="openai"||$.providerOptions?.setCacheKey)Z.promptCacheKey=$.sessionID;if($.model.api.npm==="@ai-sdk/google"||$.model.api.npm==="@ai-sdk/google-vertex"){if($.model.capabilities.reasoning){if(Z.thinkingConfig={includeThoughts:!0},$.model.api.id.includes("gemini-3"))Z.thinkingConfig.thinkingLevel="high"}}let J=$.model.api.id.toLowerCase();if(($.model.api.npm==="@ai-sdk/anthropic"||$.model.api.npm==="@ai-sdk/google-vertex/anthropic")&&(J.includes("k2p5")||J.includes("kimi-k2.5")||J.includes("kimi-k2p5")))Z.thinking={type:"enabled",budgetTokens:Math.max(1,Math.min(16000,Math.floor($.model.limit.output/2-1)))};if($.model.providerID==="alibaba-cn"&&$.model.capabilities.reasoning&&$.model.api.npm==="@ai-sdk/openai-compatible"&&!J.includes("kimi-k2-thinking"))Z.enable_thinking=!0;if($.model.api.id.includes("gpt-5")&&!$.model.api.id.includes("gpt-5-chat")){if(!$.model.api.id.includes("gpt-5-pro")){if(Z.reasoningEffort="medium",$.model.api.npm==="@ai-sdk/openai"||$.model.api.npm==="@ai-sdk/azure"||$.model.api.npm==="@ai-sdk/github-copilot")Z.reasoningSummary="auto"}if($.model.api.id.includes("gpt-5.")&&!$.model.api.id.includes("codex")&&!$.model.api.id.includes("-chat")&&$.model.providerID!=="azure")Z.textVerbosity="low";if($.model.providerID.startsWith("opencode"))Z.promptCacheKey=$.sessionID,Z.include=["reasoning.encrypted_content"],Z.reasoningSummary="auto"}if($.model.providerID==="venice")Z.promptCacheKey=$.sessionID;if($.model.providerID==="openrouter")Z.prompt_cache_key=$.sessionID;if($.model.api.npm==="@ai-sdk/gateway")Z.gateway={caching:"auto"};return Z}function nm($){if($.providerID==="openai"||$.api.npm==="@ai-sdk/openai"||$.api.npm==="@ai-sdk/github-copilot"){if($.api.id.includes("gpt-5")){if($.api.id.includes("5.")||$.api.id.includes("5-mini"))return{store:!1,reasoningEffort:"low"};return{store:!1,reasoningEffort:"minimal"}}return{store:!1}}if($.providerID==="google"){if($.api.id.includes("gemini-3"))return{thinkingConfig:{thinkingLevel:"minimal"}};return{thinkingConfig:{thinkingBudget:0}}}if($.providerID==="openrouter"||$.providerID==="llmgateway"){if($.api.id.includes("google"))return{reasoning:{enabled:!1}};return{reasoningEffort:"minimal"}}if($.providerID==="venice")return{veniceParameters:{disableThinking:!0}};return{}}var aj0={amazon:"bedrock"};function om($,Z){if($.api.npm==="@ai-sdk/gateway"){let Y=$.api.id.indexOf("/"),X=Y>0?$.api.id.slice(0,Y):void 0,Q=X?aj0[X]??X:void 0,G=Z.gateway,W=Object.fromEntries(Object.entries(Z).filter(([U])=>U!=="gateway")),K=Object.keys(W).length>0,V={};if(G!==void 0)V.gateway=G;if(K)if(Q)V[Q]=W;else if(G&&typeof G==="object"&&!Array.isArray(G))V.gateway={...G,...W};else V.gateway=W;return V}let J=NK($.api.npm)??$.providerID;if($.api.npm==="@ai-sdk/azure")return{openai:Z,azure:Z};return{[J]:Z}}function sm($,Z){return Math.min($.limit.output,Z)||Z}function rm($){return dm($)}function am($){return pm($)}function tm($){return cm($)}function em($){return im($)}function $l($){return nm($)}function Zl($,Z){return om($,Z)}function Jl($){return sm($,MK)}function tj0($){let Z=$,J=Z.anyOf??Z.oneOf;if(!J?.length)return $;let Y=new Map;for(let W of J){if(!W.properties)continue;for(let[K,V]of Object.entries(W.properties))if(V&&typeof V==="object"&&"const"in V){if(!Y.has(K))Y.set(K,new Set);Y.get(K).add(V.const)}}let X;for(let[W,K]of Y)if(K.size===J.length){X=W;break}let Q={},G={};for(let W of J){if(!W.properties)continue;let K=X?W.properties[X]?.const:void 0;for(let[V,U]of Object.entries(W.properties)){if(V===X)continue;if(!(V in Q))Q[V]=U;if(K!==void 0){if(!G[V])G[V]=[];G[V].push(K)}}}if(X)for(let[W,K]of Object.entries(G)){if(K.length===J.length)continue;let V=`(only when ${X}=${K.map((H)=>JSON.stringify(H)).join("|")})`,U=Q[W].description;Q[W]={...Q[W],description:U?`${V} ${U}`:V}}if(X){let W=J[0].properties[X],K=J.map((H)=>H.properties[X]?.const),V=W?.description??"",U=J.map((H)=>{let B=H.properties[X]?.const,z=(H.required??[]).filter((F)=>F!==X);return z.length>0?`${B}: requires ${z.join(", ")}`:`${B}: no extra required fields`}).join("; ");Q[X]={type:"string",enum:K,description:V?`${V}
800
800
 
801
- Per-${X}: ${U}.`:`Per-${X}: ${U}.`}}return{type:"object",properties:Q,required:X?[X]:[],additionalProperties:!1}}function Yl($,Z){if(Z=tj0(Z),$.providerID==="google"||$.api.id.includes("gemini")){let J=(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G),Y=(G)=>J(G)&&(Array.isArray(G.anyOf)||Array.isArray(G.oneOf)||Array.isArray(G.allOf)),X=(G)=>{if(!J(G))return!1;if(Y(G))return!0;return["type","properties","items","prefixItems","enum","const","$ref","additionalProperties","patternProperties","required","not","if","then","else"].some((W)=>(W in G))},Q=(G)=>{if(G===null||typeof G!=="object")return G;if(Array.isArray(G))return G.map(Q);let W={};for(let[K,V]of Object.entries(G))if(K==="enum"&&Array.isArray(V)){if(W[K]=V.map((U)=>String(U)),W.type==="integer"||W.type==="number")W.type="string"}else if(typeof V==="object"&&V!==null)W[K]=Q(V);else W[K]=V;if(W.type==="object"&&W.properties&&Array.isArray(W.required))W.required=W.required.filter((K)=>(K in W.properties));if(W.type==="array"&&!Y(W)){if(W.items==null)W.items={};if(J(W.items)&&!X(W.items))W.items.type="string"}if(W.type&&W.type!=="object"&&!Y(W))delete W.properties,delete W.required;return W};Z=Q(Z)}return Z}function Xl($,Z){return Yl($,Z)}var bA=1e6,DK=new Set(F8.tiers().map(($)=>$.id)),Wl=F8.tiers(),N7=Object.fromEntries(Wl.map(($)=>[$.id,{providerID:$.providerID,modelID:$.modelID}])),k6=F8.qlexProviderMeta();function Kl($,Z){let J=F8.tierBudgetFacts($)??F8.tierBudgetFacts("default");return{id:s1.make($),providerID:X1.make("qlex"),name:Z,family:k6.family,api:{id:$,url:"",npm:k6.npm},status:"active",headers:{},options:{},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:J.context,output:J.output},capabilities:{temperature:k6.capabilities.temperature,reasoning:J.reasoning,attachment:k6.capabilities.attachment,toolcall:k6.capabilities.toolcall,input:{...k6.capabilities.input},output:{...k6.capabilities.output},interleaved:k6.capabilities.interleaved},release_date:k6.release_date,variants:{}}}var Q9={id:X1.make("qlex"),name:k6.name,source:"custom",env:[],options:{},models:Object.fromEntries(Wl.map(($)=>[$.id,Kl($.id,$.label)]))};function Vl(){let $=F8.tiers();DK.clear();for(let J of $)DK.add(J.id);for(let J of Object.keys(N7))delete N7[J];Object.assign(N7,Object.fromEntries($.map((J)=>[J.id,{providerID:J.providerID,modelID:J.modelID}])));let Z=Q9.models;for(let J of Object.keys(Z))delete Z[J];Object.assign(Q9.models,Object.fromEntries($.map((J)=>[J.id,Kl(J.id,J.label)])))}var _A=new Set;function Ul($){let Z={input:$?.input??0,output:$?.output??0,cache:{read:$?.cache_read??0,write:$?.cache_write??0}};if($?.context_over_200k)Z.experimentalOver200K={cache:{read:$.context_over_200k.cache_read??0,write:$.context_over_200k.cache_write??0},input:$.context_over_200k.input,output:$.context_over_200k.output};return Z}function Ql($,Z){let J={id:s1.make(Z.id),providerID:X1.make($.id),name:Z.name,family:Z.family,api:{id:Z.id,url:Z.provider?.api??$.api??"",npm:Z.provider?.npm??$.npm??"@ai-sdk/openai-compatible"},status:Z.status??"active",headers:{},options:{},cost:Ul(Z.cost),limit:{context:Z.limit.context,input:Z.limit.input,output:Z.limit.output},capabilities:{temperature:Z.temperature??!1,reasoning:Z.reasoning??!1,attachment:Z.attachment??!1,toolcall:Z.tool_call??!0,input:{text:Z.modalities?.input?.includes("text")??!1,audio:Z.modalities?.input?.includes("audio")??!1,image:Z.modalities?.input?.includes("image")??!1,video:Z.modalities?.input?.includes("video")??!1,pdf:Z.modalities?.input?.includes("pdf")??!1},output:{text:Z.modalities?.output?.includes("text")??!1,audio:Z.modalities?.output?.includes("audio")??!1,image:Z.modalities?.output?.includes("image")??!1,video:Z.modalities?.output?.includes("video")??!1,pdf:Z.modalities?.output?.includes("pdf")??!1},interleaved:Z.interleaved??!1},release_date:Z.release_date??"",variants:{}};return{...J,variants:v6(G5(J),(Y)=>Y)}}function wK($){let Z={};for(let[J,Y]of Object.entries($.models)){Z[J]=Ql($,Y);for(let[X,Q]of Object.entries(Y.experimental?.modes??{})){let G=`${Y.id}-${X}`,W=Ql($,Y);Z[G]={...W,id:s1.make(G),name:`${Y.name} ${X[0].toUpperCase()}${X.slice(1)}`,cost:Q.cost?N1(W.cost,Ul(Q.cost)):W.cost,options:Q.provider?.body?Object.fromEntries(Object.entries(Q.provider.body).map(([K,V])=>[K.replace(/_([a-z])/g,(U,H)=>H.toUpperCase()),V])):W.options,headers:Q.provider?.headers??W.headers}}}return{id:X1.make($.id),source:"custom",name:$.name,env:$.env??[],options:{},models:Z}}function Hl($){return v6($,(Z)=>G9(Object.values(Z.models))[0].id)}var ej0=["gpt-5.5","gpt-5","claude-sonnet-4","gemini-3-pro"];function G9($){return Gl($,[(Z)=>ej0.findIndex((J)=>Z.id.includes(J)),"desc"],[(Z)=>Z.id.includes("latest")?0:1,"asc"],[(Z)=>Z.id,"desc"])}function W5($){let[Z,...J]=$.split("/");return{providerID:X1.make(Z),modelID:s1.make(J.join("/"))}}var KY=j1.create("ProviderModelNotFoundError",P.object({providerID:X1.zod,modelID:s1.zod,suggestions:P.array(P.string()).optional()})),LK=j1.create("ProviderModelGroupNotFoundError",P.object({group:P.string(),suggestions:P.array(P.string()).optional()})),TK=j1.create("ProviderInitError",P.object({providerID:X1.zod}));function Bl($){let{getState:Z,config:J,readRecent:Y}=$,X=T.fn("Provider.getProvider")((U)=>Z().pipe(T.map((H)=>H.providers[U]))),Q=T.fn("Provider.getModel")(function*(U,H){let B=yield*Z(),z=B.providers[U];if(!z){let A=Object.keys(B.providers),j=RK.default.go(U,A,{limit:3,threshold:-1e4});throw new KY({providerID:U,modelID:H,suggestions:j.map((N)=>N.target)})}let F=z.models[H];if(!F){let A=Object.keys(z.models),j=RK.default.go(H,A,{limit:3,threshold:-1e4});throw new KY({providerID:U,modelID:H,suggestions:j.map((N)=>N.target)})}return F}),G=T.fn("Provider.closest")(function*(U,H){let z=(yield*Z()).providers[U];if(!z)return;for(let F of H)for(let A of Object.keys(z.models))if(A.includes(F))return{providerID:U,modelID:A};return}),W=T.fn("Provider.resolveModelRef")(function*(U,H){if(U.includes("/")){let N=W5(U);return yield*Q(N.providerID,N.modelID)}let B=yield*J.get(),z=B.model_groups?.[U];if(!z){if(DK.has(U)){let q=N7[U];if(q){let C=yield*Q(X1.make(q.providerID),s1.make(q.modelID)).pipe(T.exit);if(C._tag==="Success")return C.value}let M=yield*V();return yield*Q(M.providerID,M.modelID)}let N=Object.keys(B.model_groups??{}),L=RK.default.go(U,N,{limit:3,threshold:-1e4});throw new LK({group:U,suggestions:L.map((q)=>q.target)})}let F=typeof z==="string"?z:z.default,A=typeof z==="string"?[z]:z.models??[z.default];if(H)for(let N of A){let L=W5(N);if(L.providerID!==H)continue;let q=yield*Q(L.providerID,L.modelID).pipe(T.exit);if(q._tag==="Success")return q.value}let j=W5(F);return yield*Q(j.providerID,j.modelID)}),K=T.fn("Provider.getSmallModel")(function*(U){let H=yield*J.get();if(H.small_model){let B=W5(H.small_model);return yield*Q(B.providerID,B.modelID)}for(let B of["lite","free","economical"]){if(H.model_groups?.[B])return yield*W(B,U);let F=N7[B];if(F){let A=yield*Q(X1.make(F.providerID),s1.make(F.modelID)).pipe(T.exit);if(A._tag==="Success")return A.value}}return yield*W("economical",U)}),V=T.fn("Provider.defaultModel")(function*(){let U=yield*J.get();if(U.model)return W5(U.model);let H=yield*Z(),B=yield*Y().pipe(T.map((A)=>{if(!J8(A)||!Array.isArray(A.recent))return[];return A.recent.flatMap((j)=>{if(!J8(j))return[];if(typeof j.providerID!=="string")return[];if(typeof j.modelID!=="string")return[];return[{providerID:X1.make(j.providerID),modelID:s1.make(j.modelID)}]})}),T.catch(()=>T.succeed([])));for(let A of B){let j=H.providers[A.providerID];if(!j)continue;if(!j.models[A.modelID])continue;return{providerID:A.providerID,modelID:A.modelID}}for(let A of["default","fast","economical","power"]){let j=N7[A];if(!j)continue;let N=H.providers[X1.make(j.providerID)];if(N?.models[s1.make(j.modelID)])return{providerID:N.id,modelID:s1.make(j.modelID)}}let z=Object.values(H.providers).find((A)=>!U.provider||Object.keys(U.provider).includes(A.id));if(!z)throw Error("no providers found");let[F]=G9(Object.values(z.models));if(!F)throw Error("no models found");return{providerID:z.id,modelID:F.id}});return{getProvider:X,getModel:Q,closest:G,resolveModelRef:W,getSmallModel:K,defaultModel:V}}var PK=480000;function zl($,Z,J){if(typeof Z!=="number"||Z<=0)return $;if(!$.body)return $;if(!$.headers.get("content-type")?.includes("text/event-stream"))return $;let Y=$.body.getReader(),X=new ReadableStream({async pull(Q){let G=await new Promise((W,K)=>{let V=setTimeout(()=>{let U=Error("SSE read timed out");J.abort(U),Y.cancel(U),K(U)},Z);Y.read().then((U)=>{clearTimeout(V),W(U)},(U)=>{clearTimeout(V),K(U)})});if(G.done){Q.close();return}Q.enqueue(G.value)},async cancel(Q){J.abort(Q),await Y.cancel(Q)}});return new Response(X,{headers:new Headers($.headers),status:$.status,statusText:$.statusText})}import OZ from"os";var VY=E0.create({service:"provider/loaders"}),IK=new Map,jl={"@qitqode/qlex-provider":()=>import("./chunk-9s785py4.js").then(($)=>$.createQlexProvider),"@ai-sdk/amazon-bedrock":()=>import("./chunk-rp8asmq7.js").then(($)=>$.createAmazonBedrock),"@ai-sdk/anthropic":()=>import("./chunk-jv4th87b.js").then(($)=>$.createAnthropic),"@ai-sdk/azure":()=>import("./chunk-rm5ntsvn.js").then(($)=>$.createAzure),"@ai-sdk/google":()=>import("./chunk-yrfq22a5.js").then(($)=>$.createGoogleGenerativeAI),"@ai-sdk/google-vertex":()=>import("./chunk-0f3ft9dh.js").then(($)=>$.createVertex),"@ai-sdk/google-vertex/anthropic":()=>import("./chunk-s0ptrw0z.js").then(($)=>$.createVertexAnthropic),"@ai-sdk/openai":()=>import("./chunk-z2h1gxyx.js").then(($)=>$.createOpenAI),"@ai-sdk/openai-compatible":()=>import("./chunk-k6w32q2p.js").then(($)=>$.createOpenAICompatible),"@openrouter/ai-sdk-provider":()=>import("./chunk-j3jqk62r.js").then(($)=>$.createOpenRouter),"@ai-sdk/xai":()=>import("./chunk-2hv2c8d5.js").then(($)=>$.createXai),"@ai-sdk/mistral":()=>import("./chunk-p887g1xj.js").then(($)=>$.createMistral),"@ai-sdk/groq":()=>import("./chunk-q128vfc6.js").then(($)=>$.createGroq),"@ai-sdk/deepinfra":()=>import("./chunk-p635phfw.js").then(($)=>$.createDeepInfra),"@ai-sdk/cerebras":()=>import("./chunk-2bgqy6z7.js").then(($)=>$.createCerebras),"@ai-sdk/cohere":()=>import("./chunk-2qwmrp16.js").then(($)=>$.createCohere),"@ai-sdk/gateway":()=>import("./chunk-phpmxjf8.js").then(($)=>$.createGateway),"@ai-sdk/togetherai":()=>import("./chunk-9y15zjxa.js").then(($)=>$.createTogetherAI),"@ai-sdk/perplexity":()=>import("./chunk-bk3z400e.js").then(($)=>$.createPerplexity),"@ai-sdk/vercel":()=>import("./chunk-skv9ww0s.js").then(($)=>$.createVercel),"@ai-sdk/alibaba":()=>import("./chunk-86yk21g4.js").then(($)=>$.createAlibaba),"gitlab-ai-provider":()=>import("./chunk-qaz100ht.js").then(($)=>$.createGitLab),"@ai-sdk/github-copilot":()=>import("./chunk-wfggztm4.js").then(($)=>$.createOpenaiCompatible),"venice-ai-sdk-provider":()=>import("./chunk-42r7z6sq.js").then(($)=>$.createVenice)};function Nl($){return $.responses===void 0&&$.chat===void 0}function $N0($){let Z=/^gpt-(\d+)/.exec($);if(!Z)return!1;return Number(Z[1])>=5&&!$.startsWith("gpt-5-mini")}async function Fl($,Z,J){if(Nl($))return $.languageModel(Z);if(J?.useCompletionUrls)return $.chat(Z);else return $.responses(Z)}function Al($,Z){return $.CLOUDFLARE_ACCOUNT_ID||(Z?.type==="api"?Z.metadata?.accountId:void 0)}function Ml($){return{qlex:T.fnUntraced(function*(){return{autoload:!0,options:{getToken:Ol,onInvalidCredentials:async()=>{if(process.env.QITQODE_KEY)VY.error(SA),console.error(SA);try{await ql()}catch{}}},async getModel(Y,X){return Y.languageModel(X)}}}),anthropic:()=>T.succeed({autoload:!1,options:{headers:{"anthropic-beta":"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"}}}),opencode:T.fnUntraced(function*(Z){let J=yield*$.env(),X=l$(()=>{if(Z.env.some((Q)=>J[Q]))return!0;return!1})||Boolean(yield*$.auth(Z.id))||Boolean((yield*$.config()).provider?.opencode?.options?.apiKey);for(let[Q,G]of Object.entries(Z.models))if(!X||G.cost.input===0)delete Z.models[Q];return{autoload:Object.keys(Z.models).length>0,options:{}}}),openai:()=>T.succeed({autoload:!1,async getModel(Z,J,Y){return Z.responses(J)},options:{}}),xai:()=>T.succeed({autoload:!1,async getModel(Z,J,Y){return Z.responses(J)},options:{}}),"github-copilot":()=>T.succeed({autoload:!1,async getModel(Z,J,Y){if(Nl(Z))return Z.languageModel(J);return $N0(J)?Z.responses(J):Z.chat(J)},options:{}}),azure:T.fnUntraced(function*(Z){let J=yield*$.env(),Y=l$(()=>{let X=Z.options?.resourceName;if(typeof X==="string"&&X.trim()!=="")return X;return J.AZURE_RESOURCE_NAME});return{autoload:!1,getModel:Fl,options:{},vars(X){return{...Y&&{AZURE_RESOURCE_NAME:Y}}}}}),"azure-cognitive-services":T.fnUntraced(function*(){let Z=yield*$.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME");return{autoload:!1,getModel:Fl,options:{baseURL:Z?`https://${Z}.cognitiveservices.azure.com/openai`:void 0}}}),"amazon-bedrock":T.fnUntraced(function*(){let Z=(yield*$.config()).provider?.["amazon-bedrock"],J=yield*$.auth("amazon-bedrock"),Y=yield*$.env(),X=Z?.options?.region,Q=Y.AWS_REGION,G=X??Q??"us-east-1",W=Z?.options?.profile,K=Y.AWS_PROFILE,V=W??K,U=Y.AWS_ACCESS_KEY_ID,H=l$(()=>{let N=IK.get("AWS_BEARER_TOKEN_BEDROCK");if(N)return N;if(J?.type==="api")return IK.set("AWS_BEARER_TOKEN_BEDROCK",J.key),process.env.AWS_BEARER_TOKEN_BEDROCK=J.key,J.key;return}),B=Y.AWS_WEB_IDENTITY_TOKEN_FILE,z=Boolean(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(!V&&!U&&!H&&!B&&!z)return{autoload:!1};let{fromNodeProviderChain:F}=yield*T.promise(()=>import("./chunk-q4fn41ex.js")),A={region:G};if(!H){let N=V?{profile:V}:{};A.credentialProvider=F(N)}let j=Z?.options?.endpoint??Z?.options?.baseURL;if(j)A.baseURL=j;return{autoload:!0,options:A,async getModel(N,L,q){if(["global.","us.","eu.","jp.","apac.","au."].some((w)=>L.startsWith(w)))return N.languageModel(L);let C=q?.region??G,R=C.split("-")[0];switch(R){case"us":{let w=["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek"].some((_)=>L.includes(_)),I=C.startsWith("us-gov");if(w&&!I)L=`${R}.${L}`;break}case"eu":{let w=["eu-west-1","eu-west-2","eu-west-3","eu-north-1","eu-central-1","eu-south-1","eu-south-2"].some((_)=>C.includes(_)),I=["claude","nova-lite","nova-micro","llama3","pixtral"].some((_)=>L.includes(_));if(w&&I)L=`${R}.${L}`;break}case"ap":{let w=["ap-southeast-2","ap-southeast-4"].includes(C),I=C==="ap-northeast-1";if(w&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some((_)=>L.includes(_)))R="au",L=`${R}.${L}`;else if(I){if(["claude","nova-lite","nova-micro","nova-pro"].some((E)=>L.includes(E)))R="jp",L=`${R}.${L}`}else if(["claude","nova-lite","nova-micro","nova-pro"].some((E)=>L.includes(E)))R="apac",L=`${R}.${L}`;break}}return N.languageModel(L)}}}),llmgateway:()=>T.succeed({autoload:!1,options:{headers:{"X-Source":"qitqode"}}}),openrouter:()=>T.succeed({autoload:!1,options:{headers:{"X-OpenRouter-Categories":"programming,programming-app,cli-agent"}}}),nvidia:()=>T.succeed({autoload:!1,options:{}}),vercel:()=>T.succeed({autoload:!1,options:{}}),"google-vertex":T.fnUntraced(function*(Z){let J=yield*$.env(),Y=Z.options?.project??J.GOOGLE_CLOUD_PROJECT??J.GCP_PROJECT??J.GCLOUD_PROJECT,X=String(Z.options?.location??J.GOOGLE_VERTEX_LOCATION??J.GOOGLE_CLOUD_LOCATION??J.VERTEX_LOCATION??"us-central1");if(!Boolean(Y))return{autoload:!1};return{autoload:!0,vars(G){let W=X==="global"?"aiplatform.googleapis.com":`${X}-aiplatform.googleapis.com`;return{...Y&&{GOOGLE_VERTEX_PROJECT:Y},GOOGLE_VERTEX_LOCATION:X,GOOGLE_VERTEX_ENDPOINT:W}},options:{project:Y,location:X,fetch:async(G,W)=>{let{GoogleAuth:K}=await import("./chunk-pasm65wq.js").then((m)=>m6(m.default,1)),H=await(await new K().getApplicationDefault()).credential.getAccessToken(),B=new Headers(W?.headers);return B.set("Authorization",`Bearer ${H.token}`),fetch(G,{...W,headers:B})}},async getModel(G,W){let K=String(W).trim();return G.languageModel(K)}}}),"google-vertex-anthropic":T.fnUntraced(function*(){let Z=yield*$.env(),J=Z.GOOGLE_CLOUD_PROJECT??Z.GCP_PROJECT??Z.GCLOUD_PROJECT,Y=Z.GOOGLE_CLOUD_LOCATION??Z.VERTEX_LOCATION??"global";if(!Boolean(J))return{autoload:!1};return{autoload:!0,options:{project:J,location:Y},async getModel(Q,G){let W=String(G).trim();return Q.languageModel(W)}}}),"sap-ai-core":T.fnUntraced(function*(){let Z=yield*$.auth("sap-ai-core"),J=l$(()=>{let Q=IK.get("AICORE_SERVICE_KEY");if(Q)return Q;if(Z?.type==="api")return IK.set("AICORE_SERVICE_KEY",Z.key),process.env.AICORE_SERVICE_KEY=Z.key,Z.key;return}),Y=process.env.AICORE_DEPLOYMENT_ID,X=process.env.AICORE_RESOURCE_GROUP;return{autoload:!!J,options:J?{deploymentId:Y,resourceGroup:X}:{},async getModel(Q,G){return Q(G)}}}),zenmux:()=>T.succeed({autoload:!1,options:{}}),gitlab:T.fnUntraced(function*(Z){let{VERSION:J,isWorkflowModel:Y,discoverWorkflowModels:X}=yield*T.promise(()=>import("./chunk-qaz100ht.js")),Q=(yield*$.get("GITLAB_INSTANCE_URL"))||"https://gitlab.com",G=yield*$.auth(Z.id),W=yield*T.sync(()=>{if(G?.type==="oauth")return G.access;if(G?.type==="api")return G.key;return}),K=W??(yield*$.get("GITLAB_TOKEN")),V=(yield*$.config()).provider?.gitlab,U=yield*B0.directory,H={"User-Agent":`qitqode/${E$} gitlab-ai-provider/${J} (${OZ.platform()} ${OZ.release()}; ${OZ.arch()})`,"anthropic-beta":"context-1m-2025-08-07",...V?.options?.aiGatewayHeaders},B={duo_agent_platform_agentic_chat:!0,duo_agent_platform:!0,...V?.options?.featureFlags};return{autoload:!!K,options:{instanceUrl:Q,apiKey:K,aiGatewayHeaders:H,featureFlags:B},async getModel(z,F,A){if(F.startsWith("duo-workflow-")){let j=typeof A?.workflowRef==="string"?A.workflowRef:void 0,N=Y(F)?F:"duo-workflow",L=typeof A?.workflowDefinition==="string"?A.workflowDefinition:void 0,q=z.workflowChat(N,{featureFlags:B,workflowDefinition:L});if(j)q.selectedModelRef=j;return q}return z.agenticChat(F,{aiGatewayHeaders:H,featureFlags:B})},async discoverModels(){if(!W)return VY.info("gitlab model discovery skipped: no apiKey"),{};try{let z=W,F=()=>G?.type==="api"?{"PRIVATE-TOKEN":z}:{Authorization:`Bearer ${z}`};VY.info("gitlab model discovery starting",{instanceUrl:Q});let A=await X({instanceUrl:Q,getHeaders:F},{workingDirectory:U});if(!A.models.length)return VY.info("gitlab model discovery skipped: no models found",{project:A.project?{id:A.project.id,path:A.project.pathWithNamespace}:null}),{};let j={};for(let N of A.models)if(!Z.models[N.id])j[N.id]={id:s1.make(N.id),providerID:X1.make("gitlab"),name:`Agent Platform (${N.name})`,family:"",api:{id:N.id,url:Q,npm:"gitlab-ai-provider"},status:"active",headers:{},options:{workflowRef:N.ref},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:N.context,output:N.output},capabilities:{temperature:!1,reasoning:!0,attachment:!0,toolcall:!0,input:{text:!0,audio:!1,image:!0,video:!1,pdf:!0},output:{text:!0,audio:!1,image:!1,video:!1,pdf:!1},interleaved:!1},release_date:"",variants:{}};return VY.info("gitlab model discovery complete",{count:Object.keys(j).length,models:Object.keys(j)}),j}catch(z){return VY.warn("gitlab model discovery failed",{error:z}),{}}}}}),"cloudflare-workers-ai":T.fnUntraced(function*(Z){if(Z.options?.baseURL)return{autoload:!1};let J=yield*$.auth(Z.id),Y=yield*$.env(),X=Al(Y,J);if(!X)return{autoload:!1,async getModel(){throw Error("CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>")}};let Q=yield*T.gen(function*(){let G=Y.CLOUDFLARE_API_KEY;if(G)return G;if(J?.type==="api")return J.key;return});return{autoload:!!Q,options:{apiKey:Q,headers:{"User-Agent":`qitqode/${E$} cloudflare-workers-ai (${OZ.platform()} ${OZ.release()}; ${OZ.arch()})`}},async getModel(G,W){return G.languageModel(W)},vars(G){return{CLOUDFLARE_ACCOUNT_ID:X}}}}),"cloudflare-ai-gateway":T.fnUntraced(function*(Z){if(Z.options?.baseURL)return{autoload:!1};let J=yield*$.auth(Z.id),Y=yield*$.env(),X=Al(Y,J),Q=Y.CLOUDFLARE_GATEWAY_ID||(J?.type==="api"?J.metadata?.gatewayId:void 0);if(!X||!Q){let z=[!X?"CLOUDFLARE_ACCOUNT_ID":void 0,!Q?"CLOUDFLARE_GATEWAY_ID":void 0].filter((F)=>Boolean(F));return{autoload:!1,async getModel(){throw Error(`${z.join(" and ")} missing. Set with: ${z.map((F)=>`export ${F}=<value>`).join(" && ")}`)}}}let G=yield*T.gen(function*(){let z=Y.CLOUDFLARE_API_TOKEN||Y.CF_AIG_TOKEN;if(z)return z;if(J?.type==="api")return J.key;return});if(!G)throw Error("CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. Set it via environment variable or run `qitqode auth cloudflare-ai-gateway`.");let{createAiGateway:W}=yield*T.promise(()=>import("./chunk-3qfpw8f6.js")),{createUnified:K}=yield*T.promise(()=>import("./chunk-b4zy78be.js")),U={metadata:l$(()=>{if(Z.options?.metadata)return Z.options.metadata;try{return JSON.parse(Z.options?.headers?.["cf-aig-metadata"])}catch{return}}),cacheTtl:Z.options?.cacheTtl,cacheKey:Z.options?.cacheKey,skipCache:Z.options?.skipCache,collectLog:Z.options?.collectLog,headers:{"User-Agent":`qitqode/${E$} cloudflare-ai-gateway (${OZ.platform()} ${OZ.release()}; ${OZ.arch()})`}},H=W({accountId:X,gateway:Q,apiKey:G,...Object.values(U).some((z)=>z!==void 0)?{options:U}:{}}),B=K();return{autoload:!0,async getModel(z,F,A){return H(B(F))},options:{}}}),cerebras:()=>T.succeed({autoload:!1,options:{headers:{"X-Cerebras-3rd-Party-Integration":"qitqode"}}}),kilo:()=>T.succeed({autoload:!1,options:{}})}}import{pathToFileURL as ZN0}from"url";var fA=E0.create({service:"provider.sdk-runtime"});async function Dl($,Z,J){try{let Y=[];try{const W=CK(Y,fA.time("getSDK",{providerID:$.providerID}),0);let K=Z.providers[$.providerID];let V={...K.options};if($.providerID==="google-vertex"&&!$.api.npm.includes("@ai-sdk/openai-compatible"))delete V.fetch;if($.api.npm.includes("@ai-sdk/openai-compatible")&&V.includeUsage!==!1)V.includeUsage=!0;let U=l$(()=>{let R=typeof V.baseURL==="string"&&V.baseURL!==""?V.baseURL:$.api.url;if(!R)return;let w=Z.varsLoaders[$.providerID];if(w){let I=w(V);for(let[_,E]of Object.entries(I)){let f="${"+_+"}";R=R.replaceAll(f,E)}}return R});if(U!==void 0)V.baseURL=U;if(V.apiKey===void 0&&typeof K.key==="string")V.apiKey=K.key;if($.headers)V.headers={...V.headers,...$.headers};let H=V.fetch;delete V.fetch;let B=V4.fast(JSON.stringify({providerID:$.providerID,npm:$.api.npm,options:V}));let z=Z.sdk.get(B);if(z)return z;let F=V.chunkTimeout;let A=typeof F==="number"?F:PK;delete V.chunkTimeout;V.fetch=async(R,w)=>{let I=H??fetch,_=w??{},E=typeof A==="number"&&A>0?new AbortController:void 0,f=[];if(_.signal)f.push(_.signal);if(E)f.push(E.signal);if(V.timeout!==void 0&&V.timeout!==null&&V.timeout!==!1)f.push(AbortSignal.timeout(V.timeout));let b=f.length===0?null:f.length===1?f[0]:AbortSignal.any(f);if(b)_.signal=b;if($.api.npm==="@ai-sdk/openai"&&_.body&&_.method==="POST"){let k=JSON.parse(_.body);if(!($.providerID.includes("azure")&&k.store===!0)&&Array.isArray(k.input)){for(let p of k.input)if("id"in p)delete p.id;_.body=JSON.stringify(k)}}let y=await I(R,{..._,timeout:!1});if(!E)return y;return zl(y,A,E)};let j=jl[$.api.npm];if(j){fA.info("using bundled provider",{providerID:$.providerID,pkg:$.api.npm});let w=(await j())({name:$.providerID,...V});return Z.sdk.set(B,w),w}let N;if(!$.api.npm.startsWith("file://")){let R=await q6.add($.api.npm);if(!R.entrypoint)throw Error(`Package ${$.api.npm} has no import entrypoint`);N=R.entrypoint}else fA.info("loading local provider",{pkg:$.api.npm}),N=$.api.npm;let L=N.startsWith("file://")?N:ZN0(N).href;let q=await import(L);let M=q[Object.keys(q).find((R)=>R.startsWith("create"))];let C=M({name:$.providerID,...V});Z.sdk.set(B,C);return C}catch(X){var Q=X,G=1}finally{EK(Y,Q,G)}}catch(W){throw new TK({providerID:$.providerID},{cause:W})}}function wl($){let Z={};function J(Y,X){let Q=Z[Y];if(Q){Z[Y]=N1(Q,X);return}let G=$[Y];if(!G)return;Z[Y]=N1(G,X)}return{database:$,providers:Z,mergeProvider:J}}function Ll($){if($.enabled&&!$.enabled.has($.providerID))return!1;if($.disabled.has($.providerID))return!1;return!0}function Tl($,Z){let J=$.env.map((Y)=>Z[Y]).find(Boolean);if(!J)return;return{source:"env",key:$.env.length===1?J:void 0}}function Rl($){if($.type!=="api")return;return{source:"api",key:$.key}}function kA($){return $.hasProvider?{options:$.options??{}}:{source:"custom",options:$.options??{}}}var JN0=E0.create({service:"provider.discovery.filter"});function Pl($){for(let[Z,J]of Object.entries($.providers)){let Y=X1.make(Z);if(!$.isAllowed(Y)){delete $.providers[Y];continue}let X=$.overrides[Y];for(let[Q,G]of Object.entries(J.models)){if(G.api.id=G.api.id??G.id??Q,Q==="gpt-5-chat-latest"||Y===X1.openrouter&&Q==="openai/gpt-5-chat")delete J.models[Q];if(G.status==="alpha"&&!$.experimentalModels)delete J.models[Q];if(G.status==="deprecated")delete J.models[Q];if(X?.blacklist&&X.blacklist.includes(Q)||X?.whitelist&&!X.whitelist.includes(Q))delete J.models[Q];G.variants=v6(G5(G),(K)=>K);let W=X?.models?.[Q]?.variants;if(W&&G.variants){let K=N1(G.variants,W);G.variants=v6(bK(K,(V)=>!V.disabled),(V)=>_K(V,["disabled"]))}}if(Object.keys(J.models).length===0){delete $.providers[Y];continue}JN0.info("found",{providerID:Y})}return $.providers}var YN0=E0.create({service:"provider.discovery.config"});function Il($){for(let[Z,J]of $.configProviders){let Y=$.database[Z],X={id:X1.make(Z),name:J.name??Y?.name??Z,env:J.env??Y?.env??[],options:N1(Y?.options??{},J.options??{}),source:"config",models:Y?.models??{}};for(let[Q,G]of Object.entries(J.models??{})){let W=X.models[G.id??Q],K=G.id??W?.api.id??Q,V=G.provider?.npm??J.npm??W?.api.npm??$.modelsDev[Z]?.npm??"@ai-sdk/openai-compatible",U=l$(()=>{if(G.name)return G.name;if(G.id&&G.id!==Q)return Q;return W?.name??Q}),H={id:s1.make(Q),api:{id:K,npm:V,url:G.provider?.api??J?.api??W?.api.url??$.modelsDev[Z]?.api??""},status:G.status??W?.status??"active",name:U,providerID:X1.make(Z),capabilities:{temperature:G.temperature??W?.capabilities.temperature??!1,reasoning:G.reasoning??W?.capabilities.reasoning??!1,attachment:G.attachment??W?.capabilities.attachment??!1,toolcall:G.tool_call??W?.capabilities.toolcall??!0,input:{text:G.modalities?.input?.includes("text")??W?.capabilities.input.text??!0,audio:G.modalities?.input?.includes("audio")??W?.capabilities.input.audio??!1,image:G.modalities?.input?.includes("image")??W?.capabilities.input.image??!1,video:G.modalities?.input?.includes("video")??W?.capabilities.input.video??!1,pdf:G.modalities?.input?.includes("pdf")??W?.capabilities.input.pdf??!1},output:{text:G.modalities?.output?.includes("text")??W?.capabilities.output.text??!0,audio:G.modalities?.output?.includes("audio")??W?.capabilities.output.audio??!1,image:G.modalities?.output?.includes("image")??W?.capabilities.output.image??!1,video:G.modalities?.output?.includes("video")??W?.capabilities.output.video??!1,pdf:G.modalities?.output?.includes("pdf")??W?.capabilities.output.pdf??!1},interleaved:G.interleaved??W?.capabilities.interleaved??(!W&&V==="@ai-sdk/openai-compatible"&&K.includes("deepseek")?{field:"reasoning_content"}:!1)},cost:{input:G?.cost?.input??W?.cost?.input??0,output:G?.cost?.output??W?.cost?.output??0,cache:{read:G?.cost?.cache_read??W?.cost?.cache.read??0,write:G?.cost?.cache_write??W?.cost?.cache.write??0}},options:N1(W?.options??{},G.options??{}),limit:{context:(()=>{let z=G.limit?.context??W?.limit?.context;if(z!==void 0)return z;let F=`${Z}/${Q}`;if(!_A.has(F))_A.add(F),YN0.warn("limit.context not configured and not found in models.dev",{providerID:Z,modelID:Q,defaulting_to:bA,fix:`Set limit.context explicitly in qitqode.json under provider.${Z}.models.${Q}`});return bA})(),input:G.limit?.input??W?.limit?.input,output:G.limit?.output??W?.limit?.output??0},headers:N1(W?.headers??{},G.headers??{}),family:G.family??W?.family??"",release_date:G.release_date??W?.release_date??"",cachePromptTTL:G.cachePromptTTL??W?.cachePromptTTL,variants:{}},B=N1(G5(H),G.variants??{});H.variants=v6(bK(B,(z)=>!z.disabled),(z)=>_K(z,["disabled"])),X.models[Q]=H}$.database[Z]=X}}var SK=E0.create({service:"provider.discovery"});function El($){let{config:Z,auth:J,env:Y,plugin:X}=$;return T.gen(function*(){let E=[];try{const Q=CK(E,SK.time("state"),0);let G=yield*T7.make();let W=yield*Z.get();let K=yield*T.promise(()=>Cl());let V=v6(K,wK);V[Q9.id]=Q9;let U=wl(V);let{providers:H,mergeProvider:B}=U;let z=new Map;let F={};let A={};let j=new Map;let N={};let L={auth:(k)=>J.get(k).pipe(T.orDie),config:()=>Z.get(),env:()=>Y.all(),get:(k)=>Y.get(k)};SK.info("init");let q=yield*X.list();let M=Object.entries(W.provider??{});let C=new Set(W.disabled_providers??[]);let R=W.enabled_providers?new Set(W.enabled_providers):null;let w=(k)=>Ll({providerID:k,enabled:R,disabled:C});Il({database:V,modelsDev:K,configProviders:M});if(!b0.QITQODE_DISABLE_PROVIDER_ENV){let k=yield*Y.all();for(let[g,d]of Object.entries(V)){let p=X1.make(g);if(C.has(p))continue;let t=Tl(d,k);if(t)B(p,t)}}let I=yield*J.all().pipe(T.orDie);for(let[k,g]of Object.entries(I)){let d=X1.make(k);if(C.has(d))continue;let p=Rl(g);if(p)B(d,p)}for(let k of q){if(!k.auth)continue;let g=X1.make(k.auth.provider);if(C.has(g))continue;if(!(yield*J.get(g).pipe(T.orDie)))continue;if(!k.auth.loader)continue;let t=(yield*T.promise(()=>k.auth.loader(()=>G.promise(J.get(g).pipe(T.orDie)),V[k.auth.provider])))??{};B(g,kA({options:t,hasProvider:Boolean(H[g])}))}for(let[k,g]of Object.entries(Ml(L))){let d=X1.make(k);if(C.has(d))continue;let p=V[d];if(!p){SK.error("Provider does not exist in model list "+d);continue}let t=yield*g(p);if(t&&(t.autoload||H[d])){if(t.getModel)F[d]=t.getModel;if(t.vars)A[d]=t.vars;if(t.discoverModels)N[d]=t.discoverModels;let r=t.options??{};B(d,kA({options:r,hasProvider:Boolean(H[d])}))}}for(let[k,g]of M){let d=X1.make(k),p={source:"config"};if(g.env)p.env=g.env;if(g.name)p.name=g.name;if(g.options)p.options=g.options;B(d,p)}let _=X1.make("gitlab");if(N[_]&&H[_]&&w(_))yield*T.promise(async()=>{try{let k=await N[_]();for(let[g,d]of Object.entries(k))if(!H[_].models[g])H[_].models[g]=d}catch(k){SK.warn("state discovery error",{id:"gitlab",error:k})}});for(let k of q){let g=k.provider,d=g?.models;if(!g||!d)continue;let p=X1.make(g.id);if(C.has(p))continue;let t=H[p];if(!t)continue;let r=yield*J.get(p).pipe(T.orDie);t.models=yield*T.promise(async()=>{let G0=await d(t,{auth:r});return Object.fromEntries(Object.entries(G0).map(([O0,h0])=>[O0,{...h0,id:s1.make(O0),providerID:p}]))})}Pl({providers:H,overrides:W.provider??{},isAllowed:w,experimentalModels:b0.QITQODE_ENABLE_EXPERIMENTAL_MODELS});return{models:z,providers:H,sdk:j,modelLoaders:F,varsLoaders:A}}catch(f){var b=f,y=1}finally{EK(E,b,y)}})}var QN0=O.Struct({id:O.String,url:O.String,npm:O.String}),bl=O.Struct({text:O.Boolean,audio:O.Boolean,image:O.Boolean,video:O.Boolean,pdf:O.Boolean}),GN0=O.Union([O.Boolean,O.Struct({field:O.Literals(["reasoning_content","reasoning_details"])})]),WN0=O.Struct({temperature:O.Boolean,reasoning:O.Boolean,attachment:O.Boolean,toolcall:O.Boolean,input:bl,output:bl,interleaved:GN0}),_l=O.Struct({read:O.Number,write:O.Number}),KN0=O.Struct({input:O.Number,output:O.Number,cache:_l,experimentalOver200K:O.optional(O.Struct({input:O.Number,output:O.Number,cache:_l}))}),VN0=O.Struct({context:O.Number,input:O.optional(O.Number),output:O.Number}),vA=O.Struct({id:s1,providerID:X1,api:QN0,name:O.String,family:O.optional(O.String),capabilities:WN0,cost:KN0,limit:VN0,status:O.Literals(["alpha","beta","deprecated","active"]),options:O.Record(O.String,O.Any),headers:O.Record(O.String,O.String),release_date:O.String,variants:O.optional(O.Record(O.String,O.Record(O.String,O.Any))),cacheTTL:O.optional(O.Number),cachePromptTTL:O.optional(O.Literals(["5m","1h"]))}).annotate({identifier:"Model"}).pipe(u0(($)=>({zod:w0($)}))),fK=O.Struct({id:X1,name:O.String,source:O.Literals(["env","config","custom","api"]),env:O.Array(O.String),key:O.optional(O.String),options:O.Record(O.String,O.Any),models:O.Record(O.String,vA)}).annotate({identifier:"Provider"}).pipe(u0(($)=>({zod:w0($)}))),Sl=O.Record(O.String,O.String),fl=O.Struct({all:O.Array(fK),default:Sl,connected:O.Array(O.String)}).pipe(u0(($)=>({zod:w0($)}))),kl=O.Struct({providers:O.Array(fK),default:Sl}).pipe(u0(($)=>({zod:w0($)})));async function xl($=yl){return F8.loadLiveRatings($)}function hl($){F8.mergeLiveTierRatings($)}class kK extends S1.Service()("@qitqode/Provider"){}var HN0=T0.effect(kK,T.gen(function*(){let $=yield*D$.Service,Z=yield*X8.Service,J=yield*k8.Service,Y=yield*l6.Service,X=yield*AZ.Service;F8.beginTierRatingsLoad();let[Q,G]=yield*T.promise(()=>Promise.all([vl(),xl()]));F8.mergeLiveTiers(Q),hl(G),Vl();let W=yield*B0.make(()=>El({config:Z,auth:J,env:Y,plugin:X})),K=T.fn("Provider.list")(()=>B0.use(W,(N)=>N.providers)),V=Bl({getState:()=>B0.get(W),config:Z,readRecent:()=>$.readJson(UN0.join(F0.Path.state,"model.json"))}),{getProvider:U,getModel:H,closest:B,getSmallModel:z,defaultModel:F,resolveModelRef:A}=V,j=T.fn("Provider.getLanguage")(function*(N){let L=yield*B0.get(W),q=yield*Y.all(),M=`${N.providerID}/${N.id}`;if(L.models.has(M))return L.models.get(M);return yield*T.promise(async()=>{let C=L.providers[N.providerID],R=await Dl(N,L,q);try{let w=L.modelLoaders[N.providerID]?await L.modelLoaders[N.providerID](R,N.api.id,{...C.options,...N.options}):R.languageModel(N.api.id);return L.models.set(M,w),w}catch(w){if(w instanceof XH)throw new KY({modelID:N.id,providerID:N.providerID},{cause:w});throw w}})});return kK.of({list:K,getProvider:U,getModel:H,getLanguage:j,closest:B,getSmallModel:z,defaultModel:F,resolveModelRef:A})})),BN0=T0.suspend(()=>HN0.pipe(T0.provide(D$.defaultLayer),T0.provide(l6.defaultLayer),T0.provide(X8.defaultLayer),T0.provide(k8.defaultLayer),T0.provide(AZ.defaultLayer)));var sl={};F1(sl,{layer:()=>ol,defaultLayer:()=>NN0,ValidationFailed:()=>nl,Service:()=>vK,OauthMissing:()=>pl,OauthCodeMissing:()=>cl,OauthCallbackFailed:()=>il,Methods:()=>ll,Method:()=>yA,CallbackInput:()=>jN0,AuthorizeInput:()=>qN0,Authorization:()=>dl});var ml=O.Struct({key:O.String,op:O.Literals(["eq","neq"]),value:O.String}),zN0=O.Struct({type:O.Literal("text"),key:O.String,message:O.String,placeholder:O.optional(O.String),when:O.optional(ml)}),FN0=O.Struct({label:O.String,value:O.String,hint:O.optional(O.String)}),AN0=O.Struct({type:O.Literal("select"),key:O.String,message:O.String,options:O.Array(FN0),when:O.optional(ml)}),ON0=O.Union([zN0,AN0]);class yA extends O.Class("ProviderAuthMethod")({type:O.Literals(["oauth","api"]),label:O.String,prompts:O.optional(O.Array(ON0))}){static zod=w0(this)}var ll=O.Record(O.String,O.Array(yA)).pipe(u0(($)=>({zod:w0($)})));class dl extends O.Class("ProviderAuthAuthorization")({url:O.String,method:O.Literals(["auto","code"]),instructions:O.String}){static zod=w0(this)}var qN0=O.Struct({method:O.Number.annotate({description:"Auth method index"}),inputs:O.optional(O.Record(O.String,O.String)).annotate({description:"Prompt inputs"})}).pipe(u0(($)=>({zod:w0($)}))),jN0=O.Struct({method:O.Number.annotate({description:"Auth method index"}),code:O.optional(O.String).annotate({description:"OAuth authorization code"})}).pipe(u0(($)=>({zod:w0($)}))),pl=j1.create("ProviderAuthOauthMissing",P.object({providerID:X1.zod})),cl=j1.create("ProviderAuthOauthCodeMissing",P.object({providerID:X1.zod})),il=j1.create("ProviderAuthOauthCallbackFailed",P.object({})),nl=j1.create("ProviderAuthValidationFailed",P.object({field:P.string(),message:P.string()}));class vK extends S1.Service()("@qitqode/ProviderAuth"){}var ol=T0.effect(vK,T.gen(function*(){let $=yield*k8.Service,Z=yield*AZ.Service,J=yield*B0.make(T.fn("ProviderAuth.state")(function*(){let W=yield*Z.list();return{hooks:y7.fromEntries(ul.filterMap(W,(K)=>K.auth?.provider!==void 0?v7.succeed([X1.make(K.auth.provider),K.auth]):v7.failVoid)),pending:new Map}})),Y=O.decodeUnknownSync(ll),X=T.fn("ProviderAuth.methods")(function*(){let W=(yield*B0.get(J)).hooks;return Y(y7.map(W,(K)=>K.methods.map((V)=>({type:V.type,label:V.label,prompts:V.prompts?.map((U)=>{if(U.type==="select")return{type:"select",key:U.key,message:U.message,options:U.options,when:U.when};return{type:"text",key:U.key,message:U.message,placeholder:U.placeholder,when:U.when}})}))))}),Q=T.fn("ProviderAuth.authorize")(function*(W){let{hooks:K,pending:V}=yield*B0.get(J),U=K[W.providerID].methods[W.method];if(U.type!=="oauth")return;if(U.prompts&&W.inputs){for(let B of U.prompts)if(B.type==="text"&&B.validate&&W.inputs[B.key]!==void 0){let z=B.validate(W.inputs[B.key]);if(z)return yield*T.fail(new nl({field:B.key,message:z}))}}let H=yield*T.promise(()=>U.authorize(W.inputs));return V.set(W.providerID,H),{url:H.url,method:H.method,instructions:H.instructions}}),G=T.fn("ProviderAuth.callback")(function*(W){let V=(yield*B0.get(J)).pending.get(W.providerID);if(!V)return yield*T.fail(new pl({providerID:W.providerID}));if(V.method==="code"&&!W.code)return yield*T.fail(new cl({providerID:W.providerID}));let U=yield*T.promise(()=>V.method==="code"?V.callback(W.code):V.callback(W.code));if(!U||U.type!=="success")return yield*T.fail(new il({}));if("key"in U)yield*$.set(W.providerID,{type:"api",key:U.key,..."metadata"in U&&U.metadata?{metadata:U.metadata}:{}});if("refresh"in U){let{type:H,provider:B,refresh:z,access:F,expires:A,...j}=U;yield*$.set(W.providerID,{type:"oauth",access:F,refresh:z,expires:A,...j})}});return vK.of({methods:X,authorize:Q,callback:G})})),NN0=T0.suspend(()=>ol.pipe(T0.provide(k8.defaultLayer),T0.provide(AZ.defaultLayer)));var W9={};F1(W9,{parseStreamError:()=>RN0,parseAPICallError:()=>PN0});import{STATUS_CODES as rl}from"http";var MN0=[/prompt is too long/i,/input is too long for requested model/i,/exceeds the context window/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 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,/context[_ ]length[_ ]exceeded/i,/request entity too large/i,/context length is only \d+ tokens/i,/input length.*exceeds.*context length/i,/prompt too long; exceeded (?:max )?context length/i,/too large for model with \d+ maximum context length/i,/model_context_window_exceeded/i];function DN0($){let Z=$.statusCode;if(!Z)return $.isRetryable;return Z===404||$.isRetryable}function wN0($){if(MN0.some((Z)=>Z.test($)))return!0;return/^4(00|13)\s*(status code)?\s*\(no body\)/i.test($)}function LN0($){if(!$||!/^\s*[\[{]/.test($))return!1;try{return JSON.parse($),!1}catch(Z){let J=0,Y=!1,X=!1;for(let Q of $){if(Y){if(X)X=!1;else if(Q==="\\")X=!0;else if(Q==='"')Y=!1;continue}if(Q==='"')Y=!0;else if(Q==="{"||Q==="[")J++;else if(Q==="}"||Q==="]")J--;if(J<0)return!1}return Y||J>0||/unexpected end|end of json|unterminated string/i.test(String(Z))}}function TN0($,Z){return l$(()=>{let J=Z.message;if(J===""){if(Z.responseBody)return Z.responseBody;if(Z.statusCode){let X=rl[Z.statusCode];if(X)return X}return"Unknown error"}if(!Z.responseBody||Z.statusCode&&J!==rl[Z.statusCode])return J;try{let X=JSON.parse(Z.responseBody),Q=X.message||X.detail||X.error?.message||X.error;if(Q&&typeof Q==="string")return`${J}: ${Q.slice(0,300)}`;if(Array.isArray(Q)&&Q.length>0){let G=Q[0],W=typeof G?.msg==="string"?G.msg:typeof G?.message==="string"?G.message:typeof G==="string"?G:void 0;if(W)return`${J}: ${W.slice(0,300)}`}}catch{}if(/^\s*<!doctype|^\s*<html/i.test(Z.responseBody)){if(Z.statusCode===401)return"Unauthorized: request was blocked by a gateway or proxy. Your authentication token may be missing or expired \u2014 try running `qitqode auth login <your provider URL>` to re-authenticate.";if(Z.statusCode===403)return"Forbidden: request was blocked by a gateway or proxy. You may not have permission to access this resource \u2014 check your account and provider settings.";return J}let Y=Z.responseBody.length>300?Z.responseBody.slice(0,300)+"\u2026":Z.responseBody;return`${J}: ${Y}`}).trim()}function al($){if(typeof $==="string")try{let Z=JSON.parse($);if(Z&&typeof Z==="object")return Z;return}catch{return}if(typeof $==="object"&&$!==null)return $;return}function RN0($){let Z=al($);if(!Z)return;let J=JSON.stringify(Z);if(Z.type!=="error")return;switch(Z?.error?.code){case"context_length_exceeded":return{type:"context_overflow",message:"Input exceeds context window of this model",responseBody:J};case"insufficient_quota":return{type:"api_error",message:"Quota exceeded. Check your plan and billing details.",isRetryable:!1,responseBody:J};case"usage_not_included":return{type:"api_error",message:"To use Codex with your ChatGPT plan, upgrade to Plus: https://chatgpt.com/explore/plus.",isRetryable:!1,responseBody:J};case"invalid_prompt":return{type:"api_error",message:typeof Z?.error?.message==="string"?Z?.error?.message:"Invalid prompt.",isRetryable:!1,responseBody:J}}}function PN0($){let Z=TN0($.providerID,$.error),J=al($.error.responseBody),Y=LN0($.error.responseBody);if(wN0(Z)||$.error.statusCode===413||J?.error?.code==="context_length_exceeded")return{type:"context_overflow",message:Z,responseBody:$.error.responseBody};let X=$.error.url?{url:$.error.url}:void 0;return{type:"api_error",message:Y?"The model connection ended before the response completed.":Z,statusCode:$.error.statusCode,isRetryable:Y||($.providerID.startsWith("openai")?DN0($.error):$.error.isRetryable),category:Y?"stream_truncated":void 0,responseHeaders:$.error.responseHeaders,responseBody:$.error.responseBody,metadata:X}}function xA($,Z){switch(!0){case($ instanceof DOMException&&$.name==="AbortError"):return new f5({message:$.message},{cause:$}).toObject();case O4.isInstance($):{let J=$.lastError??$.errors[$.errors.length-1];if(J!==void 0&&J!==$)return xA(J,Z);return new L6({message:$.message,isRetryable:!0},{cause:$}).toObject()}case U4.isInstance($):return $;case YH.isInstance($):return new H4({providerID:Z.providerID,message:$.message},{cause:$}).toObject();case $?.code==="ECONNRESET":return new L6({message:"Connection reset by server",isRetryable:!0,metadata:{code:$.code??"",syscall:$.syscall??"",message:$.message??""}},{cause:$}).toObject();case($ instanceof Error&&$.code==="ZlibError"):if(Z.aborted)return new f5({message:$.message},{cause:$}).toObject();return new L6({message:"Response decompression failed",isRetryable:!0,metadata:{code:$.code,message:$.message}},{cause:$}).toObject();case FX.isInstance($):{let J=W9.parseAPICallError({providerID:Z.providerID,error:$});if(J.type==="context_overflow")return new GX({message:J.message,responseBody:J.responseBody},{cause:$}).toObject();return new L6({message:J.message,statusCode:J.statusCode,isRetryable:J.isRetryable,category:J.category,outputBudgetRecoveryAvailable:void 0,outputBudgetRecoveryTokens:void 0,diagnostic:UY($),responseHeaders:J.responseHeaders,responseBody:J.responseBody,metadata:J.metadata},{cause:$}).toObject()}case($ instanceof Error&&(typeof $.status==="number"||typeof $.category==="string"&&typeof $.retryable==="boolean")):{let J=$.status,Y=$.retryable===!0;return new L6({message:V6($),statusCode:J,isRetryable:Y,category:$.category,upstreamCode:$.upstreamCode,requestId:$.requestId,outputBudgetRecoveryAvailable:$.outputBudgetRecoveryAvailable,outputBudgetRecoveryTokens:$.outputBudgetRecoveryTokens,diagnostic:UY($)},{cause:$}).toObject()}case $ instanceof Error:return new j1.Unknown({message:V6($),diagnostic:UY($)},{cause:$}).toObject();default:try{let J=W9.parseStreamError($);if(J){if(J.type==="context_overflow")return new GX({message:J.message,responseBody:J.responseBody},{cause:$}).toObject();return new L6({message:J.message,isRetryable:J.isRetryable,diagnostic:UY($),responseBody:J.responseBody},{cause:$}).toObject()}}catch{}return new j1.Unknown({message:V6($),diagnostic:UY($)},{cause:$}).toObject()}}var BY={};F1(BY,{layer:()=>Xd,defaultLayer:()=>kN0,Service:()=>yK,ActorRegistry:()=>BY});var _1=g6("actor_registry",{session_id:w1().$type().notNull().references(()=>I1.id,{onDelete:"cascade"}),actor_id:w1().notNull(),mode:w1().$type().notNull(),parent_actor_id:w1(),status:w1().$type().notNull(),last_outcome:w1().$type(),lifecycle:w1().$type().notNull(),agent:w1().notNull(),description:w1().notNull(),context_mode:w1().$type().notNull(),context_watermark:w1().$type(),background:j8({mode:"boolean"}).notNull(),tools:w1({mode:"json"}).$type(),last_turn_time:j8().notNull(),turn_count:j8().notNull().default(0),last_error:w1(),time_completed:j8(),...xY},($)=>[k9({columns:[$.session_id,$.actor_id]}),K9("actor_registry_session_agent_idx").on($.session_id,$.agent),K9("actor_registry_session_parent_idx").on($.session_id,$.parent_actor_id),K9("actor_registry_status_idx").on($.status),K9("actor_registry_status_last_turn_idx").on($.status,$.last_turn_time)]);var hA=P.enum(["pending","running","idle"]),gA=P.enum(["success","failure","cancelled"]),IN0=P.enum(["ephemeral","persistent"]),CN0=P.enum(["none","state","full"]),uA=P.enum(["peer","subagent","main"]),EN0=P.union([P.array(P.string()).readonly(),P.literal("INHERIT")]),Qd0=P.object({sessionID:r0.zod,actorID:P.string(),mode:uA,parentActorID:P.string().optional(),status:hA,lastOutcome:gA.optional(),lifecycle:IN0,agent:P.string(),description:P.string(),contextMode:CN0,contextWatermark:i1.zod.optional(),background:P.boolean(),tools:EN0.optional(),lastTurnTime:P.number(),turnCount:P.number(),lastError:P.string().optional(),time:P.object({created:P.number(),updated:P.number(),completed:P.number().optional()})}).meta({ref:"Actor"});var tl=L1.define("actor.registered",P.object({sessionID:r0.zod,actorID:P.string(),mode:uA,parentActorID:P.string().optional(),description:P.string(),agent:P.string(),background:P.boolean()})),el=L1.define("actor.status",P.object({sessionID:r0.zod,actorID:P.string(),status:hA,lastOutcome:gA.optional(),turnCount:P.number(),lastTurnTime:P.number(),error:P.string().optional()})),$d=L1.define("actor.stuck",P.object({sessionID:r0.zod,actorID:P.string(),description:P.string(),lastTurnTime:P.number(),stuckDuration:P.number()})),Hd0=L1.define("writer.cache_perf",P.object({sessionID:r0.zod,writerActorID:P.string(),status:P.enum(["completed","failed"]),total_input_tokens:P.number(),cache_read_tokens:P.number(),cache_write_tokens:P.number(),cache_hit_rate:P.number(),num_llm_calls:P.number()})),Bd0=L1.define("inbox.arrived",P.object({receiverSessionID:r0.zod,receiverActorID:P.string(),senderSessionID:r0.zod.optional(),senderActorID:P.string().optional(),inboxID:P.string(),type:P.string()}));var Zd=new Set(["checkpoint-writer","dream","distill"]);var _N0=E0.create({service:"actor.registry"}),SN0=300000,fN0=60000;function HY($){return{sessionID:$.session_id,actorID:$.actor_id,mode:$.mode,parentActorID:$.parent_actor_id??void 0,status:$.status,lastOutcome:$.last_outcome??void 0,lifecycle:$.lifecycle,agent:$.agent,description:$.description,contextMode:$.context_mode,contextWatermark:$.context_watermark??void 0,background:Boolean($.background),tools:$.tools??void 0,lastTurnTime:$.last_turn_time,turnCount:$.turn_count,lastError:$.last_error??void 0,time:{created:$.time_created,updated:$.time_updated,completed:$.time_completed??void 0}}}class yK extends S1.Service()("@qitqode/ActorRegistry"){}var Xd=T0.effect(yK,T.gen(function*(){let $=yield*l1.Service,Z=new Map,J=T.fn("ActorRegistry.register")(function*(A){let j=Date.now(),N={session_id:A.sessionID,actor_id:A.actorID,mode:A.mode,parent_actor_id:A.parentActorID??null,status:"pending",last_outcome:null,lifecycle:A.lifecycle,agent:A.agent,description:A.description,context_mode:A.contextMode,context_watermark:A.contextWatermark??null,background:A.background,tools:A.tools??null,last_turn_time:j,turn_count:0,last_error:null,time_completed:null,time_created:j,time_updated:j};return yield*T.sync(()=>W1.use((L)=>{try{L.insert(_1).values(N).run()}catch(q){if(typeof q==="object"&&q!==null&&"code"in q&&typeof q.code==="string"&&(q.code==="SQLITE_CONSTRAINT_PRIMARYKEY"||q.code==="SQLITE_CONSTRAINT_UNIQUE")||q instanceof Error&&q.message.toLowerCase().includes("unique constraint"))throw Error(`Actor ID collision: '${A.actorID}' already exists in session '${A.sessionID}'.`);throw q}})),yield*$.publish(tl,{sessionID:A.sessionID,actorID:A.actorID,mode:A.mode,parentActorID:A.parentActorID,description:A.description,agent:A.agent,background:A.background}),HY(N)}),Y=T.fnUntraced(function*(A,j){return yield*T.sync(()=>W1.use((N)=>N.select().from(_1).where(O$(m0(_1.session_id,A),m0(_1.actor_id,j))).get()))}),X=T.fn("ActorRegistry.updateStatus")(function*(A,j,N){let L=Date.now(),q=N.status==="idle"&&N.lastOutcome!==void 0,M={status:N.status,time_updated:L,...q?{time_completed:L}:{}};if(N.lastOutcome!==void 0)M.last_outcome=N.lastOutcome;if(N.lastError!==void 0)M.last_error=N.lastError;else if(N.lastOutcome!==void 0&&N.lastOutcome!=="failure")M.last_error=null;yield*T.sync(()=>W1.use((R)=>R.update(_1).set(M).where(O$(m0(_1.session_id,A),m0(_1.actor_id,j))).run()));let C=yield*Y(A,j);if(!C)return;yield*$.publish(el,{sessionID:A,actorID:j,status:C.status,...C.last_outcome?{lastOutcome:C.last_outcome}:{},turnCount:C.turn_count,lastTurnTime:C.last_turn_time,...C.last_error?{error:C.last_error}:{}})}),Q=T.fn("ActorRegistry.updateTurn")(function*(A,j){let N=Date.now();yield*T.sync(()=>W1.use((L)=>L.update(_1).set({last_turn_time:N,turn_count:Jd`${_1.turn_count} + 1`,time_updated:N}).where(O$(m0(_1.session_id,A),m0(_1.actor_id,j))).run()))}),G=T.fn("ActorRegistry.get")(function*(A,j){let N=yield*Y(A,j);return N?HY(N):void 0}),W=T.fn("ActorRegistry.listBySession")(function*(A){return(yield*T.sync(()=>W1.use((N)=>N.select().from(_1).where(m0(_1.session_id,A)).all()))).map(HY)}),K=T.fn("ActorRegistry.listActive")(function*(){return(yield*T.sync(()=>W1.use((j)=>j.select().from(_1).where(O$(k5(_1.status,["pending","running"]),m0(_1.background,!0))).all()))).map(HY)}),V=T.fn("ActorRegistry.listByParent")(function*(A,j){return(yield*T.sync(()=>W1.use((L)=>L.select().from(_1).where(O$(m0(_1.session_id,A),m0(_1.parent_actor_id,j))).all()))).map(HY)}),U=T.fn("ActorRegistry.renderForAgent")(function*(A){let N=(yield*W(A)).filter((M)=>M.background&&(M.status==="pending"||M.status==="running"));if(N.length===0)return"";let L=[];L.push("## Active Actors"),L.push(""),L.push(`You have ${N.length} background actor(s) registered. Interact via the \`actor\` tool.`),L.push("");let q=Date.now();for(let M of N){let C=q-M.lastTurnTime,R=C<60000?`${Math.floor(C/1000)}s`:`${Math.floor(C/60000)}m`;L.push(`- actor_id: ${M.actorID} (${M.status}, last activity ${R} ago)`),L.push(` description: ${M.description}`),L.push(` agent: ${M.agent}`)}return L.join(`
801
+ Per-${X}: ${U}.`:`Per-${X}: ${U}.`}}return{type:"object",properties:Q,required:X?[X]:[],additionalProperties:!1}}function Yl($,Z){if(Z=tj0(Z),$.providerID==="google"||$.api.id.includes("gemini")){let J=(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G),Y=(G)=>J(G)&&(Array.isArray(G.anyOf)||Array.isArray(G.oneOf)||Array.isArray(G.allOf)),X=(G)=>{if(!J(G))return!1;if(Y(G))return!0;return["type","properties","items","prefixItems","enum","const","$ref","additionalProperties","patternProperties","required","not","if","then","else"].some((W)=>(W in G))},Q=(G)=>{if(G===null||typeof G!=="object")return G;if(Array.isArray(G))return G.map(Q);let W={};for(let[K,V]of Object.entries(G))if(K==="enum"&&Array.isArray(V)){if(W[K]=V.map((U)=>String(U)),W.type==="integer"||W.type==="number")W.type="string"}else if(typeof V==="object"&&V!==null)W[K]=Q(V);else W[K]=V;if(W.type==="object"&&W.properties&&Array.isArray(W.required))W.required=W.required.filter((K)=>(K in W.properties));if(W.type==="array"&&!Y(W)){if(W.items==null)W.items={};if(J(W.items)&&!X(W.items))W.items.type="string"}if(W.type&&W.type!=="object"&&!Y(W))delete W.properties,delete W.required;return W};Z=Q(Z)}return Z}function Xl($,Z){return Yl($,Z)}var bA=1e6,DK=new Set(F8.tiers().map(($)=>$.id)),Wl=F8.tiers(),N7=Object.fromEntries(Wl.map(($)=>[$.id,{providerID:$.providerID,modelID:$.modelID}])),k6=F8.qlexProviderMeta();function Kl($,Z){let J=F8.tierBudgetFacts($)??F8.tierBudgetFacts("default");return{id:s1.make($),providerID:X1.make("qlex"),name:Z,family:k6.family,api:{id:$,url:"",npm:k6.npm},status:"active",headers:{},options:{},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:J.context,output:J.output},capabilities:{temperature:k6.capabilities.temperature,reasoning:J.reasoning,attachment:k6.capabilities.attachment,toolcall:k6.capabilities.toolcall,input:{...k6.capabilities.input},output:{...k6.capabilities.output},interleaved:k6.capabilities.interleaved},release_date:k6.release_date,variants:{}}}var Q9={id:X1.make("qlex"),name:k6.name,source:"custom",env:[],options:{},models:Object.fromEntries(Wl.map(($)=>[$.id,Kl($.id,$.label)]))};function Vl(){let $=F8.tiers();DK.clear();for(let J of $)DK.add(J.id);for(let J of Object.keys(N7))delete N7[J];Object.assign(N7,Object.fromEntries($.map((J)=>[J.id,{providerID:J.providerID,modelID:J.modelID}])));let Z=Q9.models;for(let J of Object.keys(Z))delete Z[J];Object.assign(Q9.models,Object.fromEntries($.map((J)=>[J.id,Kl(J.id,J.label)])))}var _A=new Set;function Ul($){let Z={input:$?.input??0,output:$?.output??0,cache:{read:$?.cache_read??0,write:$?.cache_write??0}};if($?.context_over_200k)Z.experimentalOver200K={cache:{read:$.context_over_200k.cache_read??0,write:$.context_over_200k.cache_write??0},input:$.context_over_200k.input,output:$.context_over_200k.output};return Z}function Ql($,Z){let J={id:s1.make(Z.id),providerID:X1.make($.id),name:Z.name,family:Z.family,api:{id:Z.id,url:Z.provider?.api??$.api??"",npm:Z.provider?.npm??$.npm??"@ai-sdk/openai-compatible"},status:Z.status??"active",headers:{},options:{},cost:Ul(Z.cost),limit:{context:Z.limit.context,input:Z.limit.input,output:Z.limit.output},capabilities:{temperature:Z.temperature??!1,reasoning:Z.reasoning??!1,attachment:Z.attachment??!1,toolcall:Z.tool_call??!0,input:{text:Z.modalities?.input?.includes("text")??!1,audio:Z.modalities?.input?.includes("audio")??!1,image:Z.modalities?.input?.includes("image")??!1,video:Z.modalities?.input?.includes("video")??!1,pdf:Z.modalities?.input?.includes("pdf")??!1},output:{text:Z.modalities?.output?.includes("text")??!1,audio:Z.modalities?.output?.includes("audio")??!1,image:Z.modalities?.output?.includes("image")??!1,video:Z.modalities?.output?.includes("video")??!1,pdf:Z.modalities?.output?.includes("pdf")??!1},interleaved:Z.interleaved??!1},release_date:Z.release_date??"",variants:{}};return{...J,variants:v6(G5(J),(Y)=>Y)}}function wK($){let Z={};for(let[J,Y]of Object.entries($.models)){Z[J]=Ql($,Y);for(let[X,Q]of Object.entries(Y.experimental?.modes??{})){let G=`${Y.id}-${X}`,W=Ql($,Y);Z[G]={...W,id:s1.make(G),name:`${Y.name} ${X[0].toUpperCase()}${X.slice(1)}`,cost:Q.cost?N1(W.cost,Ul(Q.cost)):W.cost,options:Q.provider?.body?Object.fromEntries(Object.entries(Q.provider.body).map(([K,V])=>[K.replace(/_([a-z])/g,(U,H)=>H.toUpperCase()),V])):W.options,headers:Q.provider?.headers??W.headers}}}return{id:X1.make($.id),source:"custom",name:$.name,env:$.env??[],options:{},models:Z}}function Hl($){return v6($,(Z)=>G9(Object.values(Z.models))[0].id)}var ej0=["gpt-5.5","gpt-5","claude-sonnet-4","gemini-3-pro"];function G9($){return Gl($,[(Z)=>ej0.findIndex((J)=>Z.id.includes(J)),"desc"],[(Z)=>Z.id.includes("latest")?0:1,"asc"],[(Z)=>Z.id,"desc"])}function W5($){let[Z,...J]=$.split("/");return{providerID:X1.make(Z),modelID:s1.make(J.join("/"))}}var KY=j1.create("ProviderModelNotFoundError",P.object({providerID:X1.zod,modelID:s1.zod,suggestions:P.array(P.string()).optional()})),LK=j1.create("ProviderModelGroupNotFoundError",P.object({group:P.string(),suggestions:P.array(P.string()).optional()})),TK=j1.create("ProviderInitError",P.object({providerID:X1.zod}));function Bl($){let{getState:Z,config:J,readRecent:Y}=$,X=T.fn("Provider.getProvider")((U)=>Z().pipe(T.map((H)=>H.providers[U]))),Q=T.fn("Provider.getModel")(function*(U,H){let B=yield*Z(),z=B.providers[U];if(!z){let A=Object.keys(B.providers),j=RK.default.go(U,A,{limit:3,threshold:-1e4});throw new KY({providerID:U,modelID:H,suggestions:j.map((N)=>N.target)})}let F=z.models[H];if(!F){let A=Object.keys(z.models),j=RK.default.go(H,A,{limit:3,threshold:-1e4});throw new KY({providerID:U,modelID:H,suggestions:j.map((N)=>N.target)})}return F}),G=T.fn("Provider.closest")(function*(U,H){let z=(yield*Z()).providers[U];if(!z)return;for(let F of H)for(let A of Object.keys(z.models))if(A.includes(F))return{providerID:U,modelID:A};return}),W=T.fn("Provider.resolveModelRef")(function*(U,H){if(U.includes("/")){let N=W5(U);return yield*Q(N.providerID,N.modelID)}let B=yield*J.get(),z=B.model_groups?.[U];if(!z){if(DK.has(U)){let q=N7[U];if(q){let C=yield*Q(X1.make(q.providerID),s1.make(q.modelID)).pipe(T.exit);if(C._tag==="Success")return C.value}let M=yield*V();return yield*Q(M.providerID,M.modelID)}let N=Object.keys(B.model_groups??{}),L=RK.default.go(U,N,{limit:3,threshold:-1e4});throw new LK({group:U,suggestions:L.map((q)=>q.target)})}let F=typeof z==="string"?z:z.default,A=typeof z==="string"?[z]:z.models??[z.default];if(H)for(let N of A){let L=W5(N);if(L.providerID!==H)continue;let q=yield*Q(L.providerID,L.modelID).pipe(T.exit);if(q._tag==="Success")return q.value}let j=W5(F);return yield*Q(j.providerID,j.modelID)}),K=T.fn("Provider.getSmallModel")(function*(U){let H=yield*J.get();if(H.small_model){let B=W5(H.small_model);return yield*Q(B.providerID,B.modelID)}for(let B of["lite","free","economical"]){if(H.model_groups?.[B])return yield*W(B,U);let F=N7[B];if(F){let A=yield*Q(X1.make(F.providerID),s1.make(F.modelID)).pipe(T.exit);if(A._tag==="Success")return A.value}}return yield*W("economical",U)}),V=T.fn("Provider.defaultModel")(function*(){let U=yield*J.get();if(U.model)return W5(U.model);let H=yield*Z(),B=yield*Y().pipe(T.map((A)=>{if(!J8(A)||!Array.isArray(A.recent))return[];return A.recent.flatMap((j)=>{if(!J8(j))return[];if(typeof j.providerID!=="string")return[];if(typeof j.modelID!=="string")return[];return[{providerID:X1.make(j.providerID),modelID:s1.make(j.modelID)}]})}),T.catch(()=>T.succeed([])));for(let A of B){let j=H.providers[A.providerID];if(!j)continue;if(!j.models[A.modelID])continue;return{providerID:A.providerID,modelID:A.modelID}}for(let A of["default","fast","economical","power"]){let j=N7[A];if(!j)continue;let N=H.providers[X1.make(j.providerID)];if(N?.models[s1.make(j.modelID)])return{providerID:N.id,modelID:s1.make(j.modelID)}}let z=Object.values(H.providers).find((A)=>!U.provider||Object.keys(U.provider).includes(A.id));if(!z)throw Error("no providers found");let[F]=G9(Object.values(z.models));if(!F)throw Error("no models found");return{providerID:z.id,modelID:F.id}});return{getProvider:X,getModel:Q,closest:G,resolveModelRef:W,getSmallModel:K,defaultModel:V}}var PK=480000;function zl($,Z,J){if(typeof Z!=="number"||Z<=0)return $;if(!$.body)return $;if(!$.headers.get("content-type")?.includes("text/event-stream"))return $;let Y=$.body.getReader(),X=new ReadableStream({async pull(Q){let G=await new Promise((W,K)=>{let V=setTimeout(()=>{let U=Error("SSE read timed out");J.abort(U),Y.cancel(U),K(U)},Z);Y.read().then((U)=>{clearTimeout(V),W(U)},(U)=>{clearTimeout(V),K(U)})});if(G.done){Q.close();return}Q.enqueue(G.value)},async cancel(Q){J.abort(Q),await Y.cancel(Q)}});return new Response(X,{headers:new Headers($.headers),status:$.status,statusText:$.statusText})}import OZ from"os";var VY=E0.create({service:"provider/loaders"}),IK=new Map,jl={"@qitqode/qlex-provider":()=>import("./chunk-qk9x8j8d.js").then(($)=>$.createQlexProvider),"@ai-sdk/amazon-bedrock":()=>import("./chunk-p169ee92.js").then(($)=>$.createAmazonBedrock),"@ai-sdk/anthropic":()=>import("./chunk-mn9end71.js").then(($)=>$.createAnthropic),"@ai-sdk/azure":()=>import("./chunk-nty5z2cj.js").then(($)=>$.createAzure),"@ai-sdk/google":()=>import("./chunk-jg1ccs3j.js").then(($)=>$.createGoogleGenerativeAI),"@ai-sdk/google-vertex":()=>import("./chunk-05ck7acg.js").then(($)=>$.createVertex),"@ai-sdk/google-vertex/anthropic":()=>import("./chunk-g3wvtyw3.js").then(($)=>$.createVertexAnthropic),"@ai-sdk/openai":()=>import("./chunk-bbng1cea.js").then(($)=>$.createOpenAI),"@ai-sdk/openai-compatible":()=>import("./chunk-f97k17t8.js").then(($)=>$.createOpenAICompatible),"@openrouter/ai-sdk-provider":()=>import("./chunk-bqn6bqws.js").then(($)=>$.createOpenRouter),"@ai-sdk/xai":()=>import("./chunk-0428v6mw.js").then(($)=>$.createXai),"@ai-sdk/mistral":()=>import("./chunk-rn83r0js.js").then(($)=>$.createMistral),"@ai-sdk/groq":()=>import("./chunk-w4brava0.js").then(($)=>$.createGroq),"@ai-sdk/deepinfra":()=>import("./chunk-f31yvp20.js").then(($)=>$.createDeepInfra),"@ai-sdk/cerebras":()=>import("./chunk-wwdpw27v.js").then(($)=>$.createCerebras),"@ai-sdk/cohere":()=>import("./chunk-3vvd7j14.js").then(($)=>$.createCohere),"@ai-sdk/gateway":()=>import("./chunk-sh9vjnsh.js").then(($)=>$.createGateway),"@ai-sdk/togetherai":()=>import("./chunk-xe69cnsk.js").then(($)=>$.createTogetherAI),"@ai-sdk/perplexity":()=>import("./chunk-y0527cg0.js").then(($)=>$.createPerplexity),"@ai-sdk/vercel":()=>import("./chunk-804vmbcd.js").then(($)=>$.createVercel),"@ai-sdk/alibaba":()=>import("./chunk-venprxdp.js").then(($)=>$.createAlibaba),"gitlab-ai-provider":()=>import("./chunk-k5q9px67.js").then(($)=>$.createGitLab),"@ai-sdk/github-copilot":()=>import("./chunk-k4gsktts.js").then(($)=>$.createOpenaiCompatible),"venice-ai-sdk-provider":()=>import("./chunk-y67kaj0b.js").then(($)=>$.createVenice)};function Nl($){return $.responses===void 0&&$.chat===void 0}function $N0($){let Z=/^gpt-(\d+)/.exec($);if(!Z)return!1;return Number(Z[1])>=5&&!$.startsWith("gpt-5-mini")}async function Fl($,Z,J){if(Nl($))return $.languageModel(Z);if(J?.useCompletionUrls)return $.chat(Z);else return $.responses(Z)}function Al($,Z){return $.CLOUDFLARE_ACCOUNT_ID||(Z?.type==="api"?Z.metadata?.accountId:void 0)}function Ml($){return{qlex:T.fnUntraced(function*(){return{autoload:!0,options:{getToken:Ol,onInvalidCredentials:async()=>{if(process.env.QITQODE_KEY)VY.error(SA),console.error(SA);try{await ql()}catch{}}},async getModel(Y,X){return Y.languageModel(X)}}}),anthropic:()=>T.succeed({autoload:!1,options:{headers:{"anthropic-beta":"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"}}}),opencode:T.fnUntraced(function*(Z){let J=yield*$.env(),X=l$(()=>{if(Z.env.some((Q)=>J[Q]))return!0;return!1})||Boolean(yield*$.auth(Z.id))||Boolean((yield*$.config()).provider?.opencode?.options?.apiKey);for(let[Q,G]of Object.entries(Z.models))if(!X||G.cost.input===0)delete Z.models[Q];return{autoload:Object.keys(Z.models).length>0,options:{}}}),openai:()=>T.succeed({autoload:!1,async getModel(Z,J,Y){return Z.responses(J)},options:{}}),xai:()=>T.succeed({autoload:!1,async getModel(Z,J,Y){return Z.responses(J)},options:{}}),"github-copilot":()=>T.succeed({autoload:!1,async getModel(Z,J,Y){if(Nl(Z))return Z.languageModel(J);return $N0(J)?Z.responses(J):Z.chat(J)},options:{}}),azure:T.fnUntraced(function*(Z){let J=yield*$.env(),Y=l$(()=>{let X=Z.options?.resourceName;if(typeof X==="string"&&X.trim()!=="")return X;return J.AZURE_RESOURCE_NAME});return{autoload:!1,getModel:Fl,options:{},vars(X){return{...Y&&{AZURE_RESOURCE_NAME:Y}}}}}),"azure-cognitive-services":T.fnUntraced(function*(){let Z=yield*$.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME");return{autoload:!1,getModel:Fl,options:{baseURL:Z?`https://${Z}.cognitiveservices.azure.com/openai`:void 0}}}),"amazon-bedrock":T.fnUntraced(function*(){let Z=(yield*$.config()).provider?.["amazon-bedrock"],J=yield*$.auth("amazon-bedrock"),Y=yield*$.env(),X=Z?.options?.region,Q=Y.AWS_REGION,G=X??Q??"us-east-1",W=Z?.options?.profile,K=Y.AWS_PROFILE,V=W??K,U=Y.AWS_ACCESS_KEY_ID,H=l$(()=>{let N=IK.get("AWS_BEARER_TOKEN_BEDROCK");if(N)return N;if(J?.type==="api")return IK.set("AWS_BEARER_TOKEN_BEDROCK",J.key),process.env.AWS_BEARER_TOKEN_BEDROCK=J.key,J.key;return}),B=Y.AWS_WEB_IDENTITY_TOKEN_FILE,z=Boolean(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(!V&&!U&&!H&&!B&&!z)return{autoload:!1};let{fromNodeProviderChain:F}=yield*T.promise(()=>import("./chunk-0xrb12s8.js")),A={region:G};if(!H){let N=V?{profile:V}:{};A.credentialProvider=F(N)}let j=Z?.options?.endpoint??Z?.options?.baseURL;if(j)A.baseURL=j;return{autoload:!0,options:A,async getModel(N,L,q){if(["global.","us.","eu.","jp.","apac.","au."].some((w)=>L.startsWith(w)))return N.languageModel(L);let C=q?.region??G,R=C.split("-")[0];switch(R){case"us":{let w=["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek"].some((_)=>L.includes(_)),I=C.startsWith("us-gov");if(w&&!I)L=`${R}.${L}`;break}case"eu":{let w=["eu-west-1","eu-west-2","eu-west-3","eu-north-1","eu-central-1","eu-south-1","eu-south-2"].some((_)=>C.includes(_)),I=["claude","nova-lite","nova-micro","llama3","pixtral"].some((_)=>L.includes(_));if(w&&I)L=`${R}.${L}`;break}case"ap":{let w=["ap-southeast-2","ap-southeast-4"].includes(C),I=C==="ap-northeast-1";if(w&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some((_)=>L.includes(_)))R="au",L=`${R}.${L}`;else if(I){if(["claude","nova-lite","nova-micro","nova-pro"].some((E)=>L.includes(E)))R="jp",L=`${R}.${L}`}else if(["claude","nova-lite","nova-micro","nova-pro"].some((E)=>L.includes(E)))R="apac",L=`${R}.${L}`;break}}return N.languageModel(L)}}}),llmgateway:()=>T.succeed({autoload:!1,options:{headers:{"X-Source":"qitqode"}}}),openrouter:()=>T.succeed({autoload:!1,options:{headers:{"X-OpenRouter-Categories":"programming,programming-app,cli-agent"}}}),nvidia:()=>T.succeed({autoload:!1,options:{}}),vercel:()=>T.succeed({autoload:!1,options:{}}),"google-vertex":T.fnUntraced(function*(Z){let J=yield*$.env(),Y=Z.options?.project??J.GOOGLE_CLOUD_PROJECT??J.GCP_PROJECT??J.GCLOUD_PROJECT,X=String(Z.options?.location??J.GOOGLE_VERTEX_LOCATION??J.GOOGLE_CLOUD_LOCATION??J.VERTEX_LOCATION??"us-central1");if(!Boolean(Y))return{autoload:!1};return{autoload:!0,vars(G){let W=X==="global"?"aiplatform.googleapis.com":`${X}-aiplatform.googleapis.com`;return{...Y&&{GOOGLE_VERTEX_PROJECT:Y},GOOGLE_VERTEX_LOCATION:X,GOOGLE_VERTEX_ENDPOINT:W}},options:{project:Y,location:X,fetch:async(G,W)=>{let{GoogleAuth:K}=await import("./chunk-d6hxsfm6.js").then((m)=>m6(m.default,1)),H=await(await new K().getApplicationDefault()).credential.getAccessToken(),B=new Headers(W?.headers);return B.set("Authorization",`Bearer ${H.token}`),fetch(G,{...W,headers:B})}},async getModel(G,W){let K=String(W).trim();return G.languageModel(K)}}}),"google-vertex-anthropic":T.fnUntraced(function*(){let Z=yield*$.env(),J=Z.GOOGLE_CLOUD_PROJECT??Z.GCP_PROJECT??Z.GCLOUD_PROJECT,Y=Z.GOOGLE_CLOUD_LOCATION??Z.VERTEX_LOCATION??"global";if(!Boolean(J))return{autoload:!1};return{autoload:!0,options:{project:J,location:Y},async getModel(Q,G){let W=String(G).trim();return Q.languageModel(W)}}}),"sap-ai-core":T.fnUntraced(function*(){let Z=yield*$.auth("sap-ai-core"),J=l$(()=>{let Q=IK.get("AICORE_SERVICE_KEY");if(Q)return Q;if(Z?.type==="api")return IK.set("AICORE_SERVICE_KEY",Z.key),process.env.AICORE_SERVICE_KEY=Z.key,Z.key;return}),Y=process.env.AICORE_DEPLOYMENT_ID,X=process.env.AICORE_RESOURCE_GROUP;return{autoload:!!J,options:J?{deploymentId:Y,resourceGroup:X}:{},async getModel(Q,G){return Q(G)}}}),zenmux:()=>T.succeed({autoload:!1,options:{}}),gitlab:T.fnUntraced(function*(Z){let{VERSION:J,isWorkflowModel:Y,discoverWorkflowModels:X}=yield*T.promise(()=>import("./chunk-k5q9px67.js")),Q=(yield*$.get("GITLAB_INSTANCE_URL"))||"https://gitlab.com",G=yield*$.auth(Z.id),W=yield*T.sync(()=>{if(G?.type==="oauth")return G.access;if(G?.type==="api")return G.key;return}),K=W??(yield*$.get("GITLAB_TOKEN")),V=(yield*$.config()).provider?.gitlab,U=yield*B0.directory,H={"User-Agent":`qitqode/${E$} gitlab-ai-provider/${J} (${OZ.platform()} ${OZ.release()}; ${OZ.arch()})`,"anthropic-beta":"context-1m-2025-08-07",...V?.options?.aiGatewayHeaders},B={duo_agent_platform_agentic_chat:!0,duo_agent_platform:!0,...V?.options?.featureFlags};return{autoload:!!K,options:{instanceUrl:Q,apiKey:K,aiGatewayHeaders:H,featureFlags:B},async getModel(z,F,A){if(F.startsWith("duo-workflow-")){let j=typeof A?.workflowRef==="string"?A.workflowRef:void 0,N=Y(F)?F:"duo-workflow",L=typeof A?.workflowDefinition==="string"?A.workflowDefinition:void 0,q=z.workflowChat(N,{featureFlags:B,workflowDefinition:L});if(j)q.selectedModelRef=j;return q}return z.agenticChat(F,{aiGatewayHeaders:H,featureFlags:B})},async discoverModels(){if(!W)return VY.info("gitlab model discovery skipped: no apiKey"),{};try{let z=W,F=()=>G?.type==="api"?{"PRIVATE-TOKEN":z}:{Authorization:`Bearer ${z}`};VY.info("gitlab model discovery starting",{instanceUrl:Q});let A=await X({instanceUrl:Q,getHeaders:F},{workingDirectory:U});if(!A.models.length)return VY.info("gitlab model discovery skipped: no models found",{project:A.project?{id:A.project.id,path:A.project.pathWithNamespace}:null}),{};let j={};for(let N of A.models)if(!Z.models[N.id])j[N.id]={id:s1.make(N.id),providerID:X1.make("gitlab"),name:`Agent Platform (${N.name})`,family:"",api:{id:N.id,url:Q,npm:"gitlab-ai-provider"},status:"active",headers:{},options:{workflowRef:N.ref},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:N.context,output:N.output},capabilities:{temperature:!1,reasoning:!0,attachment:!0,toolcall:!0,input:{text:!0,audio:!1,image:!0,video:!1,pdf:!0},output:{text:!0,audio:!1,image:!1,video:!1,pdf:!1},interleaved:!1},release_date:"",variants:{}};return VY.info("gitlab model discovery complete",{count:Object.keys(j).length,models:Object.keys(j)}),j}catch(z){return VY.warn("gitlab model discovery failed",{error:z}),{}}}}}),"cloudflare-workers-ai":T.fnUntraced(function*(Z){if(Z.options?.baseURL)return{autoload:!1};let J=yield*$.auth(Z.id),Y=yield*$.env(),X=Al(Y,J);if(!X)return{autoload:!1,async getModel(){throw Error("CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>")}};let Q=yield*T.gen(function*(){let G=Y.CLOUDFLARE_API_KEY;if(G)return G;if(J?.type==="api")return J.key;return});return{autoload:!!Q,options:{apiKey:Q,headers:{"User-Agent":`qitqode/${E$} cloudflare-workers-ai (${OZ.platform()} ${OZ.release()}; ${OZ.arch()})`}},async getModel(G,W){return G.languageModel(W)},vars(G){return{CLOUDFLARE_ACCOUNT_ID:X}}}}),"cloudflare-ai-gateway":T.fnUntraced(function*(Z){if(Z.options?.baseURL)return{autoload:!1};let J=yield*$.auth(Z.id),Y=yield*$.env(),X=Al(Y,J),Q=Y.CLOUDFLARE_GATEWAY_ID||(J?.type==="api"?J.metadata?.gatewayId:void 0);if(!X||!Q){let z=[!X?"CLOUDFLARE_ACCOUNT_ID":void 0,!Q?"CLOUDFLARE_GATEWAY_ID":void 0].filter((F)=>Boolean(F));return{autoload:!1,async getModel(){throw Error(`${z.join(" and ")} missing. Set with: ${z.map((F)=>`export ${F}=<value>`).join(" && ")}`)}}}let G=yield*T.gen(function*(){let z=Y.CLOUDFLARE_API_TOKEN||Y.CF_AIG_TOKEN;if(z)return z;if(J?.type==="api")return J.key;return});if(!G)throw Error("CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. Set it via environment variable or run `qitqode auth cloudflare-ai-gateway`.");let{createAiGateway:W}=yield*T.promise(()=>import("./chunk-qey1efpx.js")),{createUnified:K}=yield*T.promise(()=>import("./chunk-c2kkv619.js")),U={metadata:l$(()=>{if(Z.options?.metadata)return Z.options.metadata;try{return JSON.parse(Z.options?.headers?.["cf-aig-metadata"])}catch{return}}),cacheTtl:Z.options?.cacheTtl,cacheKey:Z.options?.cacheKey,skipCache:Z.options?.skipCache,collectLog:Z.options?.collectLog,headers:{"User-Agent":`qitqode/${E$} cloudflare-ai-gateway (${OZ.platform()} ${OZ.release()}; ${OZ.arch()})`}},H=W({accountId:X,gateway:Q,apiKey:G,...Object.values(U).some((z)=>z!==void 0)?{options:U}:{}}),B=K();return{autoload:!0,async getModel(z,F,A){return H(B(F))},options:{}}}),cerebras:()=>T.succeed({autoload:!1,options:{headers:{"X-Cerebras-3rd-Party-Integration":"qitqode"}}}),kilo:()=>T.succeed({autoload:!1,options:{}})}}import{pathToFileURL as ZN0}from"url";var fA=E0.create({service:"provider.sdk-runtime"});async function Dl($,Z,J){try{let Y=[];try{const W=CK(Y,fA.time("getSDK",{providerID:$.providerID}),0);let K=Z.providers[$.providerID];let V={...K.options};if($.providerID==="google-vertex"&&!$.api.npm.includes("@ai-sdk/openai-compatible"))delete V.fetch;if($.api.npm.includes("@ai-sdk/openai-compatible")&&V.includeUsage!==!1)V.includeUsage=!0;let U=l$(()=>{let R=typeof V.baseURL==="string"&&V.baseURL!==""?V.baseURL:$.api.url;if(!R)return;let w=Z.varsLoaders[$.providerID];if(w){let I=w(V);for(let[_,E]of Object.entries(I)){let f="${"+_+"}";R=R.replaceAll(f,E)}}return R});if(U!==void 0)V.baseURL=U;if(V.apiKey===void 0&&typeof K.key==="string")V.apiKey=K.key;if($.headers)V.headers={...V.headers,...$.headers};let H=V.fetch;delete V.fetch;let B=V4.fast(JSON.stringify({providerID:$.providerID,npm:$.api.npm,options:V}));let z=Z.sdk.get(B);if(z)return z;let F=V.chunkTimeout;let A=typeof F==="number"?F:PK;delete V.chunkTimeout;V.fetch=async(R,w)=>{let I=H??fetch,_=w??{},E=typeof A==="number"&&A>0?new AbortController:void 0,f=[];if(_.signal)f.push(_.signal);if(E)f.push(E.signal);if(V.timeout!==void 0&&V.timeout!==null&&V.timeout!==!1)f.push(AbortSignal.timeout(V.timeout));let b=f.length===0?null:f.length===1?f[0]:AbortSignal.any(f);if(b)_.signal=b;if($.api.npm==="@ai-sdk/openai"&&_.body&&_.method==="POST"){let k=JSON.parse(_.body);if(!($.providerID.includes("azure")&&k.store===!0)&&Array.isArray(k.input)){for(let p of k.input)if("id"in p)delete p.id;_.body=JSON.stringify(k)}}let y=await I(R,{..._,timeout:!1});if(!E)return y;return zl(y,A,E)};let j=jl[$.api.npm];if(j){fA.info("using bundled provider",{providerID:$.providerID,pkg:$.api.npm});let w=(await j())({name:$.providerID,...V});return Z.sdk.set(B,w),w}let N;if(!$.api.npm.startsWith("file://")){let R=await q6.add($.api.npm);if(!R.entrypoint)throw Error(`Package ${$.api.npm} has no import entrypoint`);N=R.entrypoint}else fA.info("loading local provider",{pkg:$.api.npm}),N=$.api.npm;let L=N.startsWith("file://")?N:ZN0(N).href;let q=await import(L);let M=q[Object.keys(q).find((R)=>R.startsWith("create"))];let C=M({name:$.providerID,...V});Z.sdk.set(B,C);return C}catch(X){var Q=X,G=1}finally{EK(Y,Q,G)}}catch(W){throw new TK({providerID:$.providerID},{cause:W})}}function wl($){let Z={};function J(Y,X){let Q=Z[Y];if(Q){Z[Y]=N1(Q,X);return}let G=$[Y];if(!G)return;Z[Y]=N1(G,X)}return{database:$,providers:Z,mergeProvider:J}}function Ll($){if($.enabled&&!$.enabled.has($.providerID))return!1;if($.disabled.has($.providerID))return!1;return!0}function Tl($,Z){let J=$.env.map((Y)=>Z[Y]).find(Boolean);if(!J)return;return{source:"env",key:$.env.length===1?J:void 0}}function Rl($){if($.type!=="api")return;return{source:"api",key:$.key}}function kA($){return $.hasProvider?{options:$.options??{}}:{source:"custom",options:$.options??{}}}var JN0=E0.create({service:"provider.discovery.filter"});function Pl($){for(let[Z,J]of Object.entries($.providers)){let Y=X1.make(Z);if(!$.isAllowed(Y)){delete $.providers[Y];continue}let X=$.overrides[Y];for(let[Q,G]of Object.entries(J.models)){if(G.api.id=G.api.id??G.id??Q,Q==="gpt-5-chat-latest"||Y===X1.openrouter&&Q==="openai/gpt-5-chat")delete J.models[Q];if(G.status==="alpha"&&!$.experimentalModels)delete J.models[Q];if(G.status==="deprecated")delete J.models[Q];if(X?.blacklist&&X.blacklist.includes(Q)||X?.whitelist&&!X.whitelist.includes(Q))delete J.models[Q];G.variants=v6(G5(G),(K)=>K);let W=X?.models?.[Q]?.variants;if(W&&G.variants){let K=N1(G.variants,W);G.variants=v6(bK(K,(V)=>!V.disabled),(V)=>_K(V,["disabled"]))}}if(Object.keys(J.models).length===0){delete $.providers[Y];continue}JN0.info("found",{providerID:Y})}return $.providers}var YN0=E0.create({service:"provider.discovery.config"});function Il($){for(let[Z,J]of $.configProviders){let Y=$.database[Z],X={id:X1.make(Z),name:J.name??Y?.name??Z,env:J.env??Y?.env??[],options:N1(Y?.options??{},J.options??{}),source:"config",models:Y?.models??{}};for(let[Q,G]of Object.entries(J.models??{})){let W=X.models[G.id??Q],K=G.id??W?.api.id??Q,V=G.provider?.npm??J.npm??W?.api.npm??$.modelsDev[Z]?.npm??"@ai-sdk/openai-compatible",U=l$(()=>{if(G.name)return G.name;if(G.id&&G.id!==Q)return Q;return W?.name??Q}),H={id:s1.make(Q),api:{id:K,npm:V,url:G.provider?.api??J?.api??W?.api.url??$.modelsDev[Z]?.api??""},status:G.status??W?.status??"active",name:U,providerID:X1.make(Z),capabilities:{temperature:G.temperature??W?.capabilities.temperature??!1,reasoning:G.reasoning??W?.capabilities.reasoning??!1,attachment:G.attachment??W?.capabilities.attachment??!1,toolcall:G.tool_call??W?.capabilities.toolcall??!0,input:{text:G.modalities?.input?.includes("text")??W?.capabilities.input.text??!0,audio:G.modalities?.input?.includes("audio")??W?.capabilities.input.audio??!1,image:G.modalities?.input?.includes("image")??W?.capabilities.input.image??!1,video:G.modalities?.input?.includes("video")??W?.capabilities.input.video??!1,pdf:G.modalities?.input?.includes("pdf")??W?.capabilities.input.pdf??!1},output:{text:G.modalities?.output?.includes("text")??W?.capabilities.output.text??!0,audio:G.modalities?.output?.includes("audio")??W?.capabilities.output.audio??!1,image:G.modalities?.output?.includes("image")??W?.capabilities.output.image??!1,video:G.modalities?.output?.includes("video")??W?.capabilities.output.video??!1,pdf:G.modalities?.output?.includes("pdf")??W?.capabilities.output.pdf??!1},interleaved:G.interleaved??W?.capabilities.interleaved??(!W&&V==="@ai-sdk/openai-compatible"&&K.includes("deepseek")?{field:"reasoning_content"}:!1)},cost:{input:G?.cost?.input??W?.cost?.input??0,output:G?.cost?.output??W?.cost?.output??0,cache:{read:G?.cost?.cache_read??W?.cost?.cache.read??0,write:G?.cost?.cache_write??W?.cost?.cache.write??0}},options:N1(W?.options??{},G.options??{}),limit:{context:(()=>{let z=G.limit?.context??W?.limit?.context;if(z!==void 0)return z;let F=`${Z}/${Q}`;if(!_A.has(F))_A.add(F),YN0.warn("limit.context not configured and not found in models.dev",{providerID:Z,modelID:Q,defaulting_to:bA,fix:`Set limit.context explicitly in qitqode.json under provider.${Z}.models.${Q}`});return bA})(),input:G.limit?.input??W?.limit?.input,output:G.limit?.output??W?.limit?.output??0},headers:N1(W?.headers??{},G.headers??{}),family:G.family??W?.family??"",release_date:G.release_date??W?.release_date??"",cachePromptTTL:G.cachePromptTTL??W?.cachePromptTTL,variants:{}},B=N1(G5(H),G.variants??{});H.variants=v6(bK(B,(z)=>!z.disabled),(z)=>_K(z,["disabled"])),X.models[Q]=H}$.database[Z]=X}}var SK=E0.create({service:"provider.discovery"});function El($){let{config:Z,auth:J,env:Y,plugin:X}=$;return T.gen(function*(){let E=[];try{const Q=CK(E,SK.time("state"),0);let G=yield*T7.make();let W=yield*Z.get();let K=yield*T.promise(()=>Cl());let V=v6(K,wK);V[Q9.id]=Q9;let U=wl(V);let{providers:H,mergeProvider:B}=U;let z=new Map;let F={};let A={};let j=new Map;let N={};let L={auth:(k)=>J.get(k).pipe(T.orDie),config:()=>Z.get(),env:()=>Y.all(),get:(k)=>Y.get(k)};SK.info("init");let q=yield*X.list();let M=Object.entries(W.provider??{});let C=new Set(W.disabled_providers??[]);let R=W.enabled_providers?new Set(W.enabled_providers):null;let w=(k)=>Ll({providerID:k,enabled:R,disabled:C});Il({database:V,modelsDev:K,configProviders:M});if(!b0.QITQODE_DISABLE_PROVIDER_ENV){let k=yield*Y.all();for(let[g,d]of Object.entries(V)){let p=X1.make(g);if(C.has(p))continue;let t=Tl(d,k);if(t)B(p,t)}}let I=yield*J.all().pipe(T.orDie);for(let[k,g]of Object.entries(I)){let d=X1.make(k);if(C.has(d))continue;let p=Rl(g);if(p)B(d,p)}for(let k of q){if(!k.auth)continue;let g=X1.make(k.auth.provider);if(C.has(g))continue;if(!(yield*J.get(g).pipe(T.orDie)))continue;if(!k.auth.loader)continue;let t=(yield*T.promise(()=>k.auth.loader(()=>G.promise(J.get(g).pipe(T.orDie)),V[k.auth.provider])))??{};B(g,kA({options:t,hasProvider:Boolean(H[g])}))}for(let[k,g]of Object.entries(Ml(L))){let d=X1.make(k);if(C.has(d))continue;let p=V[d];if(!p){SK.error("Provider does not exist in model list "+d);continue}let t=yield*g(p);if(t&&(t.autoload||H[d])){if(t.getModel)F[d]=t.getModel;if(t.vars)A[d]=t.vars;if(t.discoverModels)N[d]=t.discoverModels;let r=t.options??{};B(d,kA({options:r,hasProvider:Boolean(H[d])}))}}for(let[k,g]of M){let d=X1.make(k),p={source:"config"};if(g.env)p.env=g.env;if(g.name)p.name=g.name;if(g.options)p.options=g.options;B(d,p)}let _=X1.make("gitlab");if(N[_]&&H[_]&&w(_))yield*T.promise(async()=>{try{let k=await N[_]();for(let[g,d]of Object.entries(k))if(!H[_].models[g])H[_].models[g]=d}catch(k){SK.warn("state discovery error",{id:"gitlab",error:k})}});for(let k of q){let g=k.provider,d=g?.models;if(!g||!d)continue;let p=X1.make(g.id);if(C.has(p))continue;let t=H[p];if(!t)continue;let r=yield*J.get(p).pipe(T.orDie);t.models=yield*T.promise(async()=>{let G0=await d(t,{auth:r});return Object.fromEntries(Object.entries(G0).map(([O0,h0])=>[O0,{...h0,id:s1.make(O0),providerID:p}]))})}Pl({providers:H,overrides:W.provider??{},isAllowed:w,experimentalModels:b0.QITQODE_ENABLE_EXPERIMENTAL_MODELS});return{models:z,providers:H,sdk:j,modelLoaders:F,varsLoaders:A}}catch(f){var b=f,y=1}finally{EK(E,b,y)}})}var QN0=O.Struct({id:O.String,url:O.String,npm:O.String}),bl=O.Struct({text:O.Boolean,audio:O.Boolean,image:O.Boolean,video:O.Boolean,pdf:O.Boolean}),GN0=O.Union([O.Boolean,O.Struct({field:O.Literals(["reasoning_content","reasoning_details"])})]),WN0=O.Struct({temperature:O.Boolean,reasoning:O.Boolean,attachment:O.Boolean,toolcall:O.Boolean,input:bl,output:bl,interleaved:GN0}),_l=O.Struct({read:O.Number,write:O.Number}),KN0=O.Struct({input:O.Number,output:O.Number,cache:_l,experimentalOver200K:O.optional(O.Struct({input:O.Number,output:O.Number,cache:_l}))}),VN0=O.Struct({context:O.Number,input:O.optional(O.Number),output:O.Number}),vA=O.Struct({id:s1,providerID:X1,api:QN0,name:O.String,family:O.optional(O.String),capabilities:WN0,cost:KN0,limit:VN0,status:O.Literals(["alpha","beta","deprecated","active"]),options:O.Record(O.String,O.Any),headers:O.Record(O.String,O.String),release_date:O.String,variants:O.optional(O.Record(O.String,O.Record(O.String,O.Any))),cacheTTL:O.optional(O.Number),cachePromptTTL:O.optional(O.Literals(["5m","1h"]))}).annotate({identifier:"Model"}).pipe(u0(($)=>({zod:w0($)}))),fK=O.Struct({id:X1,name:O.String,source:O.Literals(["env","config","custom","api"]),env:O.Array(O.String),key:O.optional(O.String),options:O.Record(O.String,O.Any),models:O.Record(O.String,vA)}).annotate({identifier:"Provider"}).pipe(u0(($)=>({zod:w0($)}))),Sl=O.Record(O.String,O.String),fl=O.Struct({all:O.Array(fK),default:Sl,connected:O.Array(O.String)}).pipe(u0(($)=>({zod:w0($)}))),kl=O.Struct({providers:O.Array(fK),default:Sl}).pipe(u0(($)=>({zod:w0($)})));async function xl($=yl){return F8.loadLiveRatings($)}function hl($){F8.mergeLiveTierRatings($)}class kK extends S1.Service()("@qitqode/Provider"){}var HN0=T0.effect(kK,T.gen(function*(){let $=yield*D$.Service,Z=yield*X8.Service,J=yield*k8.Service,Y=yield*l6.Service,X=yield*AZ.Service;F8.beginTierRatingsLoad();let[Q,G]=yield*T.promise(()=>Promise.all([vl(),xl()]));F8.mergeLiveTiers(Q),hl(G),Vl();let W=yield*B0.make(()=>El({config:Z,auth:J,env:Y,plugin:X})),K=T.fn("Provider.list")(()=>B0.use(W,(N)=>N.providers)),V=Bl({getState:()=>B0.get(W),config:Z,readRecent:()=>$.readJson(UN0.join(F0.Path.state,"model.json"))}),{getProvider:U,getModel:H,closest:B,getSmallModel:z,defaultModel:F,resolveModelRef:A}=V,j=T.fn("Provider.getLanguage")(function*(N){let L=yield*B0.get(W),q=yield*Y.all(),M=`${N.providerID}/${N.id}`;if(L.models.has(M))return L.models.get(M);return yield*T.promise(async()=>{let C=L.providers[N.providerID],R=await Dl(N,L,q);try{let w=L.modelLoaders[N.providerID]?await L.modelLoaders[N.providerID](R,N.api.id,{...C.options,...N.options}):R.languageModel(N.api.id);return L.models.set(M,w),w}catch(w){if(w instanceof XH)throw new KY({modelID:N.id,providerID:N.providerID},{cause:w});throw w}})});return kK.of({list:K,getProvider:U,getModel:H,getLanguage:j,closest:B,getSmallModel:z,defaultModel:F,resolveModelRef:A})})),BN0=T0.suspend(()=>HN0.pipe(T0.provide(D$.defaultLayer),T0.provide(l6.defaultLayer),T0.provide(X8.defaultLayer),T0.provide(k8.defaultLayer),T0.provide(AZ.defaultLayer)));var sl={};F1(sl,{layer:()=>ol,defaultLayer:()=>NN0,ValidationFailed:()=>nl,Service:()=>vK,OauthMissing:()=>pl,OauthCodeMissing:()=>cl,OauthCallbackFailed:()=>il,Methods:()=>ll,Method:()=>yA,CallbackInput:()=>jN0,AuthorizeInput:()=>qN0,Authorization:()=>dl});var ml=O.Struct({key:O.String,op:O.Literals(["eq","neq"]),value:O.String}),zN0=O.Struct({type:O.Literal("text"),key:O.String,message:O.String,placeholder:O.optional(O.String),when:O.optional(ml)}),FN0=O.Struct({label:O.String,value:O.String,hint:O.optional(O.String)}),AN0=O.Struct({type:O.Literal("select"),key:O.String,message:O.String,options:O.Array(FN0),when:O.optional(ml)}),ON0=O.Union([zN0,AN0]);class yA extends O.Class("ProviderAuthMethod")({type:O.Literals(["oauth","api"]),label:O.String,prompts:O.optional(O.Array(ON0))}){static zod=w0(this)}var ll=O.Record(O.String,O.Array(yA)).pipe(u0(($)=>({zod:w0($)})));class dl extends O.Class("ProviderAuthAuthorization")({url:O.String,method:O.Literals(["auto","code"]),instructions:O.String}){static zod=w0(this)}var qN0=O.Struct({method:O.Number.annotate({description:"Auth method index"}),inputs:O.optional(O.Record(O.String,O.String)).annotate({description:"Prompt inputs"})}).pipe(u0(($)=>({zod:w0($)}))),jN0=O.Struct({method:O.Number.annotate({description:"Auth method index"}),code:O.optional(O.String).annotate({description:"OAuth authorization code"})}).pipe(u0(($)=>({zod:w0($)}))),pl=j1.create("ProviderAuthOauthMissing",P.object({providerID:X1.zod})),cl=j1.create("ProviderAuthOauthCodeMissing",P.object({providerID:X1.zod})),il=j1.create("ProviderAuthOauthCallbackFailed",P.object({})),nl=j1.create("ProviderAuthValidationFailed",P.object({field:P.string(),message:P.string()}));class vK extends S1.Service()("@qitqode/ProviderAuth"){}var ol=T0.effect(vK,T.gen(function*(){let $=yield*k8.Service,Z=yield*AZ.Service,J=yield*B0.make(T.fn("ProviderAuth.state")(function*(){let W=yield*Z.list();return{hooks:y7.fromEntries(ul.filterMap(W,(K)=>K.auth?.provider!==void 0?v7.succeed([X1.make(K.auth.provider),K.auth]):v7.failVoid)),pending:new Map}})),Y=O.decodeUnknownSync(ll),X=T.fn("ProviderAuth.methods")(function*(){let W=(yield*B0.get(J)).hooks;return Y(y7.map(W,(K)=>K.methods.map((V)=>({type:V.type,label:V.label,prompts:V.prompts?.map((U)=>{if(U.type==="select")return{type:"select",key:U.key,message:U.message,options:U.options,when:U.when};return{type:"text",key:U.key,message:U.message,placeholder:U.placeholder,when:U.when}})}))))}),Q=T.fn("ProviderAuth.authorize")(function*(W){let{hooks:K,pending:V}=yield*B0.get(J),U=K[W.providerID].methods[W.method];if(U.type!=="oauth")return;if(U.prompts&&W.inputs){for(let B of U.prompts)if(B.type==="text"&&B.validate&&W.inputs[B.key]!==void 0){let z=B.validate(W.inputs[B.key]);if(z)return yield*T.fail(new nl({field:B.key,message:z}))}}let H=yield*T.promise(()=>U.authorize(W.inputs));return V.set(W.providerID,H),{url:H.url,method:H.method,instructions:H.instructions}}),G=T.fn("ProviderAuth.callback")(function*(W){let V=(yield*B0.get(J)).pending.get(W.providerID);if(!V)return yield*T.fail(new pl({providerID:W.providerID}));if(V.method==="code"&&!W.code)return yield*T.fail(new cl({providerID:W.providerID}));let U=yield*T.promise(()=>V.method==="code"?V.callback(W.code):V.callback(W.code));if(!U||U.type!=="success")return yield*T.fail(new il({}));if("key"in U)yield*$.set(W.providerID,{type:"api",key:U.key,..."metadata"in U&&U.metadata?{metadata:U.metadata}:{}});if("refresh"in U){let{type:H,provider:B,refresh:z,access:F,expires:A,...j}=U;yield*$.set(W.providerID,{type:"oauth",access:F,refresh:z,expires:A,...j})}});return vK.of({methods:X,authorize:Q,callback:G})})),NN0=T0.suspend(()=>ol.pipe(T0.provide(k8.defaultLayer),T0.provide(AZ.defaultLayer)));var W9={};F1(W9,{parseStreamError:()=>RN0,parseAPICallError:()=>PN0});import{STATUS_CODES as rl}from"http";var MN0=[/prompt is too long/i,/input is too long for requested model/i,/exceeds the context window/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 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,/context[_ ]length[_ ]exceeded/i,/request entity too large/i,/context length is only \d+ tokens/i,/input length.*exceeds.*context length/i,/prompt too long; exceeded (?:max )?context length/i,/too large for model with \d+ maximum context length/i,/model_context_window_exceeded/i];function DN0($){let Z=$.statusCode;if(!Z)return $.isRetryable;return Z===404||$.isRetryable}function wN0($){if(MN0.some((Z)=>Z.test($)))return!0;return/^4(00|13)\s*(status code)?\s*\(no body\)/i.test($)}function LN0($){if(!$||!/^\s*[\[{]/.test($))return!1;try{return JSON.parse($),!1}catch(Z){let J=0,Y=!1,X=!1;for(let Q of $){if(Y){if(X)X=!1;else if(Q==="\\")X=!0;else if(Q==='"')Y=!1;continue}if(Q==='"')Y=!0;else if(Q==="{"||Q==="[")J++;else if(Q==="}"||Q==="]")J--;if(J<0)return!1}return Y||J>0||/unexpected end|end of json|unterminated string/i.test(String(Z))}}function TN0($,Z){return l$(()=>{let J=Z.message;if(J===""){if(Z.responseBody)return Z.responseBody;if(Z.statusCode){let X=rl[Z.statusCode];if(X)return X}return"Unknown error"}if(!Z.responseBody||Z.statusCode&&J!==rl[Z.statusCode])return J;try{let X=JSON.parse(Z.responseBody),Q=X.message||X.detail||X.error?.message||X.error;if(Q&&typeof Q==="string")return`${J}: ${Q.slice(0,300)}`;if(Array.isArray(Q)&&Q.length>0){let G=Q[0],W=typeof G?.msg==="string"?G.msg:typeof G?.message==="string"?G.message:typeof G==="string"?G:void 0;if(W)return`${J}: ${W.slice(0,300)}`}}catch{}if(/^\s*<!doctype|^\s*<html/i.test(Z.responseBody)){if(Z.statusCode===401)return"Unauthorized: request was blocked by a gateway or proxy. Your authentication token may be missing or expired \u2014 try running `qitqode auth login <your provider URL>` to re-authenticate.";if(Z.statusCode===403)return"Forbidden: request was blocked by a gateway or proxy. You may not have permission to access this resource \u2014 check your account and provider settings.";return J}let Y=Z.responseBody.length>300?Z.responseBody.slice(0,300)+"\u2026":Z.responseBody;return`${J}: ${Y}`}).trim()}function al($){if(typeof $==="string")try{let Z=JSON.parse($);if(Z&&typeof Z==="object")return Z;return}catch{return}if(typeof $==="object"&&$!==null)return $;return}function RN0($){let Z=al($);if(!Z)return;let J=JSON.stringify(Z);if(Z.type!=="error")return;switch(Z?.error?.code){case"context_length_exceeded":return{type:"context_overflow",message:"Input exceeds context window of this model",responseBody:J};case"insufficient_quota":return{type:"api_error",message:"Quota exceeded. Check your plan and billing details.",isRetryable:!1,responseBody:J};case"usage_not_included":return{type:"api_error",message:"To use Codex with your ChatGPT plan, upgrade to Plus: https://chatgpt.com/explore/plus.",isRetryable:!1,responseBody:J};case"invalid_prompt":return{type:"api_error",message:typeof Z?.error?.message==="string"?Z?.error?.message:"Invalid prompt.",isRetryable:!1,responseBody:J}}}function PN0($){let Z=TN0($.providerID,$.error),J=al($.error.responseBody),Y=LN0($.error.responseBody);if(wN0(Z)||$.error.statusCode===413||J?.error?.code==="context_length_exceeded")return{type:"context_overflow",message:Z,responseBody:$.error.responseBody};let X=$.error.url?{url:$.error.url}:void 0;return{type:"api_error",message:Y?"The model connection ended before the response completed.":Z,statusCode:$.error.statusCode,isRetryable:Y||($.providerID.startsWith("openai")?DN0($.error):$.error.isRetryable),category:Y?"stream_truncated":void 0,responseHeaders:$.error.responseHeaders,responseBody:$.error.responseBody,metadata:X}}function xA($,Z){switch(!0){case($ instanceof DOMException&&$.name==="AbortError"):return new f5({message:$.message},{cause:$}).toObject();case O4.isInstance($):{let J=$.lastError??$.errors[$.errors.length-1];if(J!==void 0&&J!==$)return xA(J,Z);return new L6({message:$.message,isRetryable:!0},{cause:$}).toObject()}case U4.isInstance($):return $;case YH.isInstance($):return new H4({providerID:Z.providerID,message:$.message},{cause:$}).toObject();case $?.code==="ECONNRESET":return new L6({message:"Connection reset by server",isRetryable:!0,metadata:{code:$.code??"",syscall:$.syscall??"",message:$.message??""}},{cause:$}).toObject();case($ instanceof Error&&$.code==="ZlibError"):if(Z.aborted)return new f5({message:$.message},{cause:$}).toObject();return new L6({message:"Response decompression failed",isRetryable:!0,metadata:{code:$.code,message:$.message}},{cause:$}).toObject();case FX.isInstance($):{let J=W9.parseAPICallError({providerID:Z.providerID,error:$});if(J.type==="context_overflow")return new GX({message:J.message,responseBody:J.responseBody},{cause:$}).toObject();return new L6({message:J.message,statusCode:J.statusCode,isRetryable:J.isRetryable,category:J.category,outputBudgetRecoveryAvailable:void 0,outputBudgetRecoveryTokens:void 0,diagnostic:UY($),responseHeaders:J.responseHeaders,responseBody:J.responseBody,metadata:J.metadata},{cause:$}).toObject()}case($ instanceof Error&&(typeof $.status==="number"||typeof $.category==="string"&&typeof $.retryable==="boolean")):{let J=$.status,Y=$.retryable===!0;return new L6({message:V6($),statusCode:J,isRetryable:Y,category:$.category,upstreamCode:$.upstreamCode,requestId:$.requestId,outputBudgetRecoveryAvailable:$.outputBudgetRecoveryAvailable,outputBudgetRecoveryTokens:$.outputBudgetRecoveryTokens,diagnostic:UY($)},{cause:$}).toObject()}case $ instanceof Error:return new j1.Unknown({message:V6($),diagnostic:UY($)},{cause:$}).toObject();default:try{let J=W9.parseStreamError($);if(J){if(J.type==="context_overflow")return new GX({message:J.message,responseBody:J.responseBody},{cause:$}).toObject();return new L6({message:J.message,isRetryable:J.isRetryable,diagnostic:UY($),responseBody:J.responseBody},{cause:$}).toObject()}}catch{}return new j1.Unknown({message:V6($),diagnostic:UY($)},{cause:$}).toObject()}}var BY={};F1(BY,{layer:()=>Xd,defaultLayer:()=>kN0,Service:()=>yK,ActorRegistry:()=>BY});var _1=g6("actor_registry",{session_id:w1().$type().notNull().references(()=>I1.id,{onDelete:"cascade"}),actor_id:w1().notNull(),mode:w1().$type().notNull(),parent_actor_id:w1(),status:w1().$type().notNull(),last_outcome:w1().$type(),lifecycle:w1().$type().notNull(),agent:w1().notNull(),description:w1().notNull(),context_mode:w1().$type().notNull(),context_watermark:w1().$type(),background:j8({mode:"boolean"}).notNull(),tools:w1({mode:"json"}).$type(),last_turn_time:j8().notNull(),turn_count:j8().notNull().default(0),last_error:w1(),time_completed:j8(),...xY},($)=>[k9({columns:[$.session_id,$.actor_id]}),K9("actor_registry_session_agent_idx").on($.session_id,$.agent),K9("actor_registry_session_parent_idx").on($.session_id,$.parent_actor_id),K9("actor_registry_status_idx").on($.status),K9("actor_registry_status_last_turn_idx").on($.status,$.last_turn_time)]);var hA=P.enum(["pending","running","idle"]),gA=P.enum(["success","failure","cancelled"]),IN0=P.enum(["ephemeral","persistent"]),CN0=P.enum(["none","state","full"]),uA=P.enum(["peer","subagent","main"]),EN0=P.union([P.array(P.string()).readonly(),P.literal("INHERIT")]),Qd0=P.object({sessionID:r0.zod,actorID:P.string(),mode:uA,parentActorID:P.string().optional(),status:hA,lastOutcome:gA.optional(),lifecycle:IN0,agent:P.string(),description:P.string(),contextMode:CN0,contextWatermark:i1.zod.optional(),background:P.boolean(),tools:EN0.optional(),lastTurnTime:P.number(),turnCount:P.number(),lastError:P.string().optional(),time:P.object({created:P.number(),updated:P.number(),completed:P.number().optional()})}).meta({ref:"Actor"});var tl=L1.define("actor.registered",P.object({sessionID:r0.zod,actorID:P.string(),mode:uA,parentActorID:P.string().optional(),description:P.string(),agent:P.string(),background:P.boolean()})),el=L1.define("actor.status",P.object({sessionID:r0.zod,actorID:P.string(),status:hA,lastOutcome:gA.optional(),turnCount:P.number(),lastTurnTime:P.number(),error:P.string().optional()})),$d=L1.define("actor.stuck",P.object({sessionID:r0.zod,actorID:P.string(),description:P.string(),lastTurnTime:P.number(),stuckDuration:P.number()})),Hd0=L1.define("writer.cache_perf",P.object({sessionID:r0.zod,writerActorID:P.string(),status:P.enum(["completed","failed"]),total_input_tokens:P.number(),cache_read_tokens:P.number(),cache_write_tokens:P.number(),cache_hit_rate:P.number(),num_llm_calls:P.number()})),Bd0=L1.define("inbox.arrived",P.object({receiverSessionID:r0.zod,receiverActorID:P.string(),senderSessionID:r0.zod.optional(),senderActorID:P.string().optional(),inboxID:P.string(),type:P.string()}));var Zd=new Set(["checkpoint-writer","dream","distill"]);var _N0=E0.create({service:"actor.registry"}),SN0=300000,fN0=60000;function HY($){return{sessionID:$.session_id,actorID:$.actor_id,mode:$.mode,parentActorID:$.parent_actor_id??void 0,status:$.status,lastOutcome:$.last_outcome??void 0,lifecycle:$.lifecycle,agent:$.agent,description:$.description,contextMode:$.context_mode,contextWatermark:$.context_watermark??void 0,background:Boolean($.background),tools:$.tools??void 0,lastTurnTime:$.last_turn_time,turnCount:$.turn_count,lastError:$.last_error??void 0,time:{created:$.time_created,updated:$.time_updated,completed:$.time_completed??void 0}}}class yK extends S1.Service()("@qitqode/ActorRegistry"){}var Xd=T0.effect(yK,T.gen(function*(){let $=yield*l1.Service,Z=new Map,J=T.fn("ActorRegistry.register")(function*(A){let j=Date.now(),N={session_id:A.sessionID,actor_id:A.actorID,mode:A.mode,parent_actor_id:A.parentActorID??null,status:"pending",last_outcome:null,lifecycle:A.lifecycle,agent:A.agent,description:A.description,context_mode:A.contextMode,context_watermark:A.contextWatermark??null,background:A.background,tools:A.tools??null,last_turn_time:j,turn_count:0,last_error:null,time_completed:null,time_created:j,time_updated:j};return yield*T.sync(()=>W1.use((L)=>{try{L.insert(_1).values(N).run()}catch(q){if(typeof q==="object"&&q!==null&&"code"in q&&typeof q.code==="string"&&(q.code==="SQLITE_CONSTRAINT_PRIMARYKEY"||q.code==="SQLITE_CONSTRAINT_UNIQUE")||q instanceof Error&&q.message.toLowerCase().includes("unique constraint"))throw Error(`Actor ID collision: '${A.actorID}' already exists in session '${A.sessionID}'.`);throw q}})),yield*$.publish(tl,{sessionID:A.sessionID,actorID:A.actorID,mode:A.mode,parentActorID:A.parentActorID,description:A.description,agent:A.agent,background:A.background}),HY(N)}),Y=T.fnUntraced(function*(A,j){return yield*T.sync(()=>W1.use((N)=>N.select().from(_1).where(O$(m0(_1.session_id,A),m0(_1.actor_id,j))).get()))}),X=T.fn("ActorRegistry.updateStatus")(function*(A,j,N){let L=Date.now(),q=N.status==="idle"&&N.lastOutcome!==void 0,M={status:N.status,time_updated:L,...q?{time_completed:L}:{}};if(N.lastOutcome!==void 0)M.last_outcome=N.lastOutcome;if(N.lastError!==void 0)M.last_error=N.lastError;else if(N.lastOutcome!==void 0&&N.lastOutcome!=="failure")M.last_error=null;yield*T.sync(()=>W1.use((R)=>R.update(_1).set(M).where(O$(m0(_1.session_id,A),m0(_1.actor_id,j))).run()));let C=yield*Y(A,j);if(!C)return;yield*$.publish(el,{sessionID:A,actorID:j,status:C.status,...C.last_outcome?{lastOutcome:C.last_outcome}:{},turnCount:C.turn_count,lastTurnTime:C.last_turn_time,...C.last_error?{error:C.last_error}:{}})}),Q=T.fn("ActorRegistry.updateTurn")(function*(A,j){let N=Date.now();yield*T.sync(()=>W1.use((L)=>L.update(_1).set({last_turn_time:N,turn_count:Jd`${_1.turn_count} + 1`,time_updated:N}).where(O$(m0(_1.session_id,A),m0(_1.actor_id,j))).run()))}),G=T.fn("ActorRegistry.get")(function*(A,j){let N=yield*Y(A,j);return N?HY(N):void 0}),W=T.fn("ActorRegistry.listBySession")(function*(A){return(yield*T.sync(()=>W1.use((N)=>N.select().from(_1).where(m0(_1.session_id,A)).all()))).map(HY)}),K=T.fn("ActorRegistry.listActive")(function*(){return(yield*T.sync(()=>W1.use((j)=>j.select().from(_1).where(O$(k5(_1.status,["pending","running"]),m0(_1.background,!0))).all()))).map(HY)}),V=T.fn("ActorRegistry.listByParent")(function*(A,j){return(yield*T.sync(()=>W1.use((L)=>L.select().from(_1).where(O$(m0(_1.session_id,A),m0(_1.parent_actor_id,j))).all()))).map(HY)}),U=T.fn("ActorRegistry.renderForAgent")(function*(A){let N=(yield*W(A)).filter((M)=>M.background&&(M.status==="pending"||M.status==="running"));if(N.length===0)return"";let L=[];L.push("## Active Actors"),L.push(""),L.push(`You have ${N.length} background actor(s) registered. Interact via the \`actor\` tool.`),L.push("");let q=Date.now();for(let M of N){let C=q-M.lastTurnTime,R=C<60000?`${Math.floor(C/1000)}s`:`${Math.floor(C/60000)}m`;L.push(`- actor_id: ${M.actorID} (${M.status}, last activity ${R} ago)`),L.push(` description: ${M.description}`),L.push(` agent: ${M.agent}`)}return L.join(`
802
802
  `)}),H=T.fn("ActorRegistry.agentTypeFor")(function*(A,j){if(j==="main")return"main";return(yield*G(A,j))?.agent??"main"}),B=T.fn("ActorRegistry.isSystemSpawned")(function*(A,j){if(j==="main")return!1;let N=yield*G(A,j);if(!N)return!1;return Zd.has(N.agent)}),z=T.fn("ActorRegistry.allocateActorID")(function*(A,j){let N=`${A}:${j}`,L=`${j}-`;if(!Z.has(N)){let M=yield*T.sync(()=>W1.use((C)=>C.select({actor_id:_1.actor_id}).from(_1).where(O$(m0(_1.session_id,A),m0(_1.agent,j))).all()));if(!Z.has(N)){let C=0;for(let R of M)if(R.actor_id.startsWith(L)){let w=parseInt(R.actor_id.slice(L.length),10);if(Number.isFinite(w)&&w>C)C=w}Z.set(N,C)}}let q=(Z.get(N)??0)+1;return Z.set(N,q),`${j}-${q}`});return yield*T.sync(()=>W1.use((A)=>{let j=Date.now();A.update(_1).set({status:"idle",last_outcome:"failure",last_error:"orphaned: process restarted",time_updated:j,time_completed:j}).where(k5(_1.status,["pending","running"])).run()})),_N0.info("orphan recovery complete"),yield*T.gen(function*(){let A=Date.now()-SN0,j=yield*T.sync(()=>W1.use((N)=>N.select().from(_1).where(O$(m0(_1.status,"running"),Yd(_1.last_turn_time,A))).all()));for(let N of j){let L=HY(N);yield*$.publish($d,{sessionID:L.sessionID,actorID:L.actorID,description:L.description,lastTurnTime:L.lastTurnTime,stuckDuration:Date.now()-L.lastTurnTime})}}).pipe(T.repeat(W4.fixed(fN0)),T.ignore,T.forkScoped),yK.of({register:J,updateStatus:X,updateTurn:Q,get:G,listBySession:W,listActive:K,listByParent:V,renderForAgent:U,agentTypeFor:H,isSystemSpawned:B,allocateActorID:z})})),kN0=Xd.pipe(T0.provide(l1.layer));import nA from"path";/*!
803
803
  * decimal.js v10.5.0
804
804
  * An arbitrary-precision Decimal type for JavaScript.
805
805
  * https://github.com/MikeMcl/decimal.js
806
806
  * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
807
807
  * MIT Licence
808
- */var zY=9000000000000000,H5=1e9,mA="0123456789abcdef",gK="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",uK="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",lA={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-zY,maxE:zY,crypto:!1},Kd,qZ,i0=!0,lK="[DecimalError] ",U5=lK+"Invalid argument: ",Vd=lK+"Precision limit exceeded",Ud=lK+"crypto unavailable",Hd="[object Decimal]",n$=Math.floor,q$=Math.pow,vN0=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,yN0=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,xN0=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Bd=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,H6=1e7,x0=7,hN0=9007199254740991,gN0=gK.length-1,dA=uK.length-1,X0={toStringTag:Hd};X0.absoluteValue=X0.abs=function(){var $=new this.constructor(this);if($.s<0)$.s=1;return I0($)};X0.ceil=function(){return I0(new this.constructor(this),this.e+1,2)};X0.clampedTo=X0.clamp=function($,Z){var J,Y=this,X=Y.constructor;if($=new X($),Z=new X(Z),!$.s||!Z.s)return new X(NaN);if($.gt(Z))throw Error(U5+Z);return J=Y.cmp($),J<0?$:Y.cmp(Z)>0?Z:new X(Y)};X0.comparedTo=X0.cmp=function($){var Z,J,Y,X,Q=this,G=Q.d,W=($=new Q.constructor($)).d,K=Q.s,V=$.s;if(!G||!W)return!K||!V?NaN:K!==V?K:G===W?0:!G^K<0?1:-1;if(!G[0]||!W[0])return G[0]?K:W[0]?-V:0;if(K!==V)return K;if(Q.e!==$.e)return Q.e>$.e^K<0?1:-1;Y=G.length,X=W.length;for(Z=0,J=Y<X?Y:X;Z<J;++Z)if(G[Z]!==W[Z])return G[Z]>W[Z]^K<0?1:-1;return Y===X?0:Y>X^K<0?1:-1};X0.cosine=X0.cos=function(){var $,Z,J=this,Y=J.constructor;if(!J.d)return new Y(NaN);if(!J.d[0])return new Y(1);return $=Y.precision,Z=Y.rounding,Y.precision=$+Math.max(J.e,J.sd())+x0,Y.rounding=1,J=uN0(Y,qd(Y,J)),Y.precision=$,Y.rounding=Z,I0(qZ==2||qZ==3?J.neg():J,$,Z,!0)};X0.cubeRoot=X0.cbrt=function(){var $,Z,J,Y,X,Q,G,W,K,V,U=this,H=U.constructor;if(!U.isFinite()||U.isZero())return new H(U);if(i0=!1,Q=U.s*q$(U.s*U,0.3333333333333333),!Q||Math.abs(Q)==1/0){if(J=v$(U.d),$=U.e,Q=($-J.length+1)%3)J+=Q==1||Q==-2?"0":"00";if(Q=q$(J,0.3333333333333333),$=n$(($+1)/3)-($%3==($<0?-1:2)),Q==1/0)J="5e"+$;else J=Q.toExponential(),J=J.slice(0,J.indexOf("e")+1)+$;Y=new H(J),Y.s=U.s}else Y=new H(Q.toString());G=($=H.precision)+3;for(;;)if(W=Y,K=W.times(W).times(W),V=K.plus(U),Y=h1(V.plus(U).times(W),V.plus(K),G+2,1),v$(W.d).slice(0,G)===(J=v$(Y.d)).slice(0,G))if(J=J.slice(G-3,G+1),J=="9999"||!X&&J=="4999"){if(!X){if(I0(W,$+1,0),W.times(W).times(W).eq(U)){Y=W;break}}G+=4,X=1}else{if(!+J||!+J.slice(1)&&J.charAt(0)=="5")I0(Y,$+1,1),Z=!Y.times(Y).times(Y).eq(U);break}return i0=!0,I0(Y,$,H.rounding,Z)};X0.decimalPlaces=X0.dp=function(){var $,Z=this.d,J=NaN;if(Z){if($=Z.length-1,J=($-n$(this.e/x0))*x0,$=Z[$],$)for(;$%10==0;$/=10)J--;if(J<0)J=0}return J};X0.dividedBy=X0.div=function($){return h1(this,new this.constructor($))};X0.dividedToIntegerBy=X0.divToInt=function($){var Z=this,J=Z.constructor;return I0(h1(Z,new J($),0,1,1),J.precision,J.rounding)};X0.equals=X0.eq=function($){return this.cmp($)===0};X0.floor=function(){return I0(new this.constructor(this),this.e+1,3)};X0.greaterThan=X0.gt=function($){return this.cmp($)>0};X0.greaterThanOrEqualTo=X0.gte=function($){var Z=this.cmp($);return Z==1||Z===0};X0.hyperbolicCosine=X0.cosh=function(){var $,Z,J,Y,X,Q=this,G=Q.constructor,W=new G(1);if(!Q.isFinite())return new G(Q.s?1/0:NaN);if(Q.isZero())return W;if(J=G.precision,Y=G.rounding,G.precision=J+Math.max(Q.e,Q.sd())+4,G.rounding=1,X=Q.d.length,X<32)$=Math.ceil(X/3),Z=(1/pK(4,$)).toString();else $=16,Z="2.3283064365386962890625e-10";Q=FY(G,1,Q.times(Z),new G(1),!0);var K,V=$,U=new G(8);for(;V--;)K=Q.times(Q),Q=W.minus(K.times(U.minus(K.times(U))));return I0(Q,G.precision=J,G.rounding=Y,!0)};X0.hyperbolicSine=X0.sinh=function(){var $,Z,J,Y,X=this,Q=X.constructor;if(!X.isFinite()||X.isZero())return new Q(X);if(Z=Q.precision,J=Q.rounding,Q.precision=Z+Math.max(X.e,X.sd())+4,Q.rounding=1,Y=X.d.length,Y<3)X=FY(Q,2,X,X,!0);else{$=1.4*Math.sqrt(Y),$=$>16?16:$|0,X=X.times(1/pK(5,$)),X=FY(Q,2,X,X,!0);var G,W=new Q(5),K=new Q(16),V=new Q(20);for(;$--;)G=X.times(X),X=X.times(W.plus(G.times(K.times(G).plus(V))))}return Q.precision=Z,Q.rounding=J,I0(X,Z,J,!0)};X0.hyperbolicTangent=X0.tanh=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite())return new Y(J.s);if(J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+7,Y.rounding=1,h1(J.sinh(),J.cosh(),Y.precision=$,Y.rounding=Z)};X0.inverseCosine=X0.acos=function(){var $=this,Z=$.constructor,J=$.abs().cmp(1),Y=Z.precision,X=Z.rounding;if(J!==-1)return J===0?$.isNeg()?y6(Z,Y,X):new Z(0):new Z(NaN);if($.isZero())return y6(Z,Y+4,X).times(0.5);return Z.precision=Y+6,Z.rounding=1,$=new Z(1).minus($).div($.plus(1)).sqrt().atan(),Z.precision=Y,Z.rounding=X,$.times(2)};X0.inverseHyperbolicCosine=X0.acosh=function(){var $,Z,J=this,Y=J.constructor;if(J.lte(1))return new Y(J.eq(1)?0:NaN);if(!J.isFinite())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+Math.max(Math.abs(J.e),J.sd())+4,Y.rounding=1,i0=!1,J=J.times(J).minus(1).sqrt().plus(J),i0=!0,Y.precision=$,Y.rounding=Z,J.ln()};X0.inverseHyperbolicSine=X0.asinh=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite()||J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+2*Math.max(Math.abs(J.e),J.sd())+6,Y.rounding=1,i0=!1,J=J.times(J).plus(1).sqrt().plus(J),i0=!0,Y.precision=$,Y.rounding=Z,J.ln()};X0.inverseHyperbolicTangent=X0.atanh=function(){var $,Z,J,Y,X=this,Q=X.constructor;if(!X.isFinite())return new Q(NaN);if(X.e>=0)return new Q(X.abs().eq(1)?X.s/0:X.isZero()?X:NaN);if($=Q.precision,Z=Q.rounding,Y=X.sd(),Math.max(Y,$)<2*-X.e-1)return I0(new Q(X),$,Z,!0);return Q.precision=J=Y-X.e,X=h1(X.plus(1),new Q(1).minus(X),J+$,1),Q.precision=$+4,Q.rounding=1,X=X.ln(),Q.precision=$,Q.rounding=Z,X.times(0.5)};X0.inverseSine=X0.asin=function(){var $,Z,J,Y,X=this,Q=X.constructor;if(X.isZero())return new Q(X);if(Z=X.abs().cmp(1),J=Q.precision,Y=Q.rounding,Z!==-1){if(Z===0)return $=y6(Q,J+4,Y).times(0.5),$.s=X.s,$;return new Q(NaN)}return Q.precision=J+6,Q.rounding=1,X=X.div(new Q(1).minus(X.times(X)).sqrt().plus(1)).atan(),Q.precision=J,Q.rounding=Y,X.times(2)};X0.inverseTangent=X0.atan=function(){var $,Z,J,Y,X,Q,G,W,K,V=this,U=V.constructor,H=U.precision,B=U.rounding;if(!V.isFinite()){if(!V.s)return new U(NaN);if(H+4<=dA)return G=y6(U,H+4,B).times(0.5),G.s=V.s,G}else if(V.isZero())return new U(V);else if(V.abs().eq(1)&&H+4<=dA)return G=y6(U,H+4,B).times(0.25),G.s=V.s,G;U.precision=W=H+10,U.rounding=1,J=Math.min(28,W/x0+2|0);for($=J;$;--$)V=V.div(V.times(V).plus(1).sqrt().plus(1));i0=!1,Z=Math.ceil(W/x0),Y=1,K=V.times(V),G=new U(V),X=V;for(;$!==-1;)if(X=X.times(K),Q=G.minus(X.div(Y+=2)),X=X.times(K),G=Q.plus(X.div(Y+=2)),G.d[Z]!==void 0)for($=Z;G.d[$]===Q.d[$]&&$--;);if(J)G=G.times(2<<J-1);return i0=!0,I0(G,U.precision=H,U.rounding=B,!0)};X0.isFinite=function(){return!!this.d};X0.isInteger=X0.isInt=function(){return!!this.d&&n$(this.e/x0)>this.d.length-2};X0.isNaN=function(){return!this.s};X0.isNegative=X0.isNeg=function(){return this.s<0};X0.isPositive=X0.isPos=function(){return this.s>0};X0.isZero=function(){return!!this.d&&this.d[0]===0};X0.lessThan=X0.lt=function($){return this.cmp($)<0};X0.lessThanOrEqualTo=X0.lte=function($){return this.cmp($)<1};X0.logarithm=X0.log=function($){var Z,J,Y,X,Q,G,W,K,V=this,U=V.constructor,H=U.precision,B=U.rounding,z=5;if($==null)$=new U(10),Z=!0;else{if($=new U($),J=$.d,$.s<0||!J||!J[0]||$.eq(1))return new U(NaN);Z=$.eq(10)}if(J=V.d,V.s<0||!J||!J[0]||V.eq(1))return new U(J&&!J[0]?-1/0:V.s!=1?NaN:J?0:1/0);if(Z)if(J.length>1)Q=!0;else{for(X=J[0];X%10===0;)X/=10;Q=X!==1}if(i0=!1,W=H+z,G=V5(V,W),Y=Z?mK(U,W+10):V5($,W),K=h1(G,Y,W,1),V9(K.d,X=H,B))do if(W+=10,G=V5(V,W),Y=Z?mK(U,W+10):V5($,W),K=h1(G,Y,W,1),!Q){if(+v$(K.d).slice(X+1,X+15)+1==100000000000000)K=I0(K,H+1,0);break}while(V9(K.d,X+=10,B));return i0=!0,I0(K,H,B)};X0.minus=X0.sub=function($){var Z,J,Y,X,Q,G,W,K,V,U,H,B,z=this,F=z.constructor;if($=new F($),!z.d||!$.d){if(!z.s||!$.s)$=new F(NaN);else if(z.d)$.s=-$.s;else $=new F($.d||z.s!==$.s?z:NaN);return $}if(z.s!=$.s)return $.s=-$.s,z.plus($);if(V=z.d,B=$.d,W=F.precision,K=F.rounding,!V[0]||!B[0]){if(B[0])$.s=-$.s;else if(V[0])$=new F(z);else return new F(K===3?-0:0);return i0?I0($,W,K):$}if(J=n$($.e/x0),U=n$(z.e/x0),V=V.slice(),Q=U-J,Q){if(H=Q<0,H)Z=V,Q=-Q,G=B.length;else Z=B,J=U,G=V.length;if(Y=Math.max(Math.ceil(W/x0),G)+2,Q>Y)Q=Y,Z.length=1;Z.reverse();for(Y=Q;Y--;)Z.push(0);Z.reverse()}else{if(Y=V.length,G=B.length,H=Y<G,H)G=Y;for(Y=0;Y<G;Y++)if(V[Y]!=B[Y]){H=V[Y]<B[Y];break}Q=0}if(H)Z=V,V=B,B=Z,$.s=-$.s;G=V.length;for(Y=B.length-G;Y>0;--Y)V[G++]=0;for(Y=B.length;Y>Q;){if(V[--Y]<B[Y]){for(X=Y;X&&V[--X]===0;)V[X]=H6-1;--V[X],V[Y]+=H6}V[Y]-=B[Y]}for(;V[--G]===0;)V.pop();for(;V[0]===0;V.shift())--J;if(!V[0])return new F(K===3?-0:0);return $.d=V,$.e=dK(V,J),i0?I0($,W,K):$};X0.modulo=X0.mod=function($){var Z,J=this,Y=J.constructor;if($=new Y($),!J.d||!$.s||$.d&&!$.d[0])return new Y(NaN);if(!$.d||J.d&&!J.d[0])return I0(new Y(J),Y.precision,Y.rounding);if(i0=!1,Y.modulo==9)Z=h1(J,$.abs(),0,3,1),Z.s*=$.s;else Z=h1(J,$,0,Y.modulo,1);return Z=Z.times($),i0=!0,J.minus(Z)};X0.naturalExponential=X0.exp=function(){return pA(this)};X0.naturalLogarithm=X0.ln=function(){return V5(this)};X0.negated=X0.neg=function(){var $=new this.constructor(this);return $.s=-$.s,I0($)};X0.plus=X0.add=function($){var Z,J,Y,X,Q,G,W,K,V,U,H=this,B=H.constructor;if($=new B($),!H.d||!$.d){if(!H.s||!$.s)$=new B(NaN);else if(!H.d)$=new B($.d||H.s===$.s?H:NaN);return $}if(H.s!=$.s)return $.s=-$.s,H.minus($);if(V=H.d,U=$.d,W=B.precision,K=B.rounding,!V[0]||!U[0]){if(!U[0])$=new B(H);return i0?I0($,W,K):$}if(Q=n$(H.e/x0),Y=n$($.e/x0),V=V.slice(),X=Q-Y,X){if(X<0)J=V,X=-X,G=U.length;else J=U,Y=Q,G=V.length;if(Q=Math.ceil(W/x0),G=Q>G?Q+1:G+1,X>G)X=G,J.length=1;J.reverse();for(;X--;)J.push(0);J.reverse()}if(G=V.length,X=U.length,G-X<0)X=G,J=U,U=V,V=J;for(Z=0;X;)Z=(V[--X]=V[X]+U[X]+Z)/H6|0,V[X]%=H6;if(Z)V.unshift(Z),++Y;for(G=V.length;V[--G]==0;)V.pop();return $.d=V,$.e=dK(V,Y),i0?I0($,W,K):$};X0.precision=X0.sd=function($){var Z,J=this;if($!==void 0&&$!==!!$&&$!==1&&$!==0)throw Error(U5+$);if(J.d){if(Z=zd(J.d),$&&J.e+1>Z)Z=J.e+1}else Z=NaN;return Z};X0.round=function(){var $=this,Z=$.constructor;return I0(new Z($),$.e+1,Z.rounding)};X0.sine=X0.sin=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+Math.max(J.e,J.sd())+x0,Y.rounding=1,J=lN0(Y,qd(Y,J)),Y.precision=$,Y.rounding=Z,I0(qZ>2?J.neg():J,$,Z,!0)};X0.squareRoot=X0.sqrt=function(){var $,Z,J,Y,X,Q,G=this,W=G.d,K=G.e,V=G.s,U=G.constructor;if(V!==1||!W||!W[0])return new U(!V||V<0&&(!W||W[0])?NaN:W?G:1/0);if(i0=!1,V=Math.sqrt(+G),V==0||V==1/0){if(Z=v$(W),(Z.length+K)%2==0)Z+="0";if(V=Math.sqrt(Z),K=n$((K+1)/2)-(K<0||K%2),V==1/0)Z="5e"+K;else Z=V.toExponential(),Z=Z.slice(0,Z.indexOf("e")+1)+K;Y=new U(Z)}else Y=new U(V.toString());J=(K=U.precision)+3;for(;;)if(Q=Y,Y=Q.plus(h1(G,Q,J+2,1)).times(0.5),v$(Q.d).slice(0,J)===(Z=v$(Y.d)).slice(0,J))if(Z=Z.slice(J-3,J+1),Z=="9999"||!X&&Z=="4999"){if(!X){if(I0(Q,K+1,0),Q.times(Q).eq(G)){Y=Q;break}}J+=4,X=1}else{if(!+Z||!+Z.slice(1)&&Z.charAt(0)=="5")I0(Y,K+1,1),$=!Y.times(Y).eq(G);break}return i0=!0,I0(Y,K,U.rounding,$)};X0.tangent=X0.tan=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+10,Y.rounding=1,J=J.sin(),J.s=1,J=h1(J,new Y(1).minus(J.times(J)).sqrt(),$+10,0),Y.precision=$,Y.rounding=Z,I0(qZ==2||qZ==4?J.neg():J,$,Z,!0)};X0.times=X0.mul=function($){var Z,J,Y,X,Q,G,W,K,V,U=this,H=U.constructor,B=U.d,z=($=new H($)).d;if($.s*=U.s,!B||!B[0]||!z||!z[0])return new H(!$.s||B&&!B[0]&&!z||z&&!z[0]&&!B?NaN:!B||!z?$.s/0:$.s*0);if(J=n$(U.e/x0)+n$($.e/x0),K=B.length,V=z.length,K<V)Q=B,B=z,z=Q,G=K,K=V,V=G;Q=[],G=K+V;for(Y=G;Y--;)Q.push(0);for(Y=V;--Y>=0;){Z=0;for(X=K+Y;X>Y;)W=Q[X]+z[Y]*B[X-Y-1]+Z,Q[X--]=W%H6|0,Z=W/H6|0;Q[X]=(Q[X]+Z)%H6|0}for(;!Q[--G];)Q.pop();if(Z)++J;else Q.shift();return $.d=Q,$.e=dK(Q,J),i0?I0($,H.precision,H.rounding):$};X0.toBinary=function($,Z){return cA(this,2,$,Z)};X0.toDecimalPlaces=X0.toDP=function($,Z){var J=this,Y=J.constructor;if(J=new Y(J),$===void 0)return J;if(A8($,0,H5),Z===void 0)Z=Y.rounding;else A8(Z,0,8);return I0(J,$+J.e+1,Z)};X0.toExponential=function($,Z){var J,Y=this,X=Y.constructor;if($===void 0)J=x6(Y,!0);else{if(A8($,0,H5),Z===void 0)Z=X.rounding;else A8(Z,0,8);Y=I0(new X(Y),$+1,Z),J=x6(Y,!0,$+1)}return Y.isNeg()&&!Y.isZero()?"-"+J:J};X0.toFixed=function($,Z){var J,Y,X=this,Q=X.constructor;if($===void 0)J=x6(X);else{if(A8($,0,H5),Z===void 0)Z=Q.rounding;else A8(Z,0,8);Y=I0(new Q(X),$+X.e+1,Z),J=x6(Y,!1,$+Y.e+1)}return X.isNeg()&&!X.isZero()?"-"+J:J};X0.toFraction=function($){var Z,J,Y,X,Q,G,W,K,V,U,H,B,z=this,F=z.d,A=z.constructor;if(!F)return new A(z);if(V=J=new A(1),Y=K=new A(0),Z=new A(Y),Q=Z.e=zd(F)-z.e-1,G=Q%x0,Z.d[0]=q$(10,G<0?x0+G:G),$==null)$=Q>0?Z:V;else{if(W=new A($),!W.isInt()||W.lt(V))throw Error(U5+W);$=W.gt(Z)?Q>0?Z:V:W}i0=!1,W=new A(v$(F)),U=A.precision,A.precision=Q=F.length*x0*2;for(;;){if(H=h1(W,Z,0,1,1),X=J.plus(H.times(Y)),X.cmp($)==1)break;J=Y,Y=X,X=V,V=K.plus(H.times(X)),K=X,X=Z,Z=W.minus(H.times(X)),W=X}return X=h1($.minus(J),Y,0,1,1),K=K.plus(X.times(V)),J=J.plus(X.times(Y)),K.s=V.s=z.s,B=h1(V,Y,Q,1).minus(z).abs().cmp(h1(K,J,Q,1).minus(z).abs())<1?[V,Y]:[K,J],A.precision=U,i0=!0,B};X0.toHexadecimal=X0.toHex=function($,Z){return cA(this,16,$,Z)};X0.toNearest=function($,Z){var J=this,Y=J.constructor;if(J=new Y(J),$==null){if(!J.d)return J;$=new Y(1),Z=Y.rounding}else{if($=new Y($),Z===void 0)Z=Y.rounding;else A8(Z,0,8);if(!J.d)return $.s?J:$;if(!$.d){if($.s)$.s=J.s;return $}}if($.d[0])i0=!1,J=h1(J,$,0,Z,1).times($),i0=!0,I0(J);else $.s=J.s,J=$;return J};X0.toNumber=function(){return+this};X0.toOctal=function($,Z){return cA(this,8,$,Z)};X0.toPower=X0.pow=function($){var Z,J,Y,X,Q,G,W=this,K=W.constructor,V=+($=new K($));if(!W.d||!$.d||!W.d[0]||!$.d[0])return new K(q$(+W,V));if(W=new K(W),W.eq(1))return W;if(Y=K.precision,Q=K.rounding,$.eq(1))return I0(W,Y,Q);if(Z=n$($.e/x0),Z>=$.d.length-1&&(J=V<0?-V:V)<=hN0)return X=Fd(K,W,J,Y),$.s<0?new K(1).div(X):I0(X,Y,Q);if(G=W.s,G<0){if(Z<$.d.length-1)return new K(NaN);if(($.d[Z]&1)==0)G=1;if(W.e==0&&W.d[0]==1&&W.d.length==1)return W.s=G,W}if(J=q$(+W,V),Z=J==0||!isFinite(J)?n$(V*(Math.log("0."+v$(W.d))/Math.LN10+W.e+1)):new K(J+"").e,Z>K.maxE+1||Z<K.minE-1)return new K(Z>0?G/0:0);if(i0=!1,K.rounding=W.s=1,J=Math.min(12,(Z+"").length),X=pA($.times(V5(W,Y+J)),Y),X.d){if(X=I0(X,Y+5,1),V9(X.d,Y,Q)){if(Z=Y+10,X=I0(pA($.times(V5(W,Z+J)),Z),Z+5,1),+v$(X.d).slice(Y+1,Y+15)+1==100000000000000)X=I0(X,Y+1,0)}}return X.s=G,i0=!0,K.rounding=Q,I0(X,Y,Q)};X0.toPrecision=function($,Z){var J,Y=this,X=Y.constructor;if($===void 0)J=x6(Y,Y.e<=X.toExpNeg||Y.e>=X.toExpPos);else{if(A8($,1,H5),Z===void 0)Z=X.rounding;else A8(Z,0,8);Y=I0(new X(Y),$,Z),J=x6(Y,$<=Y.e||Y.e<=X.toExpNeg,$)}return Y.isNeg()&&!Y.isZero()?"-"+J:J};X0.toSignificantDigits=X0.toSD=function($,Z){var J=this,Y=J.constructor;if($===void 0)$=Y.precision,Z=Y.rounding;else if(A8($,1,H5),Z===void 0)Z=Y.rounding;else A8(Z,0,8);return I0(new Y(J),$,Z)};X0.toString=function(){var $=this,Z=$.constructor,J=x6($,$.e<=Z.toExpNeg||$.e>=Z.toExpPos);return $.isNeg()&&!$.isZero()?"-"+J:J};X0.truncated=X0.trunc=function(){return I0(new this.constructor(this),this.e+1,1)};X0.valueOf=X0.toJSON=function(){var $=this,Z=$.constructor,J=x6($,$.e<=Z.toExpNeg||$.e>=Z.toExpPos);return $.isNeg()?"-"+J:J};function v$($){var Z,J,Y,X=$.length-1,Q="",G=$[0];if(X>0){Q+=G;for(Z=1;Z<X;Z++){if(Y=$[Z]+"",J=x0-Y.length,J)Q+=K5(J);Q+=Y}if(G=$[Z],Y=G+"",J=x0-Y.length,J)Q+=K5(J)}else if(G===0)return"0";for(;G%10===0;)G/=10;return Q+G}function A8($,Z,J){if($!==~~$||$<Z||$>J)throw Error(U5+$)}function V9($,Z,J,Y){var X,Q,G,W;for(Q=$[0];Q>=10;Q/=10)--Z;if(--Z<0)Z+=x0,X=0;else X=Math.ceil((Z+1)/x0),Z%=x0;if(Q=q$(10,x0-Z),W=$[X]%Q|0,Y==null)if(Z<3){if(Z==0)W=W/100|0;else if(Z==1)W=W/10|0;G=J<4&&W==99999||J>3&&W==49999||W==50000||W==0}else G=(J<4&&W+1==Q||J>3&&W+1==Q/2)&&($[X+1]/Q/100|0)==q$(10,Z-2)-1||(W==Q/2||W==0)&&($[X+1]/Q/100|0)==0;else if(Z<4){if(Z==0)W=W/1000|0;else if(Z==1)W=W/100|0;else if(Z==2)W=W/10|0;G=(Y||J<4)&&W==9999||!Y&&J>3&&W==4999}else G=((Y||J<4)&&W+1==Q||!Y&&J>3&&W+1==Q/2)&&($[X+1]/Q/1000|0)==q$(10,Z-3)-1;return G}function xK($,Z,J){var Y,X=[0],Q,G=0,W=$.length;for(;G<W;){for(Q=X.length;Q--;)X[Q]*=Z;X[0]+=mA.indexOf($.charAt(G++));for(Y=0;Y<X.length;Y++)if(X[Y]>J-1){if(X[Y+1]===void 0)X[Y+1]=0;X[Y+1]+=X[Y]/J|0,X[Y]%=J}}return X.reverse()}function uN0($,Z){var J,Y,X;if(Z.isZero())return Z;if(Y=Z.d.length,Y<32)J=Math.ceil(Y/3),X=(1/pK(4,J)).toString();else J=16,X="2.3283064365386962890625e-10";$.precision+=J,Z=FY($,1,Z.times(X),new $(1));for(var Q=J;Q--;){var G=Z.times(Z);Z=G.times(G).minus(G).times(8).plus(1)}return $.precision-=J,Z}var h1=function(){function $(Y,X,Q){var G,W=0,K=Y.length;for(Y=Y.slice();K--;)G=Y[K]*X+W,Y[K]=G%Q|0,W=G/Q|0;if(W)Y.unshift(W);return Y}function Z(Y,X,Q,G){var W,K;if(Q!=G)K=Q>G?1:-1;else for(W=K=0;W<Q;W++)if(Y[W]!=X[W]){K=Y[W]>X[W]?1:-1;break}return K}function J(Y,X,Q,G){var W=0;for(;Q--;)Y[Q]-=W,W=Y[Q]<X[Q]?1:0,Y[Q]=W*G+Y[Q]-X[Q];for(;!Y[0]&&Y.length>1;)Y.shift()}return function(Y,X,Q,G,W,K){var V,U,H,B,z,F,A,j,N,L,q,M,C,R,w,I,_,E,f,b,y=Y.constructor,k=Y.s==X.s?1:-1,g=Y.d,d=X.d;if(!g||!g[0]||!d||!d[0])return new y(!Y.s||!X.s||(g?d&&g[0]==d[0]:!d)?NaN:g&&g[0]==0||!d?k*0:k/0);if(K)z=1,U=Y.e-X.e;else K=H6,z=x0,U=n$(Y.e/z)-n$(X.e/z);f=d.length,_=g.length,N=new y(k),L=N.d=[];for(H=0;d[H]==(g[H]||0);H++);if(d[H]>(g[H]||0))U--;if(Q==null)R=Q=y.precision,G=y.rounding;else if(W)R=Q+(Y.e-X.e)+1;else R=Q;if(R<0)L.push(1),F=!0;else{if(R=R/z+2|0,H=0,f==1){B=0,d=d[0],R++;for(;(H<_||B)&&R--;H++)w=B*K+(g[H]||0),L[H]=w/d|0,B=w%d|0;F=B||H<_}else{if(B=K/(d[0]+1)|0,B>1)d=$(d,B,K),g=$(g,B,K),f=d.length,_=g.length;I=f,q=g.slice(0,f),M=q.length;for(;M<f;)q[M++]=0;if(b=d.slice(),b.unshift(0),E=d[0],d[1]>=K/2)++E;do{if(B=0,V=Z(d,q,f,M),V<0){if(C=q[0],f!=M)C=C*K+(q[1]||0);if(B=C/E|0,B>1){if(B>=K)B=K-1;if(A=$(d,B,K),j=A.length,M=q.length,V=Z(A,q,j,M),V==1)B--,J(A,f<j?b:d,j,K)}else{if(B==0)V=B=1;A=d.slice()}if(j=A.length,j<M)A.unshift(0);if(J(q,A,M,K),V==-1){if(M=q.length,V=Z(d,q,f,M),V<1)B++,J(q,f<M?b:d,M,K)}M=q.length}else if(V===0)B++,q=[0];if(L[H++]=B,V&&q[0])q[M++]=g[I]||0;else q=[g[I]],M=1}while((I++<_||q[0]!==void 0)&&R--);F=q[0]!==void 0}if(!L[0])L.shift()}if(z==1)N.e=U,Kd=F;else{for(H=1,B=L[0];B>=10;B/=10)H++;N.e=H+U*z-1,I0(N,W?Q+N.e+1:Q,G,F)}return N}}();function I0($,Z,J,Y){var X,Q,G,W,K,V,U,H,B,z=$.constructor;$:if(Z!=null){if(H=$.d,!H)return $;for(X=1,W=H[0];W>=10;W/=10)X++;if(Q=Z-X,Q<0)Q+=x0,G=Z,U=H[B=0],K=U/q$(10,X-G-1)%10|0;else if(B=Math.ceil((Q+1)/x0),W=H.length,B>=W)if(Y){for(;W++<=B;)H.push(0);U=K=0,X=1,Q%=x0,G=Q-x0+1}else break $;else{U=W=H[B];for(X=1;W>=10;W/=10)X++;Q%=x0,G=Q-x0+X,K=G<0?0:U/q$(10,X-G-1)%10|0}if(Y=Y||Z<0||H[B+1]!==void 0||(G<0?U:U%q$(10,X-G-1)),V=J<4?(K||Y)&&(J==0||J==($.s<0?3:2)):K>5||K==5&&(J==4||Y||J==6&&(Q>0?G>0?U/q$(10,X-G):0:H[B-1])%10&1||J==($.s<0?8:7)),Z<1||!H[0]){if(H.length=0,V)Z-=$.e+1,H[0]=q$(10,(x0-Z%x0)%x0),$.e=-Z||0;else H[0]=$.e=0;return $}if(Q==0)H.length=B,W=1,B--;else H.length=B+1,W=q$(10,x0-Q),H[B]=G>0?(U/q$(10,X-G)%q$(10,G)|0)*W:0;if(V)for(;;)if(B==0){for(Q=1,G=H[0];G>=10;G/=10)Q++;G=H[0]+=W;for(W=1;G>=10;G/=10)W++;if(Q!=W){if($.e++,H[0]==H6)H[0]=1}break}else{if(H[B]+=W,H[B]!=H6)break;H[B--]=0,W=1}for(Q=H.length;H[--Q]===0;)H.pop()}if(i0){if($.e>z.maxE)$.d=null,$.e=NaN;else if($.e<z.minE)$.e=0,$.d=[0]}return $}function x6($,Z,J){if(!$.isFinite())return Od($);var Y,X=$.e,Q=v$($.d),G=Q.length;if(Z){if(J&&(Y=J-G)>0)Q=Q.charAt(0)+"."+Q.slice(1)+K5(Y);else if(G>1)Q=Q.charAt(0)+"."+Q.slice(1);Q=Q+($.e<0?"e":"e+")+$.e}else if(X<0){if(Q="0."+K5(-X-1)+Q,J&&(Y=J-G)>0)Q+=K5(Y)}else if(X>=G){if(Q+=K5(X+1-G),J&&(Y=J-X-1)>0)Q=Q+"."+K5(Y)}else{if((Y=X+1)<G)Q=Q.slice(0,Y)+"."+Q.slice(Y);if(J&&(Y=J-G)>0){if(X+1===G)Q+=".";Q+=K5(Y)}}return Q}function dK($,Z){var J=$[0];for(Z*=x0;J>=10;J/=10)Z++;return Z}function mK($,Z,J){if(Z>gN0){if(i0=!0,J)$.precision=J;throw Error(Vd)}return I0(new $(gK),Z,1,!0)}function y6($,Z,J){if(Z>dA)throw Error(Vd);return I0(new $(uK),Z,J,!0)}function zd($){var Z=$.length-1,J=Z*x0+1;if(Z=$[Z],Z){for(;Z%10==0;Z/=10)J--;for(Z=$[0];Z>=10;Z/=10)J++}return J}function K5($){var Z="";for(;$--;)Z+="0";return Z}function Fd($,Z,J,Y){var X,Q=new $(1),G=Math.ceil(Y/x0+4);i0=!1;for(;;){if(J%2){if(Q=Q.times(Z),Gd(Q.d,G))X=!0}if(J=n$(J/2),J===0){if(J=Q.d.length-1,X&&Q.d[J]===0)++Q.d[J];break}Z=Z.times(Z),Gd(Z.d,G)}return i0=!0,Q}function Qd($){return $.d[$.d.length-1]&1}function Ad($,Z,J){var Y,X,Q=new $(Z[0]),G=0;for(;++G<Z.length;){if(X=new $(Z[G]),!X.s){Q=X;break}if(Y=Q.cmp(X),Y===J||Y===0&&Q.s===J)Q=X}return Q}function pA($,Z){var J,Y,X,Q,G,W,K,V=0,U=0,H=0,B=$.constructor,z=B.rounding,F=B.precision;if(!$.d||!$.d[0]||$.e>17)return new B($.d?!$.d[0]?1:$.s<0?0:1/0:$.s?$.s<0?0:$:NaN);if(Z==null)i0=!1,K=F;else K=Z;W=new B(0.03125);while($.e>-2)$=$.times(W),H+=5;Y=Math.log(q$(2,H))/Math.LN10*2+5|0,K+=Y,J=Q=G=new B(1),B.precision=K;for(;;){if(Q=I0(Q.times($),K,1),J=J.times(++U),W=G.plus(h1(Q,J,K,1)),v$(W.d).slice(0,K)===v$(G.d).slice(0,K)){X=H;while(X--)G=I0(G.times(G),K,1);if(Z==null)if(V<3&&V9(G.d,K-Y,z,V))B.precision=K+=10,J=Q=W=new B(1),U=0,V++;else return I0(G,B.precision=F,z,i0=!0);else return B.precision=F,G}G=W}}function V5($,Z){var J,Y,X,Q,G,W,K,V,U,H,B,z=1,F=10,A=$,j=A.d,N=A.constructor,L=N.rounding,q=N.precision;if(A.s<0||!j||!j[0]||!A.e&&j[0]==1&&j.length==1)return new N(j&&!j[0]?-1/0:A.s!=1?NaN:j?0:A);if(Z==null)i0=!1,U=q;else U=Z;if(N.precision=U+=F,J=v$(j),Y=J.charAt(0),Math.abs(Q=A.e)<1500000000000000){while(Y<7&&Y!=1||Y==1&&J.charAt(1)>3)A=A.times($),J=v$(A.d),Y=J.charAt(0),z++;if(Q=A.e,Y>1)A=new N("0."+J),Q++;else A=new N(Y+"."+J.slice(1))}else return V=mK(N,U+2,q).times(Q+""),A=V5(new N(Y+"."+J.slice(1)),U-F).plus(V),N.precision=q,Z==null?I0(A,q,L,i0=!0):A;H=A,K=G=A=h1(A.minus(1),A.plus(1),U,1),B=I0(A.times(A),U,1),X=3;for(;;){if(G=I0(G.times(B),U,1),V=K.plus(h1(G,new N(X),U,1)),v$(V.d).slice(0,U)===v$(K.d).slice(0,U)){if(K=K.times(2),Q!==0)K=K.plus(mK(N,U+2,q).times(Q+""));if(K=h1(K,new N(z),U,1),Z==null)if(V9(K.d,U-F,L,W))N.precision=U+=F,V=G=A=h1(H.minus(1),H.plus(1),U,1),B=I0(A.times(A),U,1),X=W=1;else return I0(K,N.precision=q,L,i0=!0);else return N.precision=q,K}K=V,X+=2}}function Od($){return String($.s*$.s/0)}function hK($,Z){var J,Y,X;if((J=Z.indexOf("."))>-1)Z=Z.replace(".","");if((Y=Z.search(/e/i))>0){if(J<0)J=Y;J+=+Z.slice(Y+1),Z=Z.substring(0,Y)}else if(J<0)J=Z.length;for(Y=0;Z.charCodeAt(Y)===48;Y++);for(X=Z.length;Z.charCodeAt(X-1)===48;--X);if(Z=Z.slice(Y,X),Z){if(X-=Y,$.e=J=J-Y-1,$.d=[],Y=(J+1)%x0,J<0)Y+=x0;if(Y<X){if(Y)$.d.push(+Z.slice(0,Y));for(X-=x0;Y<X;)$.d.push(+Z.slice(Y,Y+=x0));Z=Z.slice(Y),Y=x0-Z.length}else Y-=X;for(;Y--;)Z+="0";if($.d.push(+Z),i0){if($.e>$.constructor.maxE)$.d=null,$.e=NaN;else if($.e<$.constructor.minE)$.e=0,$.d=[0]}}else $.e=0,$.d=[0];return $}function mN0($,Z){var J,Y,X,Q,G,W,K,V,U;if(Z.indexOf("_")>-1){if(Z=Z.replace(/(\d)_(?=\d)/g,"$1"),Bd.test(Z))return hK($,Z)}else if(Z==="Infinity"||Z==="NaN"){if(!+Z)$.s=NaN;return $.e=NaN,$.d=null,$}if(yN0.test(Z))J=16,Z=Z.toLowerCase();else if(vN0.test(Z))J=2;else if(xN0.test(Z))J=8;else throw Error(U5+Z);if(Q=Z.search(/p/i),Q>0)K=+Z.slice(Q+1),Z=Z.substring(2,Q);else Z=Z.slice(2);if(Q=Z.indexOf("."),G=Q>=0,Y=$.constructor,G)Z=Z.replace(".",""),W=Z.length,Q=W-Q,X=Fd(Y,new Y(J),Q,Q*2);V=xK(Z,J,H6),U=V.length-1;for(Q=U;V[Q]===0;--Q)V.pop();if(Q<0)return new Y($.s*0);if($.e=dK(V,U),$.d=V,i0=!1,G)$=h1($,X,W*4);if(K)$=$.times(Math.abs(K)<54?q$(2,K):B6.pow(2,K));return i0=!0,$}function lN0($,Z){var J,Y=Z.d.length;if(Y<3)return Z.isZero()?Z:FY($,2,Z,Z);J=1.4*Math.sqrt(Y),J=J>16?16:J|0,Z=Z.times(1/pK(5,J)),Z=FY($,2,Z,Z);var X,Q=new $(5),G=new $(16),W=new $(20);for(;J--;)X=Z.times(Z),Z=Z.times(Q.plus(X.times(G.times(X).minus(W))));return Z}function FY($,Z,J,Y,X){var Q,G,W,K,V=1,U=$.precision,H=Math.ceil(U/x0);i0=!1,K=J.times(J),W=new $(Y);for(;;){if(G=h1(W.times(K),new $(Z++*Z++),U,1),W=X?Y.plus(G):Y.minus(G),Y=h1(G.times(K),new $(Z++*Z++),U,1),G=W.plus(Y),G.d[H]!==void 0){for(Q=H;G.d[Q]===W.d[Q]&&Q--;);if(Q==-1)break}Q=W,W=Y,Y=G,G=Q,V++}return i0=!0,G.d.length=H+1,G}function pK($,Z){var J=$;while(--Z)J*=$;return J}function qd($,Z){var J,Y=Z.s<0,X=y6($,$.precision,1),Q=X.times(0.5);if(Z=Z.abs(),Z.lte(Q))return qZ=Y?4:1,Z;if(J=Z.divToInt(X),J.isZero())qZ=Y?3:2;else{if(Z=Z.minus(J.times(X)),Z.lte(Q))return qZ=Qd(J)?Y?2:3:Y?4:1,Z;qZ=Qd(J)?Y?1:4:Y?3:2}return Z.minus(X).abs()}function cA($,Z,J,Y){var X,Q,G,W,K,V,U,H,B,z=$.constructor,F=J!==void 0;if(F)if(A8(J,1,H5),Y===void 0)Y=z.rounding;else A8(Y,0,8);else J=z.precision,Y=z.rounding;if(!$.isFinite())U=Od($);else{if(U=x6($),G=U.indexOf("."),F){if(X=2,Z==16)J=J*4-3;else if(Z==8)J=J*3-2}else X=Z;if(G>=0)U=U.replace(".",""),B=new z(1),B.e=U.length-G,B.d=xK(x6(B),10,X),B.e=B.d.length;H=xK(U,10,X),Q=K=H.length;for(;H[--K]==0;)H.pop();if(!H[0])U=F?"0p+0":"0";else{if(G<0)Q--;else $=new z($),$.d=H,$.e=Q,$=h1($,B,J,Y,0,X),H=$.d,Q=$.e,V=Kd;if(G=H[J],W=X/2,V=V||H[J+1]!==void 0,V=Y<4?(G!==void 0||V)&&(Y===0||Y===($.s<0?3:2)):G>W||G===W&&(Y===4||V||Y===6&&H[J-1]&1||Y===($.s<0?8:7)),H.length=J,V){for(;++H[--J]>X-1;)if(H[J]=0,!J)++Q,H.unshift(1)}for(K=H.length;!H[K-1];--K);for(G=0,U="";G<K;G++)U+=mA.charAt(H[G]);if(F){if(K>1)if(Z==16||Z==8){G=Z==16?4:3;for(--K;K%G;K++)U+="0";H=xK(U,X,Z);for(K=H.length;!H[K-1];--K);for(G=1,U="1.";G<K;G++)U+=mA.charAt(H[G])}else U=U.charAt(0)+"."+U.slice(1);U=U+(Q<0?"p":"p+")+Q}else if(Q<0){for(;++Q;)U="0"+U;U="0."+U}else if(++Q>K)for(Q-=K;Q--;)U+="0";else if(Q<K)U=U.slice(0,Q)+"."+U.slice(Q)}U=(Z==16?"0x":Z==2?"0b":Z==8?"0o":"")+U}return $.s<0?"-"+U:U}function Gd($,Z){if($.length>Z)return $.length=Z,!0}function dN0($){return new this($).abs()}function pN0($){return new this($).acos()}function cN0($){return new this($).acosh()}function iN0($,Z){return new this($).plus(Z)}function nN0($){return new this($).asin()}function oN0($){return new this($).asinh()}function sN0($){return new this($).atan()}function rN0($){return new this($).atanh()}function aN0($,Z){$=new this($),Z=new this(Z);var J,Y=this.precision,X=this.rounding,Q=Y+4;if(!$.s||!Z.s)J=new this(NaN);else if(!$.d&&!Z.d)J=y6(this,Q,1).times(Z.s>0?0.25:0.75),J.s=$.s;else if(!Z.d||$.isZero())J=Z.s<0?y6(this,Y,X):new this(0),J.s=$.s;else if(!$.d||Z.isZero())J=y6(this,Q,1).times(0.5),J.s=$.s;else if(Z.s<0)this.precision=Q,this.rounding=1,J=this.atan(h1($,Z,Q,1)),Z=y6(this,Q,1),this.precision=Y,this.rounding=X,J=$.s<0?J.minus(Z):J.plus(Z);else J=this.atan(h1($,Z,Q,1));return J}function tN0($){return new this($).cbrt()}function eN0($){return I0($=new this($),$.e+1,2)}function $M0($,Z,J){return new this($).clamp(Z,J)}function ZM0($){if(!$||typeof $!=="object")throw Error(lK+"Object expected");var Z,J,Y,X=$.defaults===!0,Q=["precision",1,H5,"rounding",0,8,"toExpNeg",-zY,0,"toExpPos",0,zY,"maxE",0,zY,"minE",-zY,0,"modulo",0,9];for(Z=0;Z<Q.length;Z+=3){if(J=Q[Z],X)this[J]=lA[J];if((Y=$[J])!==void 0)if(n$(Y)===Y&&Y>=Q[Z+1]&&Y<=Q[Z+2])this[J]=Y;else throw Error(U5+J+": "+Y)}if(J="crypto",X)this[J]=lA[J];if((Y=$[J])!==void 0)if(Y===!0||Y===!1||Y===0||Y===1)if(Y)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[J]=!0;else throw Error(Ud);else this[J]=!1;else throw Error(U5+J+": "+Y);return this}function JM0($){return new this($).cos()}function YM0($){return new this($).cosh()}function jd($){var Z,J,Y;function X(Q){var G,W,K,V=this;if(!(V instanceof X))return new X(Q);if(V.constructor=X,Wd(Q)){if(V.s=Q.s,i0)if(!Q.d||Q.e>X.maxE)V.e=NaN,V.d=null;else if(Q.e<X.minE)V.e=0,V.d=[0];else V.e=Q.e,V.d=Q.d.slice();else V.e=Q.e,V.d=Q.d?Q.d.slice():Q.d;return}if(K=typeof Q,K==="number"){if(Q===0){V.s=1/Q<0?-1:1,V.e=0,V.d=[0];return}if(Q<0)Q=-Q,V.s=-1;else V.s=1;if(Q===~~Q&&Q<1e7){for(G=0,W=Q;W>=10;W/=10)G++;if(i0)if(G>X.maxE)V.e=NaN,V.d=null;else if(G<X.minE)V.e=0,V.d=[0];else V.e=G,V.d=[Q];else V.e=G,V.d=[Q];return}if(Q*0!==0){if(!Q)V.s=NaN;V.e=NaN,V.d=null;return}return hK(V,Q.toString())}if(K==="string"){if((W=Q.charCodeAt(0))===45)Q=Q.slice(1),V.s=-1;else{if(W===43)Q=Q.slice(1);V.s=1}return Bd.test(Q)?hK(V,Q):mN0(V,Q)}if(K==="bigint"){if(Q<0)Q=-Q,V.s=-1;else V.s=1;return hK(V,Q.toString())}throw Error(U5+Q)}if(X.prototype=X0,X.ROUND_UP=0,X.ROUND_DOWN=1,X.ROUND_CEIL=2,X.ROUND_FLOOR=3,X.ROUND_HALF_UP=4,X.ROUND_HALF_DOWN=5,X.ROUND_HALF_EVEN=6,X.ROUND_HALF_CEIL=7,X.ROUND_HALF_FLOOR=8,X.EUCLID=9,X.config=X.set=ZM0,X.clone=jd,X.isDecimal=Wd,X.abs=dN0,X.acos=pN0,X.acosh=cN0,X.add=iN0,X.asin=nN0,X.asinh=oN0,X.atan=sN0,X.atanh=rN0,X.atan2=aN0,X.cbrt=tN0,X.ceil=eN0,X.clamp=$M0,X.cos=JM0,X.cosh=YM0,X.div=XM0,X.exp=QM0,X.floor=GM0,X.hypot=WM0,X.ln=KM0,X.log=VM0,X.log10=HM0,X.log2=UM0,X.max=BM0,X.min=zM0,X.mod=FM0,X.mul=AM0,X.pow=OM0,X.random=qM0,X.round=jM0,X.sign=NM0,X.sin=MM0,X.sinh=DM0,X.sqrt=wM0,X.sub=LM0,X.sum=TM0,X.tan=RM0,X.tanh=PM0,X.trunc=IM0,$===void 0)$={};if($){if($.defaults!==!0){Y=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"];for(Z=0;Z<Y.length;)if(!$.hasOwnProperty(J=Y[Z++]))$[J]=this[J]}}return X.config($),X}function XM0($,Z){return new this($).div(Z)}function QM0($){return new this($).exp()}function GM0($){return I0($=new this($),$.e+1,3)}function WM0(){var $,Z,J=new this(0);i0=!1;for($=0;$<arguments.length;)if(Z=new this(arguments[$++]),!Z.d){if(Z.s)return i0=!0,new this(1/0);J=Z}else if(J.d)J=J.plus(Z.times(Z));return i0=!0,J.sqrt()}function Wd($){return $ instanceof B6||$&&$.toStringTag===Hd||!1}function KM0($){return new this($).ln()}function VM0($,Z){return new this($).log(Z)}function UM0($){return new this($).log(2)}function HM0($){return new this($).log(10)}function BM0(){return Ad(this,arguments,-1)}function zM0(){return Ad(this,arguments,1)}function FM0($,Z){return new this($).mod(Z)}function AM0($,Z){return new this($).mul(Z)}function OM0($,Z){return new this($).pow(Z)}function qM0($){var Z,J,Y,X,Q=0,G=new this(1),W=[];if($===void 0)$=this.precision;else A8($,1,H5);if(Y=Math.ceil($/x0),!this.crypto)for(;Q<Y;)W[Q++]=Math.random()*1e7|0;else if(crypto.getRandomValues){Z=crypto.getRandomValues(new Uint32Array(Y));for(;Q<Y;)if(X=Z[Q],X>=4290000000)Z[Q]=crypto.getRandomValues(new Uint32Array(1))[0];else W[Q++]=X%1e7}else if(crypto.randomBytes){Z=crypto.randomBytes(Y*=4);for(;Q<Y;)if(X=Z[Q]+(Z[Q+1]<<8)+(Z[Q+2]<<16)+((Z[Q+3]&127)<<24),X>=2140000000)crypto.randomBytes(4).copy(Z,Q);else W.push(X%1e7),Q+=4;Q=Y/4}else throw Error(Ud);if(Y=W[--Q],$%=x0,Y&&$)X=q$(10,x0-$),W[Q]=(Y/X|0)*X;for(;W[Q]===0;Q--)W.pop();if(Q<0)J=0,W=[0];else{J=-1;for(;W[0]===0;J-=x0)W.shift();for(Y=1,X=W[0];X>=10;X/=10)Y++;if(Y<x0)J-=x0-Y}return G.e=J,G.d=W,G}function jM0($){return I0($=new this($),$.e+1,this.rounding)}function NM0($){return $=new this($),$.d?$.d[0]?$.s:0*$.s:$.s||NaN}function MM0($){return new this($).sin()}function DM0($){return new this($).sinh()}function wM0($){return new this($).sqrt()}function LM0($,Z){return new this($).sub(Z)}function TM0(){var $=0,Z=arguments,J=new this(Z[$]);i0=!1;for(;J.s&&++$<Z.length;)J=J.plus(Z[$]);return i0=!0,I0(J,this.precision,this.rounding)}function RM0($){return new this($).tan()}function PM0($){return new this($).tanh()}function IM0($){return I0($=new this($),$.e+1,1)}X0[Symbol.for("nodejs.util.inspect.custom")]=X0.toString;X0[Symbol.toStringTag]="Decimal";var B6=X0.constructor=jd(lA);gK=new B6(gK);uK=new B6(uK);var CM0=O.String.annotate({[F$]:d1.schema("workspace")}).pipe(O.brand("WorkspaceID")),iA=CM0.pipe(u0(($)=>({ascending:(Z)=>$.make(d1.ascending("workspace",Z)),zod:d1.schema("workspace").pipe(P.custom())})));function cK($){let Z={};for(let[J,Y]of Object.entries($.required().shape))Z[J]=Y.nullable();return P.object(Z)}var Nd=E0.create({service:"session.usage"});function EM0($){return/^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test($)}function OY($){let Z=$.summary_additions!==null||$.summary_deletions!==null||$.summary_files!==null?{additions:$.summary_additions??0,deletions:$.summary_deletions??0,files:$.summary_files??0,diffs:$.summary_diffs??void 0}:void 0,J=$.share_url?{url:$.share_url}:void 0,Y=$.revert??void 0;return{id:$.id,slug:$.slug,projectID:$.project_id,workspaceID:$.workspace_id??void 0,directory:$.directory,parentID:$.parent_id??void 0,contextFrom:$.context_from??void 0,contextWatermark:$.context_watermark??void 0,title:$.title,version:$.version,summary:Z,share:J,revert:Y,permission:$.permission??void 0,time:{created:$.time_created,updated:$.time_updated,compacting:$.time_compacting??void 0,archived:$.time_archived??void 0}}}function bM0($){return{id:$.id,project_id:$.projectID,workspace_id:$.workspaceID,parent_id:$.parentID,context_from:$.contextFrom,context_watermark:$.contextWatermark,slug:$.slug,directory:$.directory,title:$.title,version:$.version,share_url:$.share?.url,summary_additions:$.summary?.additions,summary_deletions:$.summary?.deletions,summary_files:$.summary?.files,summary_diffs:$.summary?.diffs,revert:$.revert??null,permission:$.permission,time_created:$.time.created,time_updated:$.time.updated,time_compacting:$.time.compacting,time_archived:$.time.archived}}var z6=P.object({id:r0.zod,slug:P.string(),projectID:$9.zod,workspaceID:iA.zod.optional(),directory:P.string(),parentID:r0.zod.optional(),contextFrom:r0.zod.optional(),contextWatermark:i1.zod.optional(),summary:P.object({additions:P.number(),deletions:P.number(),files:P.number(),diffs:vZ.FileDiff.array().optional()}).optional(),share:P.object({url:P.string()}).optional(),title:P.string(),version:P.string(),time:P.object({created:P.number(),updated:P.number(),compacting:P.number().optional(),archived:P.number().optional()}),permission:Q5.Ruleset.zod.optional(),revert:P.object({messageID:i1.zod,partID:MZ.zod.optional(),snapshot:P.string().optional(),diff:P.string().optional()}).optional()}).meta({ref:"Session"}),Md=P.object({id:$9.zod,name:P.string().optional(),worktree:P.string()}).meta({ref:"ProjectSummary"}),_M0=z6.extend({project:Md.nullable()}).meta({ref:"GlobalSession"}),SM0=P.object({parentID:r0.zod.optional(),contextFrom:r0.zod.optional(),contextWatermark:i1.zod.optional(),title:P.string().optional(),permission:z6.shape.permission,workspaceID:iA.zod.optional()}).optional(),fM0=P.object({sessionID:r0.zod,messageID:i1.zod.optional()}),kM0=r0.zod,vM0=r0.zod,yM0=r0.zod,xM0=P.object({sessionID:r0.zod,title:P.string()}),hM0=P.object({sessionID:r0.zod,time:P.number().optional()}),gM0=P.object({sessionID:r0.zod,permission:Q5.Ruleset.zod}),uM0=P.object({sessionID:r0.zod,revert:z6.shape.revert,summary:z6.shape.summary}),mM0=P.object({sessionID:r0.zod,limit:P.number().optional()}),qY={Created:X$.define({type:"session.created",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:z6})}),Updated:X$.define({type:"session.updated",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:cK(z6).extend({share:cK(z6.shape.share.unwrap()).optional(),time:cK(z6.shape.time).optional()})}),busSchema:P.object({sessionID:r0.zod,info:z6})}),Deleted:X$.define({type:"session.deleted",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:z6})}),Diff:L1.define("session.diff",P.object({sessionID:r0.zod,diff:vZ.FileDiff.array()})),Error:L1.define("session.error",P.object({sessionID:r0.zod.optional(),error:P.lazy(()=>b$.Assistant.shape.error)})),RetryAttempt:L1.define("session.retry.attempt",P.object({sessionID:r0.zod,messageID:P.string(),attempt:P.number().int().min(1),maxAttempts:P.number().int().min(1),reason:P.string(),nextDelayMs:P.number().int().nonnegative()}))};function lM0($){let Z=S8.project.vcs?nA.join(S8.worktree,".qitqode","plans"):nA.join(F0.Path.data,"plans");return nA.join(Z,[$.time.created,$.slug].join("-")+".md")}var dM0=($)=>{let Z=(j)=>{if(!Number.isFinite(j))return 0;return j},J=Z($.usage.inputTokens??0),Y=Z($.usage.outputTokens??0),X=Z($.usage.outputTokenDetails?.reasoningTokens??$.usage.reasoningTokens??0),Q=Z($.usage.inputTokenDetails?.cacheReadTokens??$.usage.cachedInputTokens??0),G=Z(Number($.usage.inputTokenDetails?.cacheWriteTokens??$.metadata?.anthropic?.cacheCreationInputTokens??$.metadata?.vertex?.cacheCreationInputTokens??$.metadata?.bedrock?.usage?.cacheWriteInputTokens??$.metadata?.venice?.usage?.cacheCreationInputTokens??0)),W=Z(J-Q-G),V={total:$.usage.totalTokens,input:W,output:Z(Y-X),reasoning:X,cache:{write:G,read:Q}},U=$.usage.raw,H=typeof U?.cost_usd==="number"?U.cost_usd:void 0,B=typeof U?.cost_credits==="number"?U.cost_credits:void 0,z=typeof U?.context_window==="number"?U.context_window:void 0;if(H!==void 0){let j={cost:Z(H),costCredits:Z(B??H),tokens:V,contextWindow:z};return Nd.info("usage",{provider:$.model.providerID,model:$.model.id,source:"qlex",tokens:V,cost:j.cost,costCredits:j.costCredits}),j}let F=$.model.cost?.experimentalOver200K&&V.input+V.cache.read>200000?$.model.cost.experimentalOver200K:$.model.cost,A=Z(new B6(0).add(new B6(V.input).mul(F?.input??0).div(1e6)).add(new B6(V.output).mul(F?.output??0).div(1e6)).add(new B6(V.cache.read).mul(F?.cache?.read??0).div(1e6)).add(new B6(V.cache.write).mul(F?.cache?.write??0).div(1e6)).add(new B6(V.reasoning).mul(F?.output??0).div(1e6)).toNumber());return Nd.info("usage",{provider:$.model.providerID,model:$.model.id,source:"estimated",tokens:V,cost:A}),{cost:A,costCredits:void 0,tokens:V,contextWindow:z}};function*pM0($){let Z=S8.project,J=[m0(I1.project_id,Z.id)];if($?.workspaceID)J.push(m0(I1.workspace_id,$.workspaceID));if(!b0.QITQODE_EXPERIMENTAL_WORKSPACES){if($?.directory)J.push(m0(I1.directory,$.directory))}if($?.roots)J.push(iK(I1.parent_id));if($?.start)J.push(oA(I1.time_updated,$.start));if($?.search)J.push(sA(I1.title,`%${$.search}%`));let Y=$?.limit??100,X=W1.use((Q)=>Q.select().from(I1).where(O$(...J)).orderBy(o6(I1.time_updated)).limit(Y).all());for(let Q of X)yield OY(Q)}function*cM0($){let Z=[];if($?.directory)Z.push(m0(I1.directory,$.directory));if($?.roots)Z.push(iK(I1.parent_id));if($?.start)Z.push(oA(I1.time_updated,$.start));if($?.cursor)Z.push(WX(I1.time_updated,$.cursor));if($?.search)Z.push(sA(I1.title,`%${$.search}%`));if(!$?.archived)Z.push(iK(I1.time_archived));let J=$?.limit??100,Y=W1.use((G)=>{return(Z.length>0?G.select().from(I1).where(O$(...Z)):G.select().from(I1)).orderBy(o6(I1.time_updated),o6(I1.id)).limit(J).all()}),X=[...new Set(Y.map((G)=>G.project_id))],Q=new Map;if(X.length>0){let G=W1.use((W)=>W.select({id:AY.id,name:AY.name,worktree:AY.worktree}).from(AY).where(k5(AY.id,X)).all());for(let W of G)Q.set(W.id,{id:W.id,name:W.name??void 0,worktree:W.worktree})}for(let G of Y){let W=Q.get(G.project_id)??null;yield{...OY(G),project:W}}}var Dd=E0.create({service:"session"}),iM0="New session - ",nM0="Child session - ";function oM0($=!1){return($?nM0:iM0)+new Date().toISOString()}function sM0($){let Z=$.match(/^(.+) \(fork #(\d+)\)$/);if(Z){let J=Z[1],Y=parseInt(Z[2],10);return`${J} (fork #${Y+1})`}return`${$} (fork #1)`}class wd extends Error{sessionID;constructor($){super(`Session ${$} is busy`);this.sessionID=$}}class nK extends S1.Service()("@qitqode/Session"){}var rA=($)=>T.sync(()=>W1.use($)),Ld=T0.effect(nK,T.gen(function*(){let $=yield*l1.Service,Z=yield*aA.Service,J=yield*BY.Service,Y=T.fn("Session.createNext")(function*(b){let y=yield*B0.context,k={id:r0.descending(b.id),slug:JV.create(),version:E$,projectID:y.project.id,directory:b.directory,workspaceID:b.workspaceID,parentID:b.parentID,contextFrom:b.contextFrom,contextWatermark:b.contextWatermark,title:b.title??oM0(!!b.parentID),permission:b.permission,time:{created:Date.now(),updated:Date.now()}};if(Dd.info("created",k),yield*T.sync(()=>X$.run(qY.Created,{sessionID:k.id,info:k})),yield*J.register({sessionID:k.id,actorID:"main",mode:"main",parentActorID:void 0,agent:"main",description:"main agent",contextMode:"full",contextWatermark:void 0,background:!1,lifecycle:"persistent",tools:"INHERIT"}).pipe(T.ignore),!b0.QITQODE_EXPERIMENTAL_WORKSPACES)yield*$.publish(qY.Updated,{sessionID:k.id,info:k});return k}),X=T.fn("Session.get")(function*(b){let y=yield*rA((k)=>k.select().from(I1).where(m0(I1.id,b)).get());if(!y)throw new KX({message:`Session not found: ${b}`});return OY(y)}),Q=T.fn("Session.children")(function*(b){return(yield*rA((k)=>k.select().from(I1).where(O$(m0(I1.parent_id,b))).all())).map(OY)}),G=T.fnUntraced(function*(b){try{let y=yield*X(b),k=yield*Q(b);for(let d of k)yield*G(d.id);let g=yield*B0.directory.pipe(T.as(!0),T.catchCause(()=>T.succeed(!1)));yield*T.sync(()=>{X$.run(qY.Deleted,{sessionID:b,info:y},{publish:g}),X$.remove(b)})}catch(y){Dd.error(y)}}),W=(b)=>T.gen(function*(){return yield*T.sync(()=>X$.run(b$.Event.Updated,{sessionID:b.sessionID,info:b})),b}).pipe(T.withSpan("Session.updateMessage")),K=(b)=>{let y={...b};if(y.state){if(y.state={...y.state},y.state.time)y.state.time={...y.state.time}}return y},V=(b)=>T.gen(function*(){return yield*T.sync(()=>X$.run(b$.Event.PartUpdated,{sessionID:b.sessionID,part:K(b),time:Date.now()})),b}).pipe(T.withSpan("Session.updatePart")),U=T.fn("Session.getPart")(function*(b){let y=W1.use((k)=>k.select().from(I8).where(O$(m0(I8.session_id,b.sessionID),m0(I8.message_id,b.messageID),m0(I8.id,b.partID))).get());if(!y)return;return{...y.data,id:y.id,sessionID:y.session_id,messageID:y.message_id}}),H=T.fn("Session.create")(function*(b){let y=yield*B0.directory,k=yield*B0.workspaceID;return yield*Y({parentID:b?.parentID,contextFrom:b?.contextFrom,contextWatermark:b?.contextWatermark,directory:y,title:b?.title,permission:b?.permission,workspaceID:k})}),B=T.fn("Session.fork")(function*(b){let y=yield*B0.directory,k=yield*X(b.sessionID),g=sM0(k.title),d=yield*Y({directory:y,workspaceID:k.workspaceID,title:g}),p=yield*R({sessionID:b.sessionID,agentID:"*"}),t=new Map;for(let r of p){if(b.messageID&&r.info.id>=b.messageID)break;let G0=i1.ascending();t.set(r.info.id,G0);let O0=r.info.role==="assistant"&&r.info.parentID?t.get(r.info.parentID):void 0,h0=yield*W({...r.info,sessionID:d.id,id:G0,...O0&&{parentID:O0}});for(let u of r.parts)yield*V({...u,id:MZ.ascending(),messageID:h0.id,sessionID:d.id})}return d}),z=(b,y)=>T.sync(()=>X$.run(qY.Updated,{sessionID:b,info:y})),F=T.fn("Session.touch")(function*(b){yield*z(b,{time:{updated:Date.now()}})}),A=T.fn("Session.setTitle")(function*(b){yield*z(b.sessionID,{title:b.title})}),j=T.fn("Session.setArchived")(function*(b){yield*z(b.sessionID,{time:{archived:b.time}})}),N=T.fn("Session.setPermission")(function*(b){yield*z(b.sessionID,{permission:b.permission,time:{updated:Date.now()}})}),L=T.fn("Session.setRevert")(function*(b){yield*z(b.sessionID,{summary:b.summary,time:{updated:Date.now()},revert:b.revert})}),q=T.fn("Session.clearRevert")(function*(b){yield*z(b,{time:{updated:Date.now()},revert:null})}),M=T.fn("Session.setSummary")(function*(b){yield*z(b.sessionID,{time:{updated:Date.now()},summary:b.summary})}),C=T.fn("Session.diff")(function*(b){return yield*Z.read(["session_diff",b]).pipe(T.orElseSucceed(()=>[]))}),R=T.fn("Session.messages")(function*(b){if(b.limit)return b$.page({sessionID:b.sessionID,limit:b.limit,agentID:b.agentID}).items;return Array.from(b$.stream(b.sessionID,{agentID:b.agentID})).reverse()}),w=T.fn("Session.removeMessage")(function*(b){return yield*T.sync(()=>X$.run(b$.Event.Removed,{sessionID:b.sessionID,messageID:b.messageID})),b.messageID}),I=T.fn("Session.removePart")(function*(b){return yield*T.sync(()=>X$.run(b$.Event.PartRemoved,{sessionID:b.sessionID,messageID:b.messageID,partID:b.partID})),b.partID}),_=T.fnUntraced(function*(b){yield*$.publish(b$.Event.PartDelta,b)}),E=T.fn("Session.findMessage")(function*(b,y,k){for(let g of b$.stream(b,{agentID:k?.agentID}))if(y(g))return O1.some(g);return O1.none()}),f=T.fn("Session.lastMainMessageID")(function*(b){return(yield*rA((k)=>k.select({id:w$.id}).from(w$).where(O$(m0(w$.session_id,b),m0(w$.agent_id,"main"))).orderBy(o6(w$.id)).limit(1).get()))?.id});return nK.of({create:H,fork:B,touch:F,get:X,setTitle:A,setArchived:j,setPermission:N,setRevert:L,clearRevert:q,setSummary:M,diff:C,messages:R,children:Q,remove:G,updateMessage:W,removeMessage:w,removePart:I,updatePart:V,getPart:U,updatePartDelta:_,findMessage:E,lastMainMessageID:f})})),rM0=Ld.pipe(T0.provide(BY.defaultLayer),T0.provide(l1.layer),T0.provide(aA.defaultLayer));export{l1 as Nj,k8 as Oj,hY as Pj,v9 as Qj,d7 as Rj,o7 as Sj,JN as Tj,IZ as Uj,nD as Vj,rD as Wj,bU as Xj,JV as Yj,_8 as Zj,z9 as _j,d1 as $j,X$ as ak,r0 as bk,i1 as ck,MZ as dk,Vj as ek,xV as fk,X4 as gk,G4 as hk,vU as ik,za as jk,QX as kk,VJ as lk,Aa as mk,vw as nk,vZ as ok,X1 as pk,s1 as qk,tb0 as rk,K_0 as sk,U_0 as tk,B_0 as uk,ne as vk,y_0 as wk,x_0 as xk,UW as yk,d3 as zk,BK as Ak,rQ as Bk,aQ as Ck,dh0 as Dk,ph0 as Ek,ch0 as Fk,Gj0 as Gk,sh0 as Hk,rh0 as Ik,tu as Jk,ah0 as Kk,$m as Lk,Zm as Mk,q7 as Nk,Q5 as Ok,Vm as Pk,jj0 as Qk,Eg0 as Rk,Um as Sk,gg0 as Tk,mg0 as Uk,lg0 as Vk,IA as Wk,km as Xk,iA as Yk,Xu0 as Zk,Qu0 as _k,el as $k,Hd0 as al,Bd0 as bl,Zd as cl,BY as dl,EA as el,AZ as fl,X9 as gl,N7 as hl,gl as il,sl as jl,b$ as kl,EM0 as ll,bM0 as ml,qY as nl,lM0 as ol,dM0 as pl,wd as ql,nK as rl,rM0 as sl,Y9 as tl,X8 as ul};
808
+ */var zY=9000000000000000,H5=1e9,mA="0123456789abcdef",gK="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",uK="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",lA={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-zY,maxE:zY,crypto:!1},Kd,qZ,i0=!0,lK="[DecimalError] ",U5=lK+"Invalid argument: ",Vd=lK+"Precision limit exceeded",Ud=lK+"crypto unavailable",Hd="[object Decimal]",n$=Math.floor,q$=Math.pow,vN0=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,yN0=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,xN0=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Bd=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,H6=1e7,x0=7,hN0=9007199254740991,gN0=gK.length-1,dA=uK.length-1,X0={toStringTag:Hd};X0.absoluteValue=X0.abs=function(){var $=new this.constructor(this);if($.s<0)$.s=1;return I0($)};X0.ceil=function(){return I0(new this.constructor(this),this.e+1,2)};X0.clampedTo=X0.clamp=function($,Z){var J,Y=this,X=Y.constructor;if($=new X($),Z=new X(Z),!$.s||!Z.s)return new X(NaN);if($.gt(Z))throw Error(U5+Z);return J=Y.cmp($),J<0?$:Y.cmp(Z)>0?Z:new X(Y)};X0.comparedTo=X0.cmp=function($){var Z,J,Y,X,Q=this,G=Q.d,W=($=new Q.constructor($)).d,K=Q.s,V=$.s;if(!G||!W)return!K||!V?NaN:K!==V?K:G===W?0:!G^K<0?1:-1;if(!G[0]||!W[0])return G[0]?K:W[0]?-V:0;if(K!==V)return K;if(Q.e!==$.e)return Q.e>$.e^K<0?1:-1;Y=G.length,X=W.length;for(Z=0,J=Y<X?Y:X;Z<J;++Z)if(G[Z]!==W[Z])return G[Z]>W[Z]^K<0?1:-1;return Y===X?0:Y>X^K<0?1:-1};X0.cosine=X0.cos=function(){var $,Z,J=this,Y=J.constructor;if(!J.d)return new Y(NaN);if(!J.d[0])return new Y(1);return $=Y.precision,Z=Y.rounding,Y.precision=$+Math.max(J.e,J.sd())+x0,Y.rounding=1,J=uN0(Y,qd(Y,J)),Y.precision=$,Y.rounding=Z,I0(qZ==2||qZ==3?J.neg():J,$,Z,!0)};X0.cubeRoot=X0.cbrt=function(){var $,Z,J,Y,X,Q,G,W,K,V,U=this,H=U.constructor;if(!U.isFinite()||U.isZero())return new H(U);if(i0=!1,Q=U.s*q$(U.s*U,0.3333333333333333),!Q||Math.abs(Q)==1/0){if(J=v$(U.d),$=U.e,Q=($-J.length+1)%3)J+=Q==1||Q==-2?"0":"00";if(Q=q$(J,0.3333333333333333),$=n$(($+1)/3)-($%3==($<0?-1:2)),Q==1/0)J="5e"+$;else J=Q.toExponential(),J=J.slice(0,J.indexOf("e")+1)+$;Y=new H(J),Y.s=U.s}else Y=new H(Q.toString());G=($=H.precision)+3;for(;;)if(W=Y,K=W.times(W).times(W),V=K.plus(U),Y=h1(V.plus(U).times(W),V.plus(K),G+2,1),v$(W.d).slice(0,G)===(J=v$(Y.d)).slice(0,G))if(J=J.slice(G-3,G+1),J=="9999"||!X&&J=="4999"){if(!X){if(I0(W,$+1,0),W.times(W).times(W).eq(U)){Y=W;break}}G+=4,X=1}else{if(!+J||!+J.slice(1)&&J.charAt(0)=="5")I0(Y,$+1,1),Z=!Y.times(Y).times(Y).eq(U);break}return i0=!0,I0(Y,$,H.rounding,Z)};X0.decimalPlaces=X0.dp=function(){var $,Z=this.d,J=NaN;if(Z){if($=Z.length-1,J=($-n$(this.e/x0))*x0,$=Z[$],$)for(;$%10==0;$/=10)J--;if(J<0)J=0}return J};X0.dividedBy=X0.div=function($){return h1(this,new this.constructor($))};X0.dividedToIntegerBy=X0.divToInt=function($){var Z=this,J=Z.constructor;return I0(h1(Z,new J($),0,1,1),J.precision,J.rounding)};X0.equals=X0.eq=function($){return this.cmp($)===0};X0.floor=function(){return I0(new this.constructor(this),this.e+1,3)};X0.greaterThan=X0.gt=function($){return this.cmp($)>0};X0.greaterThanOrEqualTo=X0.gte=function($){var Z=this.cmp($);return Z==1||Z===0};X0.hyperbolicCosine=X0.cosh=function(){var $,Z,J,Y,X,Q=this,G=Q.constructor,W=new G(1);if(!Q.isFinite())return new G(Q.s?1/0:NaN);if(Q.isZero())return W;if(J=G.precision,Y=G.rounding,G.precision=J+Math.max(Q.e,Q.sd())+4,G.rounding=1,X=Q.d.length,X<32)$=Math.ceil(X/3),Z=(1/pK(4,$)).toString();else $=16,Z="2.3283064365386962890625e-10";Q=FY(G,1,Q.times(Z),new G(1),!0);var K,V=$,U=new G(8);for(;V--;)K=Q.times(Q),Q=W.minus(K.times(U.minus(K.times(U))));return I0(Q,G.precision=J,G.rounding=Y,!0)};X0.hyperbolicSine=X0.sinh=function(){var $,Z,J,Y,X=this,Q=X.constructor;if(!X.isFinite()||X.isZero())return new Q(X);if(Z=Q.precision,J=Q.rounding,Q.precision=Z+Math.max(X.e,X.sd())+4,Q.rounding=1,Y=X.d.length,Y<3)X=FY(Q,2,X,X,!0);else{$=1.4*Math.sqrt(Y),$=$>16?16:$|0,X=X.times(1/pK(5,$)),X=FY(Q,2,X,X,!0);var G,W=new Q(5),K=new Q(16),V=new Q(20);for(;$--;)G=X.times(X),X=X.times(W.plus(G.times(K.times(G).plus(V))))}return Q.precision=Z,Q.rounding=J,I0(X,Z,J,!0)};X0.hyperbolicTangent=X0.tanh=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite())return new Y(J.s);if(J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+7,Y.rounding=1,h1(J.sinh(),J.cosh(),Y.precision=$,Y.rounding=Z)};X0.inverseCosine=X0.acos=function(){var $=this,Z=$.constructor,J=$.abs().cmp(1),Y=Z.precision,X=Z.rounding;if(J!==-1)return J===0?$.isNeg()?y6(Z,Y,X):new Z(0):new Z(NaN);if($.isZero())return y6(Z,Y+4,X).times(0.5);return Z.precision=Y+6,Z.rounding=1,$=new Z(1).minus($).div($.plus(1)).sqrt().atan(),Z.precision=Y,Z.rounding=X,$.times(2)};X0.inverseHyperbolicCosine=X0.acosh=function(){var $,Z,J=this,Y=J.constructor;if(J.lte(1))return new Y(J.eq(1)?0:NaN);if(!J.isFinite())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+Math.max(Math.abs(J.e),J.sd())+4,Y.rounding=1,i0=!1,J=J.times(J).minus(1).sqrt().plus(J),i0=!0,Y.precision=$,Y.rounding=Z,J.ln()};X0.inverseHyperbolicSine=X0.asinh=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite()||J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+2*Math.max(Math.abs(J.e),J.sd())+6,Y.rounding=1,i0=!1,J=J.times(J).plus(1).sqrt().plus(J),i0=!0,Y.precision=$,Y.rounding=Z,J.ln()};X0.inverseHyperbolicTangent=X0.atanh=function(){var $,Z,J,Y,X=this,Q=X.constructor;if(!X.isFinite())return new Q(NaN);if(X.e>=0)return new Q(X.abs().eq(1)?X.s/0:X.isZero()?X:NaN);if($=Q.precision,Z=Q.rounding,Y=X.sd(),Math.max(Y,$)<2*-X.e-1)return I0(new Q(X),$,Z,!0);return Q.precision=J=Y-X.e,X=h1(X.plus(1),new Q(1).minus(X),J+$,1),Q.precision=$+4,Q.rounding=1,X=X.ln(),Q.precision=$,Q.rounding=Z,X.times(0.5)};X0.inverseSine=X0.asin=function(){var $,Z,J,Y,X=this,Q=X.constructor;if(X.isZero())return new Q(X);if(Z=X.abs().cmp(1),J=Q.precision,Y=Q.rounding,Z!==-1){if(Z===0)return $=y6(Q,J+4,Y).times(0.5),$.s=X.s,$;return new Q(NaN)}return Q.precision=J+6,Q.rounding=1,X=X.div(new Q(1).minus(X.times(X)).sqrt().plus(1)).atan(),Q.precision=J,Q.rounding=Y,X.times(2)};X0.inverseTangent=X0.atan=function(){var $,Z,J,Y,X,Q,G,W,K,V=this,U=V.constructor,H=U.precision,B=U.rounding;if(!V.isFinite()){if(!V.s)return new U(NaN);if(H+4<=dA)return G=y6(U,H+4,B).times(0.5),G.s=V.s,G}else if(V.isZero())return new U(V);else if(V.abs().eq(1)&&H+4<=dA)return G=y6(U,H+4,B).times(0.25),G.s=V.s,G;U.precision=W=H+10,U.rounding=1,J=Math.min(28,W/x0+2|0);for($=J;$;--$)V=V.div(V.times(V).plus(1).sqrt().plus(1));i0=!1,Z=Math.ceil(W/x0),Y=1,K=V.times(V),G=new U(V),X=V;for(;$!==-1;)if(X=X.times(K),Q=G.minus(X.div(Y+=2)),X=X.times(K),G=Q.plus(X.div(Y+=2)),G.d[Z]!==void 0)for($=Z;G.d[$]===Q.d[$]&&$--;);if(J)G=G.times(2<<J-1);return i0=!0,I0(G,U.precision=H,U.rounding=B,!0)};X0.isFinite=function(){return!!this.d};X0.isInteger=X0.isInt=function(){return!!this.d&&n$(this.e/x0)>this.d.length-2};X0.isNaN=function(){return!this.s};X0.isNegative=X0.isNeg=function(){return this.s<0};X0.isPositive=X0.isPos=function(){return this.s>0};X0.isZero=function(){return!!this.d&&this.d[0]===0};X0.lessThan=X0.lt=function($){return this.cmp($)<0};X0.lessThanOrEqualTo=X0.lte=function($){return this.cmp($)<1};X0.logarithm=X0.log=function($){var Z,J,Y,X,Q,G,W,K,V=this,U=V.constructor,H=U.precision,B=U.rounding,z=5;if($==null)$=new U(10),Z=!0;else{if($=new U($),J=$.d,$.s<0||!J||!J[0]||$.eq(1))return new U(NaN);Z=$.eq(10)}if(J=V.d,V.s<0||!J||!J[0]||V.eq(1))return new U(J&&!J[0]?-1/0:V.s!=1?NaN:J?0:1/0);if(Z)if(J.length>1)Q=!0;else{for(X=J[0];X%10===0;)X/=10;Q=X!==1}if(i0=!1,W=H+z,G=V5(V,W),Y=Z?mK(U,W+10):V5($,W),K=h1(G,Y,W,1),V9(K.d,X=H,B))do if(W+=10,G=V5(V,W),Y=Z?mK(U,W+10):V5($,W),K=h1(G,Y,W,1),!Q){if(+v$(K.d).slice(X+1,X+15)+1==100000000000000)K=I0(K,H+1,0);break}while(V9(K.d,X+=10,B));return i0=!0,I0(K,H,B)};X0.minus=X0.sub=function($){var Z,J,Y,X,Q,G,W,K,V,U,H,B,z=this,F=z.constructor;if($=new F($),!z.d||!$.d){if(!z.s||!$.s)$=new F(NaN);else if(z.d)$.s=-$.s;else $=new F($.d||z.s!==$.s?z:NaN);return $}if(z.s!=$.s)return $.s=-$.s,z.plus($);if(V=z.d,B=$.d,W=F.precision,K=F.rounding,!V[0]||!B[0]){if(B[0])$.s=-$.s;else if(V[0])$=new F(z);else return new F(K===3?-0:0);return i0?I0($,W,K):$}if(J=n$($.e/x0),U=n$(z.e/x0),V=V.slice(),Q=U-J,Q){if(H=Q<0,H)Z=V,Q=-Q,G=B.length;else Z=B,J=U,G=V.length;if(Y=Math.max(Math.ceil(W/x0),G)+2,Q>Y)Q=Y,Z.length=1;Z.reverse();for(Y=Q;Y--;)Z.push(0);Z.reverse()}else{if(Y=V.length,G=B.length,H=Y<G,H)G=Y;for(Y=0;Y<G;Y++)if(V[Y]!=B[Y]){H=V[Y]<B[Y];break}Q=0}if(H)Z=V,V=B,B=Z,$.s=-$.s;G=V.length;for(Y=B.length-G;Y>0;--Y)V[G++]=0;for(Y=B.length;Y>Q;){if(V[--Y]<B[Y]){for(X=Y;X&&V[--X]===0;)V[X]=H6-1;--V[X],V[Y]+=H6}V[Y]-=B[Y]}for(;V[--G]===0;)V.pop();for(;V[0]===0;V.shift())--J;if(!V[0])return new F(K===3?-0:0);return $.d=V,$.e=dK(V,J),i0?I0($,W,K):$};X0.modulo=X0.mod=function($){var Z,J=this,Y=J.constructor;if($=new Y($),!J.d||!$.s||$.d&&!$.d[0])return new Y(NaN);if(!$.d||J.d&&!J.d[0])return I0(new Y(J),Y.precision,Y.rounding);if(i0=!1,Y.modulo==9)Z=h1(J,$.abs(),0,3,1),Z.s*=$.s;else Z=h1(J,$,0,Y.modulo,1);return Z=Z.times($),i0=!0,J.minus(Z)};X0.naturalExponential=X0.exp=function(){return pA(this)};X0.naturalLogarithm=X0.ln=function(){return V5(this)};X0.negated=X0.neg=function(){var $=new this.constructor(this);return $.s=-$.s,I0($)};X0.plus=X0.add=function($){var Z,J,Y,X,Q,G,W,K,V,U,H=this,B=H.constructor;if($=new B($),!H.d||!$.d){if(!H.s||!$.s)$=new B(NaN);else if(!H.d)$=new B($.d||H.s===$.s?H:NaN);return $}if(H.s!=$.s)return $.s=-$.s,H.minus($);if(V=H.d,U=$.d,W=B.precision,K=B.rounding,!V[0]||!U[0]){if(!U[0])$=new B(H);return i0?I0($,W,K):$}if(Q=n$(H.e/x0),Y=n$($.e/x0),V=V.slice(),X=Q-Y,X){if(X<0)J=V,X=-X,G=U.length;else J=U,Y=Q,G=V.length;if(Q=Math.ceil(W/x0),G=Q>G?Q+1:G+1,X>G)X=G,J.length=1;J.reverse();for(;X--;)J.push(0);J.reverse()}if(G=V.length,X=U.length,G-X<0)X=G,J=U,U=V,V=J;for(Z=0;X;)Z=(V[--X]=V[X]+U[X]+Z)/H6|0,V[X]%=H6;if(Z)V.unshift(Z),++Y;for(G=V.length;V[--G]==0;)V.pop();return $.d=V,$.e=dK(V,Y),i0?I0($,W,K):$};X0.precision=X0.sd=function($){var Z,J=this;if($!==void 0&&$!==!!$&&$!==1&&$!==0)throw Error(U5+$);if(J.d){if(Z=zd(J.d),$&&J.e+1>Z)Z=J.e+1}else Z=NaN;return Z};X0.round=function(){var $=this,Z=$.constructor;return I0(new Z($),$.e+1,Z.rounding)};X0.sine=X0.sin=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+Math.max(J.e,J.sd())+x0,Y.rounding=1,J=lN0(Y,qd(Y,J)),Y.precision=$,Y.rounding=Z,I0(qZ>2?J.neg():J,$,Z,!0)};X0.squareRoot=X0.sqrt=function(){var $,Z,J,Y,X,Q,G=this,W=G.d,K=G.e,V=G.s,U=G.constructor;if(V!==1||!W||!W[0])return new U(!V||V<0&&(!W||W[0])?NaN:W?G:1/0);if(i0=!1,V=Math.sqrt(+G),V==0||V==1/0){if(Z=v$(W),(Z.length+K)%2==0)Z+="0";if(V=Math.sqrt(Z),K=n$((K+1)/2)-(K<0||K%2),V==1/0)Z="5e"+K;else Z=V.toExponential(),Z=Z.slice(0,Z.indexOf("e")+1)+K;Y=new U(Z)}else Y=new U(V.toString());J=(K=U.precision)+3;for(;;)if(Q=Y,Y=Q.plus(h1(G,Q,J+2,1)).times(0.5),v$(Q.d).slice(0,J)===(Z=v$(Y.d)).slice(0,J))if(Z=Z.slice(J-3,J+1),Z=="9999"||!X&&Z=="4999"){if(!X){if(I0(Q,K+1,0),Q.times(Q).eq(G)){Y=Q;break}}J+=4,X=1}else{if(!+Z||!+Z.slice(1)&&Z.charAt(0)=="5")I0(Y,K+1,1),$=!Y.times(Y).eq(G);break}return i0=!0,I0(Y,K,U.rounding,$)};X0.tangent=X0.tan=function(){var $,Z,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.isZero())return new Y(J);return $=Y.precision,Z=Y.rounding,Y.precision=$+10,Y.rounding=1,J=J.sin(),J.s=1,J=h1(J,new Y(1).minus(J.times(J)).sqrt(),$+10,0),Y.precision=$,Y.rounding=Z,I0(qZ==2||qZ==4?J.neg():J,$,Z,!0)};X0.times=X0.mul=function($){var Z,J,Y,X,Q,G,W,K,V,U=this,H=U.constructor,B=U.d,z=($=new H($)).d;if($.s*=U.s,!B||!B[0]||!z||!z[0])return new H(!$.s||B&&!B[0]&&!z||z&&!z[0]&&!B?NaN:!B||!z?$.s/0:$.s*0);if(J=n$(U.e/x0)+n$($.e/x0),K=B.length,V=z.length,K<V)Q=B,B=z,z=Q,G=K,K=V,V=G;Q=[],G=K+V;for(Y=G;Y--;)Q.push(0);for(Y=V;--Y>=0;){Z=0;for(X=K+Y;X>Y;)W=Q[X]+z[Y]*B[X-Y-1]+Z,Q[X--]=W%H6|0,Z=W/H6|0;Q[X]=(Q[X]+Z)%H6|0}for(;!Q[--G];)Q.pop();if(Z)++J;else Q.shift();return $.d=Q,$.e=dK(Q,J),i0?I0($,H.precision,H.rounding):$};X0.toBinary=function($,Z){return cA(this,2,$,Z)};X0.toDecimalPlaces=X0.toDP=function($,Z){var J=this,Y=J.constructor;if(J=new Y(J),$===void 0)return J;if(A8($,0,H5),Z===void 0)Z=Y.rounding;else A8(Z,0,8);return I0(J,$+J.e+1,Z)};X0.toExponential=function($,Z){var J,Y=this,X=Y.constructor;if($===void 0)J=x6(Y,!0);else{if(A8($,0,H5),Z===void 0)Z=X.rounding;else A8(Z,0,8);Y=I0(new X(Y),$+1,Z),J=x6(Y,!0,$+1)}return Y.isNeg()&&!Y.isZero()?"-"+J:J};X0.toFixed=function($,Z){var J,Y,X=this,Q=X.constructor;if($===void 0)J=x6(X);else{if(A8($,0,H5),Z===void 0)Z=Q.rounding;else A8(Z,0,8);Y=I0(new Q(X),$+X.e+1,Z),J=x6(Y,!1,$+Y.e+1)}return X.isNeg()&&!X.isZero()?"-"+J:J};X0.toFraction=function($){var Z,J,Y,X,Q,G,W,K,V,U,H,B,z=this,F=z.d,A=z.constructor;if(!F)return new A(z);if(V=J=new A(1),Y=K=new A(0),Z=new A(Y),Q=Z.e=zd(F)-z.e-1,G=Q%x0,Z.d[0]=q$(10,G<0?x0+G:G),$==null)$=Q>0?Z:V;else{if(W=new A($),!W.isInt()||W.lt(V))throw Error(U5+W);$=W.gt(Z)?Q>0?Z:V:W}i0=!1,W=new A(v$(F)),U=A.precision,A.precision=Q=F.length*x0*2;for(;;){if(H=h1(W,Z,0,1,1),X=J.plus(H.times(Y)),X.cmp($)==1)break;J=Y,Y=X,X=V,V=K.plus(H.times(X)),K=X,X=Z,Z=W.minus(H.times(X)),W=X}return X=h1($.minus(J),Y,0,1,1),K=K.plus(X.times(V)),J=J.plus(X.times(Y)),K.s=V.s=z.s,B=h1(V,Y,Q,1).minus(z).abs().cmp(h1(K,J,Q,1).minus(z).abs())<1?[V,Y]:[K,J],A.precision=U,i0=!0,B};X0.toHexadecimal=X0.toHex=function($,Z){return cA(this,16,$,Z)};X0.toNearest=function($,Z){var J=this,Y=J.constructor;if(J=new Y(J),$==null){if(!J.d)return J;$=new Y(1),Z=Y.rounding}else{if($=new Y($),Z===void 0)Z=Y.rounding;else A8(Z,0,8);if(!J.d)return $.s?J:$;if(!$.d){if($.s)$.s=J.s;return $}}if($.d[0])i0=!1,J=h1(J,$,0,Z,1).times($),i0=!0,I0(J);else $.s=J.s,J=$;return J};X0.toNumber=function(){return+this};X0.toOctal=function($,Z){return cA(this,8,$,Z)};X0.toPower=X0.pow=function($){var Z,J,Y,X,Q,G,W=this,K=W.constructor,V=+($=new K($));if(!W.d||!$.d||!W.d[0]||!$.d[0])return new K(q$(+W,V));if(W=new K(W),W.eq(1))return W;if(Y=K.precision,Q=K.rounding,$.eq(1))return I0(W,Y,Q);if(Z=n$($.e/x0),Z>=$.d.length-1&&(J=V<0?-V:V)<=hN0)return X=Fd(K,W,J,Y),$.s<0?new K(1).div(X):I0(X,Y,Q);if(G=W.s,G<0){if(Z<$.d.length-1)return new K(NaN);if(($.d[Z]&1)==0)G=1;if(W.e==0&&W.d[0]==1&&W.d.length==1)return W.s=G,W}if(J=q$(+W,V),Z=J==0||!isFinite(J)?n$(V*(Math.log("0."+v$(W.d))/Math.LN10+W.e+1)):new K(J+"").e,Z>K.maxE+1||Z<K.minE-1)return new K(Z>0?G/0:0);if(i0=!1,K.rounding=W.s=1,J=Math.min(12,(Z+"").length),X=pA($.times(V5(W,Y+J)),Y),X.d){if(X=I0(X,Y+5,1),V9(X.d,Y,Q)){if(Z=Y+10,X=I0(pA($.times(V5(W,Z+J)),Z),Z+5,1),+v$(X.d).slice(Y+1,Y+15)+1==100000000000000)X=I0(X,Y+1,0)}}return X.s=G,i0=!0,K.rounding=Q,I0(X,Y,Q)};X0.toPrecision=function($,Z){var J,Y=this,X=Y.constructor;if($===void 0)J=x6(Y,Y.e<=X.toExpNeg||Y.e>=X.toExpPos);else{if(A8($,1,H5),Z===void 0)Z=X.rounding;else A8(Z,0,8);Y=I0(new X(Y),$,Z),J=x6(Y,$<=Y.e||Y.e<=X.toExpNeg,$)}return Y.isNeg()&&!Y.isZero()?"-"+J:J};X0.toSignificantDigits=X0.toSD=function($,Z){var J=this,Y=J.constructor;if($===void 0)$=Y.precision,Z=Y.rounding;else if(A8($,1,H5),Z===void 0)Z=Y.rounding;else A8(Z,0,8);return I0(new Y(J),$,Z)};X0.toString=function(){var $=this,Z=$.constructor,J=x6($,$.e<=Z.toExpNeg||$.e>=Z.toExpPos);return $.isNeg()&&!$.isZero()?"-"+J:J};X0.truncated=X0.trunc=function(){return I0(new this.constructor(this),this.e+1,1)};X0.valueOf=X0.toJSON=function(){var $=this,Z=$.constructor,J=x6($,$.e<=Z.toExpNeg||$.e>=Z.toExpPos);return $.isNeg()?"-"+J:J};function v$($){var Z,J,Y,X=$.length-1,Q="",G=$[0];if(X>0){Q+=G;for(Z=1;Z<X;Z++){if(Y=$[Z]+"",J=x0-Y.length,J)Q+=K5(J);Q+=Y}if(G=$[Z],Y=G+"",J=x0-Y.length,J)Q+=K5(J)}else if(G===0)return"0";for(;G%10===0;)G/=10;return Q+G}function A8($,Z,J){if($!==~~$||$<Z||$>J)throw Error(U5+$)}function V9($,Z,J,Y){var X,Q,G,W;for(Q=$[0];Q>=10;Q/=10)--Z;if(--Z<0)Z+=x0,X=0;else X=Math.ceil((Z+1)/x0),Z%=x0;if(Q=q$(10,x0-Z),W=$[X]%Q|0,Y==null)if(Z<3){if(Z==0)W=W/100|0;else if(Z==1)W=W/10|0;G=J<4&&W==99999||J>3&&W==49999||W==50000||W==0}else G=(J<4&&W+1==Q||J>3&&W+1==Q/2)&&($[X+1]/Q/100|0)==q$(10,Z-2)-1||(W==Q/2||W==0)&&($[X+1]/Q/100|0)==0;else if(Z<4){if(Z==0)W=W/1000|0;else if(Z==1)W=W/100|0;else if(Z==2)W=W/10|0;G=(Y||J<4)&&W==9999||!Y&&J>3&&W==4999}else G=((Y||J<4)&&W+1==Q||!Y&&J>3&&W+1==Q/2)&&($[X+1]/Q/1000|0)==q$(10,Z-3)-1;return G}function xK($,Z,J){var Y,X=[0],Q,G=0,W=$.length;for(;G<W;){for(Q=X.length;Q--;)X[Q]*=Z;X[0]+=mA.indexOf($.charAt(G++));for(Y=0;Y<X.length;Y++)if(X[Y]>J-1){if(X[Y+1]===void 0)X[Y+1]=0;X[Y+1]+=X[Y]/J|0,X[Y]%=J}}return X.reverse()}function uN0($,Z){var J,Y,X;if(Z.isZero())return Z;if(Y=Z.d.length,Y<32)J=Math.ceil(Y/3),X=(1/pK(4,J)).toString();else J=16,X="2.3283064365386962890625e-10";$.precision+=J,Z=FY($,1,Z.times(X),new $(1));for(var Q=J;Q--;){var G=Z.times(Z);Z=G.times(G).minus(G).times(8).plus(1)}return $.precision-=J,Z}var h1=function(){function $(Y,X,Q){var G,W=0,K=Y.length;for(Y=Y.slice();K--;)G=Y[K]*X+W,Y[K]=G%Q|0,W=G/Q|0;if(W)Y.unshift(W);return Y}function Z(Y,X,Q,G){var W,K;if(Q!=G)K=Q>G?1:-1;else for(W=K=0;W<Q;W++)if(Y[W]!=X[W]){K=Y[W]>X[W]?1:-1;break}return K}function J(Y,X,Q,G){var W=0;for(;Q--;)Y[Q]-=W,W=Y[Q]<X[Q]?1:0,Y[Q]=W*G+Y[Q]-X[Q];for(;!Y[0]&&Y.length>1;)Y.shift()}return function(Y,X,Q,G,W,K){var V,U,H,B,z,F,A,j,N,L,q,M,C,R,w,I,_,E,f,b,y=Y.constructor,k=Y.s==X.s?1:-1,g=Y.d,d=X.d;if(!g||!g[0]||!d||!d[0])return new y(!Y.s||!X.s||(g?d&&g[0]==d[0]:!d)?NaN:g&&g[0]==0||!d?k*0:k/0);if(K)z=1,U=Y.e-X.e;else K=H6,z=x0,U=n$(Y.e/z)-n$(X.e/z);f=d.length,_=g.length,N=new y(k),L=N.d=[];for(H=0;d[H]==(g[H]||0);H++);if(d[H]>(g[H]||0))U--;if(Q==null)R=Q=y.precision,G=y.rounding;else if(W)R=Q+(Y.e-X.e)+1;else R=Q;if(R<0)L.push(1),F=!0;else{if(R=R/z+2|0,H=0,f==1){B=0,d=d[0],R++;for(;(H<_||B)&&R--;H++)w=B*K+(g[H]||0),L[H]=w/d|0,B=w%d|0;F=B||H<_}else{if(B=K/(d[0]+1)|0,B>1)d=$(d,B,K),g=$(g,B,K),f=d.length,_=g.length;I=f,q=g.slice(0,f),M=q.length;for(;M<f;)q[M++]=0;if(b=d.slice(),b.unshift(0),E=d[0],d[1]>=K/2)++E;do{if(B=0,V=Z(d,q,f,M),V<0){if(C=q[0],f!=M)C=C*K+(q[1]||0);if(B=C/E|0,B>1){if(B>=K)B=K-1;if(A=$(d,B,K),j=A.length,M=q.length,V=Z(A,q,j,M),V==1)B--,J(A,f<j?b:d,j,K)}else{if(B==0)V=B=1;A=d.slice()}if(j=A.length,j<M)A.unshift(0);if(J(q,A,M,K),V==-1){if(M=q.length,V=Z(d,q,f,M),V<1)B++,J(q,f<M?b:d,M,K)}M=q.length}else if(V===0)B++,q=[0];if(L[H++]=B,V&&q[0])q[M++]=g[I]||0;else q=[g[I]],M=1}while((I++<_||q[0]!==void 0)&&R--);F=q[0]!==void 0}if(!L[0])L.shift()}if(z==1)N.e=U,Kd=F;else{for(H=1,B=L[0];B>=10;B/=10)H++;N.e=H+U*z-1,I0(N,W?Q+N.e+1:Q,G,F)}return N}}();function I0($,Z,J,Y){var X,Q,G,W,K,V,U,H,B,z=$.constructor;$:if(Z!=null){if(H=$.d,!H)return $;for(X=1,W=H[0];W>=10;W/=10)X++;if(Q=Z-X,Q<0)Q+=x0,G=Z,U=H[B=0],K=U/q$(10,X-G-1)%10|0;else if(B=Math.ceil((Q+1)/x0),W=H.length,B>=W)if(Y){for(;W++<=B;)H.push(0);U=K=0,X=1,Q%=x0,G=Q-x0+1}else break $;else{U=W=H[B];for(X=1;W>=10;W/=10)X++;Q%=x0,G=Q-x0+X,K=G<0?0:U/q$(10,X-G-1)%10|0}if(Y=Y||Z<0||H[B+1]!==void 0||(G<0?U:U%q$(10,X-G-1)),V=J<4?(K||Y)&&(J==0||J==($.s<0?3:2)):K>5||K==5&&(J==4||Y||J==6&&(Q>0?G>0?U/q$(10,X-G):0:H[B-1])%10&1||J==($.s<0?8:7)),Z<1||!H[0]){if(H.length=0,V)Z-=$.e+1,H[0]=q$(10,(x0-Z%x0)%x0),$.e=-Z||0;else H[0]=$.e=0;return $}if(Q==0)H.length=B,W=1,B--;else H.length=B+1,W=q$(10,x0-Q),H[B]=G>0?(U/q$(10,X-G)%q$(10,G)|0)*W:0;if(V)for(;;)if(B==0){for(Q=1,G=H[0];G>=10;G/=10)Q++;G=H[0]+=W;for(W=1;G>=10;G/=10)W++;if(Q!=W){if($.e++,H[0]==H6)H[0]=1}break}else{if(H[B]+=W,H[B]!=H6)break;H[B--]=0,W=1}for(Q=H.length;H[--Q]===0;)H.pop()}if(i0){if($.e>z.maxE)$.d=null,$.e=NaN;else if($.e<z.minE)$.e=0,$.d=[0]}return $}function x6($,Z,J){if(!$.isFinite())return Od($);var Y,X=$.e,Q=v$($.d),G=Q.length;if(Z){if(J&&(Y=J-G)>0)Q=Q.charAt(0)+"."+Q.slice(1)+K5(Y);else if(G>1)Q=Q.charAt(0)+"."+Q.slice(1);Q=Q+($.e<0?"e":"e+")+$.e}else if(X<0){if(Q="0."+K5(-X-1)+Q,J&&(Y=J-G)>0)Q+=K5(Y)}else if(X>=G){if(Q+=K5(X+1-G),J&&(Y=J-X-1)>0)Q=Q+"."+K5(Y)}else{if((Y=X+1)<G)Q=Q.slice(0,Y)+"."+Q.slice(Y);if(J&&(Y=J-G)>0){if(X+1===G)Q+=".";Q+=K5(Y)}}return Q}function dK($,Z){var J=$[0];for(Z*=x0;J>=10;J/=10)Z++;return Z}function mK($,Z,J){if(Z>gN0){if(i0=!0,J)$.precision=J;throw Error(Vd)}return I0(new $(gK),Z,1,!0)}function y6($,Z,J){if(Z>dA)throw Error(Vd);return I0(new $(uK),Z,J,!0)}function zd($){var Z=$.length-1,J=Z*x0+1;if(Z=$[Z],Z){for(;Z%10==0;Z/=10)J--;for(Z=$[0];Z>=10;Z/=10)J++}return J}function K5($){var Z="";for(;$--;)Z+="0";return Z}function Fd($,Z,J,Y){var X,Q=new $(1),G=Math.ceil(Y/x0+4);i0=!1;for(;;){if(J%2){if(Q=Q.times(Z),Gd(Q.d,G))X=!0}if(J=n$(J/2),J===0){if(J=Q.d.length-1,X&&Q.d[J]===0)++Q.d[J];break}Z=Z.times(Z),Gd(Z.d,G)}return i0=!0,Q}function Qd($){return $.d[$.d.length-1]&1}function Ad($,Z,J){var Y,X,Q=new $(Z[0]),G=0;for(;++G<Z.length;){if(X=new $(Z[G]),!X.s){Q=X;break}if(Y=Q.cmp(X),Y===J||Y===0&&Q.s===J)Q=X}return Q}function pA($,Z){var J,Y,X,Q,G,W,K,V=0,U=0,H=0,B=$.constructor,z=B.rounding,F=B.precision;if(!$.d||!$.d[0]||$.e>17)return new B($.d?!$.d[0]?1:$.s<0?0:1/0:$.s?$.s<0?0:$:NaN);if(Z==null)i0=!1,K=F;else K=Z;W=new B(0.03125);while($.e>-2)$=$.times(W),H+=5;Y=Math.log(q$(2,H))/Math.LN10*2+5|0,K+=Y,J=Q=G=new B(1),B.precision=K;for(;;){if(Q=I0(Q.times($),K,1),J=J.times(++U),W=G.plus(h1(Q,J,K,1)),v$(W.d).slice(0,K)===v$(G.d).slice(0,K)){X=H;while(X--)G=I0(G.times(G),K,1);if(Z==null)if(V<3&&V9(G.d,K-Y,z,V))B.precision=K+=10,J=Q=W=new B(1),U=0,V++;else return I0(G,B.precision=F,z,i0=!0);else return B.precision=F,G}G=W}}function V5($,Z){var J,Y,X,Q,G,W,K,V,U,H,B,z=1,F=10,A=$,j=A.d,N=A.constructor,L=N.rounding,q=N.precision;if(A.s<0||!j||!j[0]||!A.e&&j[0]==1&&j.length==1)return new N(j&&!j[0]?-1/0:A.s!=1?NaN:j?0:A);if(Z==null)i0=!1,U=q;else U=Z;if(N.precision=U+=F,J=v$(j),Y=J.charAt(0),Math.abs(Q=A.e)<1500000000000000){while(Y<7&&Y!=1||Y==1&&J.charAt(1)>3)A=A.times($),J=v$(A.d),Y=J.charAt(0),z++;if(Q=A.e,Y>1)A=new N("0."+J),Q++;else A=new N(Y+"."+J.slice(1))}else return V=mK(N,U+2,q).times(Q+""),A=V5(new N(Y+"."+J.slice(1)),U-F).plus(V),N.precision=q,Z==null?I0(A,q,L,i0=!0):A;H=A,K=G=A=h1(A.minus(1),A.plus(1),U,1),B=I0(A.times(A),U,1),X=3;for(;;){if(G=I0(G.times(B),U,1),V=K.plus(h1(G,new N(X),U,1)),v$(V.d).slice(0,U)===v$(K.d).slice(0,U)){if(K=K.times(2),Q!==0)K=K.plus(mK(N,U+2,q).times(Q+""));if(K=h1(K,new N(z),U,1),Z==null)if(V9(K.d,U-F,L,W))N.precision=U+=F,V=G=A=h1(H.minus(1),H.plus(1),U,1),B=I0(A.times(A),U,1),X=W=1;else return I0(K,N.precision=q,L,i0=!0);else return N.precision=q,K}K=V,X+=2}}function Od($){return String($.s*$.s/0)}function hK($,Z){var J,Y,X;if((J=Z.indexOf("."))>-1)Z=Z.replace(".","");if((Y=Z.search(/e/i))>0){if(J<0)J=Y;J+=+Z.slice(Y+1),Z=Z.substring(0,Y)}else if(J<0)J=Z.length;for(Y=0;Z.charCodeAt(Y)===48;Y++);for(X=Z.length;Z.charCodeAt(X-1)===48;--X);if(Z=Z.slice(Y,X),Z){if(X-=Y,$.e=J=J-Y-1,$.d=[],Y=(J+1)%x0,J<0)Y+=x0;if(Y<X){if(Y)$.d.push(+Z.slice(0,Y));for(X-=x0;Y<X;)$.d.push(+Z.slice(Y,Y+=x0));Z=Z.slice(Y),Y=x0-Z.length}else Y-=X;for(;Y--;)Z+="0";if($.d.push(+Z),i0){if($.e>$.constructor.maxE)$.d=null,$.e=NaN;else if($.e<$.constructor.minE)$.e=0,$.d=[0]}}else $.e=0,$.d=[0];return $}function mN0($,Z){var J,Y,X,Q,G,W,K,V,U;if(Z.indexOf("_")>-1){if(Z=Z.replace(/(\d)_(?=\d)/g,"$1"),Bd.test(Z))return hK($,Z)}else if(Z==="Infinity"||Z==="NaN"){if(!+Z)$.s=NaN;return $.e=NaN,$.d=null,$}if(yN0.test(Z))J=16,Z=Z.toLowerCase();else if(vN0.test(Z))J=2;else if(xN0.test(Z))J=8;else throw Error(U5+Z);if(Q=Z.search(/p/i),Q>0)K=+Z.slice(Q+1),Z=Z.substring(2,Q);else Z=Z.slice(2);if(Q=Z.indexOf("."),G=Q>=0,Y=$.constructor,G)Z=Z.replace(".",""),W=Z.length,Q=W-Q,X=Fd(Y,new Y(J),Q,Q*2);V=xK(Z,J,H6),U=V.length-1;for(Q=U;V[Q]===0;--Q)V.pop();if(Q<0)return new Y($.s*0);if($.e=dK(V,U),$.d=V,i0=!1,G)$=h1($,X,W*4);if(K)$=$.times(Math.abs(K)<54?q$(2,K):B6.pow(2,K));return i0=!0,$}function lN0($,Z){var J,Y=Z.d.length;if(Y<3)return Z.isZero()?Z:FY($,2,Z,Z);J=1.4*Math.sqrt(Y),J=J>16?16:J|0,Z=Z.times(1/pK(5,J)),Z=FY($,2,Z,Z);var X,Q=new $(5),G=new $(16),W=new $(20);for(;J--;)X=Z.times(Z),Z=Z.times(Q.plus(X.times(G.times(X).minus(W))));return Z}function FY($,Z,J,Y,X){var Q,G,W,K,V=1,U=$.precision,H=Math.ceil(U/x0);i0=!1,K=J.times(J),W=new $(Y);for(;;){if(G=h1(W.times(K),new $(Z++*Z++),U,1),W=X?Y.plus(G):Y.minus(G),Y=h1(G.times(K),new $(Z++*Z++),U,1),G=W.plus(Y),G.d[H]!==void 0){for(Q=H;G.d[Q]===W.d[Q]&&Q--;);if(Q==-1)break}Q=W,W=Y,Y=G,G=Q,V++}return i0=!0,G.d.length=H+1,G}function pK($,Z){var J=$;while(--Z)J*=$;return J}function qd($,Z){var J,Y=Z.s<0,X=y6($,$.precision,1),Q=X.times(0.5);if(Z=Z.abs(),Z.lte(Q))return qZ=Y?4:1,Z;if(J=Z.divToInt(X),J.isZero())qZ=Y?3:2;else{if(Z=Z.minus(J.times(X)),Z.lte(Q))return qZ=Qd(J)?Y?2:3:Y?4:1,Z;qZ=Qd(J)?Y?1:4:Y?3:2}return Z.minus(X).abs()}function cA($,Z,J,Y){var X,Q,G,W,K,V,U,H,B,z=$.constructor,F=J!==void 0;if(F)if(A8(J,1,H5),Y===void 0)Y=z.rounding;else A8(Y,0,8);else J=z.precision,Y=z.rounding;if(!$.isFinite())U=Od($);else{if(U=x6($),G=U.indexOf("."),F){if(X=2,Z==16)J=J*4-3;else if(Z==8)J=J*3-2}else X=Z;if(G>=0)U=U.replace(".",""),B=new z(1),B.e=U.length-G,B.d=xK(x6(B),10,X),B.e=B.d.length;H=xK(U,10,X),Q=K=H.length;for(;H[--K]==0;)H.pop();if(!H[0])U=F?"0p+0":"0";else{if(G<0)Q--;else $=new z($),$.d=H,$.e=Q,$=h1($,B,J,Y,0,X),H=$.d,Q=$.e,V=Kd;if(G=H[J],W=X/2,V=V||H[J+1]!==void 0,V=Y<4?(G!==void 0||V)&&(Y===0||Y===($.s<0?3:2)):G>W||G===W&&(Y===4||V||Y===6&&H[J-1]&1||Y===($.s<0?8:7)),H.length=J,V){for(;++H[--J]>X-1;)if(H[J]=0,!J)++Q,H.unshift(1)}for(K=H.length;!H[K-1];--K);for(G=0,U="";G<K;G++)U+=mA.charAt(H[G]);if(F){if(K>1)if(Z==16||Z==8){G=Z==16?4:3;for(--K;K%G;K++)U+="0";H=xK(U,X,Z);for(K=H.length;!H[K-1];--K);for(G=1,U="1.";G<K;G++)U+=mA.charAt(H[G])}else U=U.charAt(0)+"."+U.slice(1);U=U+(Q<0?"p":"p+")+Q}else if(Q<0){for(;++Q;)U="0"+U;U="0."+U}else if(++Q>K)for(Q-=K;Q--;)U+="0";else if(Q<K)U=U.slice(0,Q)+"."+U.slice(Q)}U=(Z==16?"0x":Z==2?"0b":Z==8?"0o":"")+U}return $.s<0?"-"+U:U}function Gd($,Z){if($.length>Z)return $.length=Z,!0}function dN0($){return new this($).abs()}function pN0($){return new this($).acos()}function cN0($){return new this($).acosh()}function iN0($,Z){return new this($).plus(Z)}function nN0($){return new this($).asin()}function oN0($){return new this($).asinh()}function sN0($){return new this($).atan()}function rN0($){return new this($).atanh()}function aN0($,Z){$=new this($),Z=new this(Z);var J,Y=this.precision,X=this.rounding,Q=Y+4;if(!$.s||!Z.s)J=new this(NaN);else if(!$.d&&!Z.d)J=y6(this,Q,1).times(Z.s>0?0.25:0.75),J.s=$.s;else if(!Z.d||$.isZero())J=Z.s<0?y6(this,Y,X):new this(0),J.s=$.s;else if(!$.d||Z.isZero())J=y6(this,Q,1).times(0.5),J.s=$.s;else if(Z.s<0)this.precision=Q,this.rounding=1,J=this.atan(h1($,Z,Q,1)),Z=y6(this,Q,1),this.precision=Y,this.rounding=X,J=$.s<0?J.minus(Z):J.plus(Z);else J=this.atan(h1($,Z,Q,1));return J}function tN0($){return new this($).cbrt()}function eN0($){return I0($=new this($),$.e+1,2)}function $M0($,Z,J){return new this($).clamp(Z,J)}function ZM0($){if(!$||typeof $!=="object")throw Error(lK+"Object expected");var Z,J,Y,X=$.defaults===!0,Q=["precision",1,H5,"rounding",0,8,"toExpNeg",-zY,0,"toExpPos",0,zY,"maxE",0,zY,"minE",-zY,0,"modulo",0,9];for(Z=0;Z<Q.length;Z+=3){if(J=Q[Z],X)this[J]=lA[J];if((Y=$[J])!==void 0)if(n$(Y)===Y&&Y>=Q[Z+1]&&Y<=Q[Z+2])this[J]=Y;else throw Error(U5+J+": "+Y)}if(J="crypto",X)this[J]=lA[J];if((Y=$[J])!==void 0)if(Y===!0||Y===!1||Y===0||Y===1)if(Y)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[J]=!0;else throw Error(Ud);else this[J]=!1;else throw Error(U5+J+": "+Y);return this}function JM0($){return new this($).cos()}function YM0($){return new this($).cosh()}function jd($){var Z,J,Y;function X(Q){var G,W,K,V=this;if(!(V instanceof X))return new X(Q);if(V.constructor=X,Wd(Q)){if(V.s=Q.s,i0)if(!Q.d||Q.e>X.maxE)V.e=NaN,V.d=null;else if(Q.e<X.minE)V.e=0,V.d=[0];else V.e=Q.e,V.d=Q.d.slice();else V.e=Q.e,V.d=Q.d?Q.d.slice():Q.d;return}if(K=typeof Q,K==="number"){if(Q===0){V.s=1/Q<0?-1:1,V.e=0,V.d=[0];return}if(Q<0)Q=-Q,V.s=-1;else V.s=1;if(Q===~~Q&&Q<1e7){for(G=0,W=Q;W>=10;W/=10)G++;if(i0)if(G>X.maxE)V.e=NaN,V.d=null;else if(G<X.minE)V.e=0,V.d=[0];else V.e=G,V.d=[Q];else V.e=G,V.d=[Q];return}if(Q*0!==0){if(!Q)V.s=NaN;V.e=NaN,V.d=null;return}return hK(V,Q.toString())}if(K==="string"){if((W=Q.charCodeAt(0))===45)Q=Q.slice(1),V.s=-1;else{if(W===43)Q=Q.slice(1);V.s=1}return Bd.test(Q)?hK(V,Q):mN0(V,Q)}if(K==="bigint"){if(Q<0)Q=-Q,V.s=-1;else V.s=1;return hK(V,Q.toString())}throw Error(U5+Q)}if(X.prototype=X0,X.ROUND_UP=0,X.ROUND_DOWN=1,X.ROUND_CEIL=2,X.ROUND_FLOOR=3,X.ROUND_HALF_UP=4,X.ROUND_HALF_DOWN=5,X.ROUND_HALF_EVEN=6,X.ROUND_HALF_CEIL=7,X.ROUND_HALF_FLOOR=8,X.EUCLID=9,X.config=X.set=ZM0,X.clone=jd,X.isDecimal=Wd,X.abs=dN0,X.acos=pN0,X.acosh=cN0,X.add=iN0,X.asin=nN0,X.asinh=oN0,X.atan=sN0,X.atanh=rN0,X.atan2=aN0,X.cbrt=tN0,X.ceil=eN0,X.clamp=$M0,X.cos=JM0,X.cosh=YM0,X.div=XM0,X.exp=QM0,X.floor=GM0,X.hypot=WM0,X.ln=KM0,X.log=VM0,X.log10=HM0,X.log2=UM0,X.max=BM0,X.min=zM0,X.mod=FM0,X.mul=AM0,X.pow=OM0,X.random=qM0,X.round=jM0,X.sign=NM0,X.sin=MM0,X.sinh=DM0,X.sqrt=wM0,X.sub=LM0,X.sum=TM0,X.tan=RM0,X.tanh=PM0,X.trunc=IM0,$===void 0)$={};if($){if($.defaults!==!0){Y=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"];for(Z=0;Z<Y.length;)if(!$.hasOwnProperty(J=Y[Z++]))$[J]=this[J]}}return X.config($),X}function XM0($,Z){return new this($).div(Z)}function QM0($){return new this($).exp()}function GM0($){return I0($=new this($),$.e+1,3)}function WM0(){var $,Z,J=new this(0);i0=!1;for($=0;$<arguments.length;)if(Z=new this(arguments[$++]),!Z.d){if(Z.s)return i0=!0,new this(1/0);J=Z}else if(J.d)J=J.plus(Z.times(Z));return i0=!0,J.sqrt()}function Wd($){return $ instanceof B6||$&&$.toStringTag===Hd||!1}function KM0($){return new this($).ln()}function VM0($,Z){return new this($).log(Z)}function UM0($){return new this($).log(2)}function HM0($){return new this($).log(10)}function BM0(){return Ad(this,arguments,-1)}function zM0(){return Ad(this,arguments,1)}function FM0($,Z){return new this($).mod(Z)}function AM0($,Z){return new this($).mul(Z)}function OM0($,Z){return new this($).pow(Z)}function qM0($){var Z,J,Y,X,Q=0,G=new this(1),W=[];if($===void 0)$=this.precision;else A8($,1,H5);if(Y=Math.ceil($/x0),!this.crypto)for(;Q<Y;)W[Q++]=Math.random()*1e7|0;else if(crypto.getRandomValues){Z=crypto.getRandomValues(new Uint32Array(Y));for(;Q<Y;)if(X=Z[Q],X>=4290000000)Z[Q]=crypto.getRandomValues(new Uint32Array(1))[0];else W[Q++]=X%1e7}else if(crypto.randomBytes){Z=crypto.randomBytes(Y*=4);for(;Q<Y;)if(X=Z[Q]+(Z[Q+1]<<8)+(Z[Q+2]<<16)+((Z[Q+3]&127)<<24),X>=2140000000)crypto.randomBytes(4).copy(Z,Q);else W.push(X%1e7),Q+=4;Q=Y/4}else throw Error(Ud);if(Y=W[--Q],$%=x0,Y&&$)X=q$(10,x0-$),W[Q]=(Y/X|0)*X;for(;W[Q]===0;Q--)W.pop();if(Q<0)J=0,W=[0];else{J=-1;for(;W[0]===0;J-=x0)W.shift();for(Y=1,X=W[0];X>=10;X/=10)Y++;if(Y<x0)J-=x0-Y}return G.e=J,G.d=W,G}function jM0($){return I0($=new this($),$.e+1,this.rounding)}function NM0($){return $=new this($),$.d?$.d[0]?$.s:0*$.s:$.s||NaN}function MM0($){return new this($).sin()}function DM0($){return new this($).sinh()}function wM0($){return new this($).sqrt()}function LM0($,Z){return new this($).sub(Z)}function TM0(){var $=0,Z=arguments,J=new this(Z[$]);i0=!1;for(;J.s&&++$<Z.length;)J=J.plus(Z[$]);return i0=!0,I0(J,this.precision,this.rounding)}function RM0($){return new this($).tan()}function PM0($){return new this($).tanh()}function IM0($){return I0($=new this($),$.e+1,1)}X0[Symbol.for("nodejs.util.inspect.custom")]=X0.toString;X0[Symbol.toStringTag]="Decimal";var B6=X0.constructor=jd(lA);gK=new B6(gK);uK=new B6(uK);var CM0=O.String.annotate({[F$]:d1.schema("workspace")}).pipe(O.brand("WorkspaceID")),iA=CM0.pipe(u0(($)=>({ascending:(Z)=>$.make(d1.ascending("workspace",Z)),zod:d1.schema("workspace").pipe(P.custom())})));function cK($){let Z={};for(let[J,Y]of Object.entries($.required().shape))Z[J]=Y.nullable();return P.object(Z)}var Nd=E0.create({service:"session.usage"});function EM0($){return/^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test($)}function OY($){let Z=$.summary_additions!==null||$.summary_deletions!==null||$.summary_files!==null?{additions:$.summary_additions??0,deletions:$.summary_deletions??0,files:$.summary_files??0,diffs:$.summary_diffs??void 0}:void 0,J=$.share_url?{url:$.share_url}:void 0,Y=$.revert??void 0;return{id:$.id,slug:$.slug,projectID:$.project_id,workspaceID:$.workspace_id??void 0,directory:$.directory,parentID:$.parent_id??void 0,contextFrom:$.context_from??void 0,contextWatermark:$.context_watermark??void 0,title:$.title,version:$.version,summary:Z,share:J,revert:Y,permission:$.permission??void 0,time:{created:$.time_created,updated:$.time_updated,compacting:$.time_compacting??void 0,archived:$.time_archived??void 0}}}function bM0($){return{id:$.id,project_id:$.projectID,workspace_id:$.workspaceID,parent_id:$.parentID,context_from:$.contextFrom,context_watermark:$.contextWatermark,slug:$.slug,directory:$.directory,title:$.title,version:$.version,share_url:$.share?.url,summary_additions:$.summary?.additions,summary_deletions:$.summary?.deletions,summary_files:$.summary?.files,summary_diffs:$.summary?.diffs,revert:$.revert??null,permission:$.permission,time_created:$.time.created,time_updated:$.time.updated,time_compacting:$.time.compacting,time_archived:$.time.archived}}var z6=P.object({id:r0.zod,slug:P.string(),projectID:$9.zod,workspaceID:iA.zod.optional(),directory:P.string(),parentID:r0.zod.optional(),contextFrom:r0.zod.optional(),contextWatermark:i1.zod.optional(),summary:P.object({additions:P.number(),deletions:P.number(),files:P.number(),diffs:vZ.FileDiff.array().optional()}).optional(),share:P.object({url:P.string()}).optional(),title:P.string(),version:P.string(),time:P.object({created:P.number(),updated:P.number(),compacting:P.number().optional(),archived:P.number().optional()}),permission:Q5.Ruleset.zod.optional(),revert:P.object({messageID:i1.zod,partID:MZ.zod.optional(),snapshot:P.string().optional(),diff:P.string().optional()}).optional()}).meta({ref:"Session"}),Md=P.object({id:$9.zod,name:P.string().optional(),worktree:P.string()}).meta({ref:"ProjectSummary"}),_M0=z6.extend({project:Md.nullable()}).meta({ref:"GlobalSession"}),SM0=P.object({parentID:r0.zod.optional(),contextFrom:r0.zod.optional(),contextWatermark:i1.zod.optional(),title:P.string().optional(),permission:z6.shape.permission,workspaceID:iA.zod.optional()}).optional(),fM0=P.object({sessionID:r0.zod,messageID:i1.zod.optional()}),kM0=r0.zod,vM0=r0.zod,yM0=r0.zod,xM0=P.object({sessionID:r0.zod,title:P.string()}),hM0=P.object({sessionID:r0.zod,time:P.number().optional()}),gM0=P.object({sessionID:r0.zod,permission:Q5.Ruleset.zod}),uM0=P.object({sessionID:r0.zod,revert:z6.shape.revert,summary:z6.shape.summary}),mM0=P.object({sessionID:r0.zod,limit:P.number().optional()}),qY={Created:X$.define({type:"session.created",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:z6})}),Updated:X$.define({type:"session.updated",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:cK(z6).extend({share:cK(z6.shape.share.unwrap()).optional(),time:cK(z6.shape.time).optional()})}),busSchema:P.object({sessionID:r0.zod,info:z6})}),Deleted:X$.define({type:"session.deleted",version:1,aggregate:"sessionID",schema:P.object({sessionID:r0.zod,info:z6})}),Diff:L1.define("session.diff",P.object({sessionID:r0.zod,diff:vZ.FileDiff.array()})),Error:L1.define("session.error",P.object({sessionID:r0.zod.optional(),error:P.lazy(()=>b$.Assistant.shape.error)})),RetryAttempt:L1.define("session.retry.attempt",P.object({sessionID:r0.zod,messageID:P.string(),attempt:P.number().int().min(1),maxAttempts:P.number().int().min(1),reason:P.string(),nextDelayMs:P.number().int().nonnegative()}))};function lM0($){let Z=S8.project.vcs?nA.join(S8.worktree,".qitqode","plans"):nA.join(F0.Path.data,"plans");return nA.join(Z,[$.time.created,$.slug].join("-")+".md")}var dM0=($)=>{let Z=(j)=>{if(!Number.isFinite(j))return 0;return j},J=Z($.usage.inputTokens??0),Y=Z($.usage.outputTokens??0),X=Z($.usage.outputTokenDetails?.reasoningTokens??$.usage.reasoningTokens??0),Q=Z($.usage.inputTokenDetails?.cacheReadTokens??$.usage.cachedInputTokens??0),G=Z(Number($.usage.inputTokenDetails?.cacheWriteTokens??$.metadata?.anthropic?.cacheCreationInputTokens??$.metadata?.vertex?.cacheCreationInputTokens??$.metadata?.bedrock?.usage?.cacheWriteInputTokens??$.metadata?.venice?.usage?.cacheCreationInputTokens??0)),W=Z(J-Q-G),V={total:$.usage.totalTokens,input:W,output:Z(Y-X),reasoning:X,cache:{write:G,read:Q}},U=$.usage.raw,H=typeof U?.cost_usd==="number"?U.cost_usd:void 0,B=typeof U?.cost_credits==="number"?U.cost_credits:void 0,z=typeof U?.context_window==="number"?U.context_window:void 0;if(H!==void 0){let j={cost:Z(H),costCredits:Z(B??H),tokens:V,contextWindow:z};return Nd.info("usage",{provider:$.model.providerID,model:$.model.id,source:"qlex",tokens:V,cost:j.cost,costCredits:j.costCredits}),j}let F=$.model.cost?.experimentalOver200K&&V.input+V.cache.read>200000?$.model.cost.experimentalOver200K:$.model.cost,A=Z(new B6(0).add(new B6(V.input).mul(F?.input??0).div(1e6)).add(new B6(V.output).mul(F?.output??0).div(1e6)).add(new B6(V.cache.read).mul(F?.cache?.read??0).div(1e6)).add(new B6(V.cache.write).mul(F?.cache?.write??0).div(1e6)).add(new B6(V.reasoning).mul(F?.output??0).div(1e6)).toNumber());return Nd.info("usage",{provider:$.model.providerID,model:$.model.id,source:"estimated",tokens:V,cost:A}),{cost:A,costCredits:void 0,tokens:V,contextWindow:z}};function*pM0($){let Z=S8.project,J=[m0(I1.project_id,Z.id)];if($?.workspaceID)J.push(m0(I1.workspace_id,$.workspaceID));if(!b0.QITQODE_EXPERIMENTAL_WORKSPACES){if($?.directory)J.push(m0(I1.directory,$.directory))}if($?.roots)J.push(iK(I1.parent_id));if($?.start)J.push(oA(I1.time_updated,$.start));if($?.search)J.push(sA(I1.title,`%${$.search}%`));let Y=$?.limit??100,X=W1.use((Q)=>Q.select().from(I1).where(O$(...J)).orderBy(o6(I1.time_updated)).limit(Y).all());for(let Q of X)yield OY(Q)}function*cM0($){let Z=[];if($?.directory)Z.push(m0(I1.directory,$.directory));if($?.roots)Z.push(iK(I1.parent_id));if($?.start)Z.push(oA(I1.time_updated,$.start));if($?.cursor)Z.push(WX(I1.time_updated,$.cursor));if($?.search)Z.push(sA(I1.title,`%${$.search}%`));if(!$?.archived)Z.push(iK(I1.time_archived));let J=$?.limit??100,Y=W1.use((G)=>{return(Z.length>0?G.select().from(I1).where(O$(...Z)):G.select().from(I1)).orderBy(o6(I1.time_updated),o6(I1.id)).limit(J).all()}),X=[...new Set(Y.map((G)=>G.project_id))],Q=new Map;if(X.length>0){let G=W1.use((W)=>W.select({id:AY.id,name:AY.name,worktree:AY.worktree}).from(AY).where(k5(AY.id,X)).all());for(let W of G)Q.set(W.id,{id:W.id,name:W.name??void 0,worktree:W.worktree})}for(let G of Y){let W=Q.get(G.project_id)??null;yield{...OY(G),project:W}}}var Dd=E0.create({service:"session"}),iM0="New session - ",nM0="Child session - ";function oM0($=!1){return($?nM0:iM0)+new Date().toISOString()}function sM0($){let Z=$.match(/^(.+) \(fork #(\d+)\)$/);if(Z){let J=Z[1],Y=parseInt(Z[2],10);return`${J} (fork #${Y+1})`}return`${$} (fork #1)`}class wd extends Error{sessionID;constructor($){super(`Session ${$} is busy`);this.sessionID=$}}class nK extends S1.Service()("@qitqode/Session"){}var rA=($)=>T.sync(()=>W1.use($)),Ld=T0.effect(nK,T.gen(function*(){let $=yield*l1.Service,Z=yield*aA.Service,J=yield*BY.Service,Y=T.fn("Session.createNext")(function*(b){let y=yield*B0.context,k={id:r0.descending(b.id),slug:JV.create(),version:E$,projectID:y.project.id,directory:b.directory,workspaceID:b.workspaceID,parentID:b.parentID,contextFrom:b.contextFrom,contextWatermark:b.contextWatermark,title:b.title??oM0(!!b.parentID),permission:b.permission,time:{created:Date.now(),updated:Date.now()}};if(Dd.info("created",k),yield*T.sync(()=>X$.run(qY.Created,{sessionID:k.id,info:k})),yield*J.register({sessionID:k.id,actorID:"main",mode:"main",parentActorID:void 0,agent:"main",description:"main agent",contextMode:"full",contextWatermark:void 0,background:!1,lifecycle:"persistent",tools:"INHERIT"}).pipe(T.ignore),!b0.QITQODE_EXPERIMENTAL_WORKSPACES)yield*$.publish(qY.Updated,{sessionID:k.id,info:k});return k}),X=T.fn("Session.get")(function*(b){let y=yield*rA((k)=>k.select().from(I1).where(m0(I1.id,b)).get());if(!y)throw new KX({message:`Session not found: ${b}`});return OY(y)}),Q=T.fn("Session.children")(function*(b){return(yield*rA((k)=>k.select().from(I1).where(O$(m0(I1.parent_id,b))).all())).map(OY)}),G=T.fnUntraced(function*(b){try{let y=yield*X(b),k=yield*Q(b);for(let d of k)yield*G(d.id);let g=yield*B0.directory.pipe(T.as(!0),T.catchCause(()=>T.succeed(!1)));yield*T.sync(()=>{X$.run(qY.Deleted,{sessionID:b,info:y},{publish:g}),X$.remove(b)})}catch(y){Dd.error(y)}}),W=(b)=>T.gen(function*(){return yield*T.sync(()=>X$.run(b$.Event.Updated,{sessionID:b.sessionID,info:b})),b}).pipe(T.withSpan("Session.updateMessage")),K=(b)=>{let y={...b};if(y.state){if(y.state={...y.state},y.state.time)y.state.time={...y.state.time}}return y},V=(b)=>T.gen(function*(){return yield*T.sync(()=>X$.run(b$.Event.PartUpdated,{sessionID:b.sessionID,part:K(b),time:Date.now()})),b}).pipe(T.withSpan("Session.updatePart")),U=T.fn("Session.getPart")(function*(b){let y=W1.use((k)=>k.select().from(I8).where(O$(m0(I8.session_id,b.sessionID),m0(I8.message_id,b.messageID),m0(I8.id,b.partID))).get());if(!y)return;return{...y.data,id:y.id,sessionID:y.session_id,messageID:y.message_id}}),H=T.fn("Session.create")(function*(b){let y=yield*B0.directory,k=yield*B0.workspaceID;return yield*Y({parentID:b?.parentID,contextFrom:b?.contextFrom,contextWatermark:b?.contextWatermark,directory:y,title:b?.title,permission:b?.permission,workspaceID:k})}),B=T.fn("Session.fork")(function*(b){let y=yield*B0.directory,k=yield*X(b.sessionID),g=sM0(k.title),d=yield*Y({directory:y,workspaceID:k.workspaceID,title:g}),p=yield*R({sessionID:b.sessionID,agentID:"*"}),t=new Map;for(let r of p){if(b.messageID&&r.info.id>=b.messageID)break;let G0=i1.ascending();t.set(r.info.id,G0);let O0=r.info.role==="assistant"&&r.info.parentID?t.get(r.info.parentID):void 0,h0=yield*W({...r.info,sessionID:d.id,id:G0,...O0&&{parentID:O0}});for(let u of r.parts)yield*V({...u,id:MZ.ascending(),messageID:h0.id,sessionID:d.id})}return d}),z=(b,y)=>T.sync(()=>X$.run(qY.Updated,{sessionID:b,info:y})),F=T.fn("Session.touch")(function*(b){yield*z(b,{time:{updated:Date.now()}})}),A=T.fn("Session.setTitle")(function*(b){yield*z(b.sessionID,{title:b.title})}),j=T.fn("Session.setArchived")(function*(b){yield*z(b.sessionID,{time:{archived:b.time}})}),N=T.fn("Session.setPermission")(function*(b){yield*z(b.sessionID,{permission:b.permission,time:{updated:Date.now()}})}),L=T.fn("Session.setRevert")(function*(b){yield*z(b.sessionID,{summary:b.summary,time:{updated:Date.now()},revert:b.revert})}),q=T.fn("Session.clearRevert")(function*(b){yield*z(b,{time:{updated:Date.now()},revert:null})}),M=T.fn("Session.setSummary")(function*(b){yield*z(b.sessionID,{time:{updated:Date.now()},summary:b.summary})}),C=T.fn("Session.diff")(function*(b){return yield*Z.read(["session_diff",b]).pipe(T.orElseSucceed(()=>[]))}),R=T.fn("Session.messages")(function*(b){if(b.limit)return b$.page({sessionID:b.sessionID,limit:b.limit,agentID:b.agentID}).items;return Array.from(b$.stream(b.sessionID,{agentID:b.agentID})).reverse()}),w=T.fn("Session.removeMessage")(function*(b){return yield*T.sync(()=>X$.run(b$.Event.Removed,{sessionID:b.sessionID,messageID:b.messageID})),b.messageID}),I=T.fn("Session.removePart")(function*(b){return yield*T.sync(()=>X$.run(b$.Event.PartRemoved,{sessionID:b.sessionID,messageID:b.messageID,partID:b.partID})),b.partID}),_=T.fnUntraced(function*(b){yield*$.publish(b$.Event.PartDelta,b)}),E=T.fn("Session.findMessage")(function*(b,y,k){for(let g of b$.stream(b,{agentID:k?.agentID}))if(y(g))return O1.some(g);return O1.none()}),f=T.fn("Session.lastMainMessageID")(function*(b){return(yield*rA((k)=>k.select({id:w$.id}).from(w$).where(O$(m0(w$.session_id,b),m0(w$.agent_id,"main"))).orderBy(o6(w$.id)).limit(1).get()))?.id});return nK.of({create:H,fork:B,touch:F,get:X,setTitle:A,setArchived:j,setPermission:N,setRevert:L,clearRevert:q,setSummary:M,diff:C,messages:R,children:Q,remove:G,updateMessage:W,removeMessage:w,removePart:I,updatePart:V,getPart:U,updatePartDelta:_,findMessage:E,lastMainMessageID:f})})),rM0=Ld.pipe(T0.provide(BY.defaultLayer),T0.provide(l1.layer),T0.provide(aA.defaultLayer));export{l1 as wj,k8 as xj,hY as yj,v9 as zj,d7 as Aj,o7 as Bj,JN as Cj,IZ as Dj,nD as Ej,rD as Fj,bU as Gj,JV as Hj,_8 as Ij,z9 as Jj,d1 as Kj,X$ as Lj,r0 as Mj,i1 as Nj,MZ as Oj,Vj as Pj,xV as Qj,X4 as Rj,G4 as Sj,vU as Tj,za as Uj,QX as Vj,VJ as Wj,Aa as Xj,vw as Yj,vZ as Zj,X1 as _j,s1 as $j,tb0 as ak,K_0 as bk,U_0 as ck,B_0 as dk,ne as ek,y_0 as fk,x_0 as gk,UW as hk,d3 as ik,BK as jk,rQ as kk,aQ as lk,dh0 as mk,ph0 as nk,ch0 as ok,Gj0 as pk,sh0 as qk,rh0 as rk,tu as sk,ah0 as tk,$m as uk,Zm as vk,q7 as wk,Q5 as xk,Vm as yk,jj0 as zk,Eg0 as Ak,Um as Bk,gg0 as Ck,mg0 as Dk,lg0 as Ek,IA as Fk,km as Gk,iA as Hk,Xu0 as Ik,Qu0 as Jk,el as Kk,Hd0 as Lk,Bd0 as Mk,Zd as Nk,BY as Ok,EA as Pk,AZ as Qk,X9 as Rk,N7 as Sk,gl as Tk,sl as Uk,b$ as Vk,EM0 as Wk,bM0 as Xk,qY as Yk,lM0 as Zk,dM0 as _k,wd as $k,nK as al,rM0 as bl,Y9 as cl,X8 as dl};