gemi 0.216.0 → 0.217.0

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 (237) hide show
  1. package/dist/ai/AgentController.d.ts +85 -2
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/AgentProvider.d.ts +20 -0
  4. package/dist/ai/AgentProvider.d.ts.map +1 -1
  5. package/dist/ai/FallbackProvider.d.ts +2 -0
  6. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  7. package/dist/ai/index.d.ts +2 -1
  8. package/dist/ai/index.d.ts.map +1 -1
  9. package/dist/ai/index.js +42 -42
  10. package/dist/ai/index.js.map +5 -5
  11. package/dist/ai/live/harness.d.ts +1 -0
  12. package/dist/ai/live/harness.d.ts.map +1 -1
  13. package/dist/ai/providers/call.d.ts +10 -0
  14. package/dist/ai/providers/call.d.ts.map +1 -1
  15. package/dist/ai/providers/fakeProvider.d.ts +3 -0
  16. package/dist/ai/providers/fakeProvider.d.ts.map +1 -1
  17. package/dist/ai/store/Attachments.d.ts +98 -2
  18. package/dist/ai/store/Attachments.d.ts.map +1 -1
  19. package/dist/ai/store/FileOwners.d.ts +18 -0
  20. package/dist/ai/store/FileOwners.d.ts.map +1 -1
  21. package/dist/ai/store/index.d.ts +1 -1
  22. package/dist/ai/store/index.d.ts.map +1 -1
  23. package/dist/ai/testing/RecordingProvider.d.ts +2 -0
  24. package/dist/ai/testing/RecordingProvider.d.ts.map +1 -1
  25. package/dist/ai/testing/index.js +3 -3
  26. package/dist/ai/testing/index.js.map +3 -3
  27. package/dist/app/index.js +1 -1
  28. package/dist/bin/ai-client/kotlin.d.ts +13 -1
  29. package/dist/bin/ai-client/kotlin.d.ts.map +1 -1
  30. package/dist/bin/ai-client/swift.d.ts +10 -1
  31. package/dist/bin/ai-client/swift.d.ts.map +1 -1
  32. package/dist/bin/gemi.js +40 -22
  33. package/dist/bin/gemi.js.map +4 -4
  34. package/dist/bin/http-client/render.d.ts +5 -0
  35. package/dist/bin/http-client/render.d.ts.map +1 -0
  36. package/dist/bun/plugin.js +1 -1
  37. package/dist/bun/preload.js +1 -1
  38. package/dist/{chunk-0ah98rf4.js → chunk-17agj0r3.js} +2 -2
  39. package/dist/{chunk-0ah98rf4.js.map → chunk-17agj0r3.js.map} +1 -1
  40. package/dist/{chunk-c2c21b6g.js → chunk-1nw9jhpt.js} +2 -2
  41. package/dist/{chunk-c2c21b6g.js.map → chunk-1nw9jhpt.js.map} +1 -1
  42. package/dist/{chunk-362a52jj.js → chunk-3r7z4kc0.js} +2 -2
  43. package/dist/{chunk-362a52jj.js.map → chunk-3r7z4kc0.js.map} +1 -1
  44. package/dist/{chunk-t0519abr.js → chunk-4k3r37be.js} +2 -2
  45. package/dist/{chunk-t0519abr.js.map → chunk-4k3r37be.js.map} +1 -1
  46. package/dist/{chunk-2crfg0m7.js → chunk-4s72m6zx.js} +3 -3
  47. package/dist/{chunk-2crfg0m7.js.map → chunk-4s72m6zx.js.map} +1 -1
  48. package/dist/{chunk-5294qsfq.js → chunk-5gp49wph.js} +2 -2
  49. package/dist/{chunk-0z8h6t7k.js.map → chunk-5gp49wph.js.map} +1 -1
  50. package/dist/{chunk-w1my1q4q.js → chunk-5vdkqv17.js} +2 -2
  51. package/dist/{chunk-w1my1q4q.js.map → chunk-5vdkqv17.js.map} +1 -1
  52. package/dist/{chunk-dqw432zh.js → chunk-5wh3cw2x.js} +3 -3
  53. package/dist/{chunk-dqw432zh.js.map → chunk-5wh3cw2x.js.map} +1 -1
  54. package/dist/{chunk-ttz05z12.js → chunk-6b7z5h54.js} +2 -2
  55. package/dist/{chunk-ttz05z12.js.map → chunk-6b7z5h54.js.map} +1 -1
  56. package/dist/{chunk-mw4c05vw.js → chunk-6ncn8rdn.js} +2 -2
  57. package/dist/{chunk-mw4c05vw.js.map → chunk-6ncn8rdn.js.map} +1 -1
  58. package/dist/chunk-7081awrd.js +11 -0
  59. package/dist/{chunk-rqa04dtq.js.map → chunk-7081awrd.js.map} +4 -4
  60. package/dist/{chunk-wcj083k2.js → chunk-7t13vyzg.js} +3 -3
  61. package/dist/{chunk-wcj083k2.js.map → chunk-7t13vyzg.js.map} +1 -1
  62. package/dist/{chunk-bk1e8sah.js → chunk-7xe5vd4w.js} +2 -2
  63. package/dist/{chunk-bk1e8sah.js.map → chunk-7xe5vd4w.js.map} +1 -1
  64. package/dist/{chunk-cws2tsxg.js → chunk-8524ejgk.js} +2 -2
  65. package/dist/{chunk-cws2tsxg.js.map → chunk-8524ejgk.js.map} +1 -1
  66. package/dist/{chunk-1hs2fxxx.js → chunk-94fdjkzf.js} +2 -2
  67. package/dist/{chunk-1hs2fxxx.js.map → chunk-94fdjkzf.js.map} +1 -1
  68. package/dist/{chunk-twb7x8j8.js → chunk-9c8e4nkz.js} +2 -2
  69. package/dist/{chunk-twb7x8j8.js.map → chunk-9c8e4nkz.js.map} +1 -1
  70. package/dist/{chunk-yjshg4e5.js → chunk-9pvxexh1.js} +2 -2
  71. package/dist/{chunk-yjshg4e5.js.map → chunk-9pvxexh1.js.map} +1 -1
  72. package/dist/{chunk-kd6z1t9z.js → chunk-aes0ecnp.js} +3 -3
  73. package/dist/{chunk-kd6z1t9z.js.map → chunk-aes0ecnp.js.map} +1 -1
  74. package/dist/{chunk-0a796avj.js → chunk-at6zjajz.js} +2 -2
  75. package/dist/{chunk-0a796avj.js.map → chunk-at6zjajz.js.map} +1 -1
  76. package/dist/{chunk-v7bbn1m0.js → chunk-b1btq22a.js} +3 -3
  77. package/dist/{chunk-v7bbn1m0.js.map → chunk-b1btq22a.js.map} +1 -1
  78. package/dist/{chunk-htkw9qbv.js → chunk-b1pps9bj.js} +2 -2
  79. package/dist/{chunk-htkw9qbv.js.map → chunk-b1pps9bj.js.map} +1 -1
  80. package/dist/{chunk-btf3t4qa.js → chunk-b8tmmpcf.js} +2 -2
  81. package/dist/{chunk-btf3t4qa.js.map → chunk-b8tmmpcf.js.map} +1 -1
  82. package/dist/chunk-bcfwa370.js +5 -0
  83. package/dist/chunk-bcfwa370.js.map +13 -0
  84. package/dist/{chunk-j6j0qxam.js → chunk-c71g46aw.js} +2 -2
  85. package/dist/{chunk-j6j0qxam.js.map → chunk-c71g46aw.js.map} +1 -1
  86. package/dist/{chunk-y9fye7az.js → chunk-cwm5x7rf.js} +2 -2
  87. package/dist/{chunk-y9fye7az.js.map → chunk-cwm5x7rf.js.map} +1 -1
  88. package/dist/{chunk-djwmrvsq.js → chunk-d6056zme.js} +2 -2
  89. package/dist/{chunk-djwmrvsq.js.map → chunk-d6056zme.js.map} +1 -1
  90. package/dist/chunk-d6bgh2nr.js +5 -0
  91. package/dist/{chunk-texzdarz.js.map → chunk-d6bgh2nr.js.map} +1 -1
  92. package/dist/{chunk-z03ds1qe.js → chunk-dgna0e7g.js} +2 -2
  93. package/dist/{chunk-z03ds1qe.js.map → chunk-dgna0e7g.js.map} +1 -1
  94. package/dist/{chunk-1k6dn4ba.js → chunk-ee7xb9qr.js} +1 -1
  95. package/dist/{chunk-5ya7fbfg.js → chunk-eh3ktv8k.js} +2 -2
  96. package/dist/{chunk-5ya7fbfg.js.map → chunk-eh3ktv8k.js.map} +1 -1
  97. package/dist/{chunk-mv2d2njy.js → chunk-fhb00fjx.js} +2 -2
  98. package/dist/{chunk-mv2d2njy.js.map → chunk-fhb00fjx.js.map} +1 -1
  99. package/dist/{chunk-py69zwwv.js → chunk-fq7wkefg.js} +2 -2
  100. package/dist/{chunk-py69zwwv.js.map → chunk-fq7wkefg.js.map} +1 -1
  101. package/dist/{chunk-01r2cx3k.js → chunk-g178aect.js} +4 -4
  102. package/dist/{chunk-01r2cx3k.js.map → chunk-g178aect.js.map} +1 -1
  103. package/dist/{chunk-jr9f5r65.js → chunk-gt6eq1p2.js} +3 -3
  104. package/dist/{chunk-jr9f5r65.js.map → chunk-gt6eq1p2.js.map} +1 -1
  105. package/dist/{chunk-z54zefss.js → chunk-gxd1388t.js} +2 -2
  106. package/dist/{chunk-z54zefss.js.map → chunk-gxd1388t.js.map} +1 -1
  107. package/dist/{chunk-dpm875be.js → chunk-gxfyd8wr.js} +3 -3
  108. package/dist/{chunk-dpm875be.js.map → chunk-gxfyd8wr.js.map} +1 -1
  109. package/dist/{chunk-gkjsanjh.js → chunk-h6knw9f0.js} +1 -1
  110. package/dist/{chunk-shn9t4vg.js → chunk-hmtn7996.js} +2 -2
  111. package/dist/{chunk-shn9t4vg.js.map → chunk-hmtn7996.js.map} +1 -1
  112. package/dist/{chunk-6s48nq83.js → chunk-jzqywxpj.js} +2 -2
  113. package/dist/{chunk-6s48nq83.js.map → chunk-jzqywxpj.js.map} +1 -1
  114. package/dist/{chunk-mnfk2r8z.js → chunk-k8nsefzb.js} +2 -2
  115. package/dist/{chunk-mnfk2r8z.js.map → chunk-k8nsefzb.js.map} +1 -1
  116. package/dist/{chunk-xw241q0q.js → chunk-kggwk7hz.js} +1 -1
  117. package/dist/{chunk-hknnxxg6.js → chunk-m0pfdc1n.js} +3 -3
  118. package/dist/{chunk-hknnxxg6.js.map → chunk-m0pfdc1n.js.map} +1 -1
  119. package/dist/{chunk-yak9kt1x.js → chunk-m68cxnbv.js} +2 -2
  120. package/dist/{chunk-yak9kt1x.js.map → chunk-m68cxnbv.js.map} +1 -1
  121. package/dist/{chunk-5m0vh0rg.js → chunk-ncw3zjxm.js} +2 -2
  122. package/dist/{chunk-5m0vh0rg.js.map → chunk-ncw3zjxm.js.map} +1 -1
  123. package/dist/{chunk-6cge785m.js → chunk-nhebjh6n.js} +1 -1
  124. package/dist/{chunk-ybmy1rts.js → chunk-p18nfs9t.js} +2 -2
  125. package/dist/{chunk-ybmy1rts.js.map → chunk-p18nfs9t.js.map} +1 -1
  126. package/dist/{chunk-djpqt7kh.js → chunk-ppdfwnqw.js} +1 -1
  127. package/dist/{chunk-62b7paq5.js → chunk-prc4bcgp.js} +2 -2
  128. package/dist/{chunk-62b7paq5.js.map → chunk-prc4bcgp.js.map} +1 -1
  129. package/dist/{chunk-hea3rwj3.js → chunk-q0d45r2j.js} +2 -2
  130. package/dist/{chunk-hea3rwj3.js.map → chunk-q0d45r2j.js.map} +1 -1
  131. package/dist/{chunk-p5n1tqqg.js → chunk-q30f4r5x.js} +2 -2
  132. package/dist/{chunk-p5n1tqqg.js.map → chunk-q30f4r5x.js.map} +1 -1
  133. package/dist/{chunk-6669vjve.js → chunk-qa528feb.js} +2 -2
  134. package/dist/{chunk-6669vjve.js.map → chunk-qa528feb.js.map} +1 -1
  135. package/dist/{chunk-4zw9gaey.js → chunk-qstjm3cb.js} +2 -2
  136. package/dist/{chunk-4zw9gaey.js.map → chunk-qstjm3cb.js.map} +1 -1
  137. package/dist/{chunk-t5af0fjq.js → chunk-r90djdx6.js} +2 -2
  138. package/dist/{chunk-t5af0fjq.js.map → chunk-r90djdx6.js.map} +1 -1
  139. package/dist/{chunk-bw1mvk6n.js → chunk-rp2f9mq1.js} +2 -2
  140. package/dist/{chunk-bw1mvk6n.js.map → chunk-rp2f9mq1.js.map} +1 -1
  141. package/dist/{chunk-9k6swvf1.js → chunk-s7jwsbfd.js} +3 -3
  142. package/dist/{chunk-9k6swvf1.js.map → chunk-s7jwsbfd.js.map} +1 -1
  143. package/dist/{chunk-3pfrqzw8.js → chunk-sba3s380.js} +2 -2
  144. package/dist/{chunk-3pfrqzw8.js.map → chunk-sba3s380.js.map} +1 -1
  145. package/dist/{chunk-naj8bmj5.js → chunk-snt0523y.js} +2 -2
  146. package/dist/{chunk-naj8bmj5.js.map → chunk-snt0523y.js.map} +1 -1
  147. package/dist/{chunk-5cf59esb.js → chunk-sqqh78tf.js} +2 -2
  148. package/dist/{chunk-5cf59esb.js.map → chunk-sqqh78tf.js.map} +1 -1
  149. package/dist/{chunk-9pjvetym.js → chunk-sxxkkx75.js} +4 -4
  150. package/dist/{chunk-9pjvetym.js.map → chunk-sxxkkx75.js.map} +1 -1
  151. package/dist/{chunk-aqjjknyk.js → chunk-tsjg2k2h.js} +2 -2
  152. package/dist/{chunk-aqjjknyk.js.map → chunk-tsjg2k2h.js.map} +1 -1
  153. package/dist/{chunk-rzhgcajs.js → chunk-v0sgcy87.js} +1 -1
  154. package/dist/{chunk-8q3pnwtj.js → chunk-vawqmdh4.js} +2 -2
  155. package/dist/{chunk-8q3pnwtj.js.map → chunk-vawqmdh4.js.map} +1 -1
  156. package/dist/{chunk-c231j2e7.js → chunk-vck02shp.js} +2 -2
  157. package/dist/{chunk-c231j2e7.js.map → chunk-vck02shp.js.map} +1 -1
  158. package/dist/{chunk-knmh8ynk.js → chunk-vewxnk3g.js} +2 -2
  159. package/dist/{chunk-knmh8ynk.js.map → chunk-vewxnk3g.js.map} +1 -1
  160. package/dist/{chunk-7bywa721.js → chunk-w3ks9nz7.js} +2 -2
  161. package/dist/{chunk-7bywa721.js.map → chunk-w3ks9nz7.js.map} +1 -1
  162. package/dist/{chunk-k9pch3e6.js → chunk-w85wrer7.js} +2 -2
  163. package/dist/{chunk-k9pch3e6.js.map → chunk-w85wrer7.js.map} +1 -1
  164. package/dist/{chunk-g7vyn179.js → chunk-w9sw2kn7.js} +3 -3
  165. package/dist/{chunk-g7vyn179.js.map → chunk-w9sw2kn7.js.map} +1 -1
  166. package/dist/{chunk-q677pnq5.js → chunk-wkmd81k4.js} +3 -3
  167. package/dist/{chunk-q677pnq5.js.map → chunk-wkmd81k4.js.map} +1 -1
  168. package/dist/{chunk-95yr9y9v.js → chunk-ww62b10k.js} +2 -2
  169. package/dist/{chunk-95yr9y9v.js.map → chunk-ww62b10k.js.map} +1 -1
  170. package/dist/{chunk-a6yge4kh.js → chunk-xb0evp2m.js} +2 -2
  171. package/dist/{chunk-a6yge4kh.js.map → chunk-xb0evp2m.js.map} +1 -1
  172. package/dist/{chunk-g1th1dfa.js → chunk-xese0rng.js} +3 -3
  173. package/dist/{chunk-g1th1dfa.js.map → chunk-xese0rng.js.map} +1 -1
  174. package/dist/{chunk-cgkp0ypn.js → chunk-xf3wke41.js} +2 -2
  175. package/dist/{chunk-cgkp0ypn.js.map → chunk-xf3wke41.js.map} +1 -1
  176. package/dist/{chunk-mjyr8at2.js → chunk-xn7azkgd.js} +3 -3
  177. package/dist/{chunk-mjyr8at2.js.map → chunk-xn7azkgd.js.map} +1 -1
  178. package/dist/{chunk-gwe9hbds.js → chunk-xp5mmgfp.js} +2 -2
  179. package/dist/{chunk-gwe9hbds.js.map → chunk-xp5mmgfp.js.map} +1 -1
  180. package/dist/{chunk-kc1y747c.js → chunk-xyv3y476.js} +3 -3
  181. package/dist/{chunk-kc1y747c.js.map → chunk-xyv3y476.js.map} +1 -1
  182. package/dist/{chunk-0z8h6t7k.js → chunk-yedb5vvg.js} +2 -2
  183. package/dist/{chunk-5294qsfq.js.map → chunk-yedb5vvg.js.map} +1 -1
  184. package/dist/{chunk-b02yzfpk.js → chunk-ykshxc5k.js} +2 -2
  185. package/dist/{chunk-b02yzfpk.js.map → chunk-ykshxc5k.js.map} +1 -1
  186. package/dist/{chunk-zbxvyanj.js → chunk-yxtfg4wy.js} +2 -2
  187. package/dist/{chunk-zbxvyanj.js.map → chunk-yxtfg4wy.js.map} +1 -1
  188. package/dist/{chunk-7mg2ash8.js → chunk-zy6hj5cc.js} +2 -2
  189. package/dist/{chunk-7mg2ash8.js.map → chunk-zy6hj5cc.js.map} +1 -1
  190. package/dist/{chunk-xg5r0383.js → chunk-zyvmbqcx.js} +3 -3
  191. package/dist/{chunk-xg5r0383.js.map → chunk-zyvmbqcx.js.map} +1 -1
  192. package/dist/config/index.js +1 -1
  193. package/dist/console/run.js +2 -2
  194. package/dist/console/run.js.map +1 -1
  195. package/dist/container/index.js +2 -2
  196. package/dist/container/index.js.map +1 -1
  197. package/dist/database/index.js +2 -2
  198. package/dist/database/index.js.map +1 -1
  199. package/dist/email/index.js +2 -2
  200. package/dist/email/index.js.map +1 -1
  201. package/dist/facades/index.js +2 -2
  202. package/dist/facades/index.js.map +1 -1
  203. package/dist/foundation/index.js +2 -2
  204. package/dist/foundation/index.js.map +1 -1
  205. package/dist/http/index.js +2 -2
  206. package/dist/http/index.js.map +1 -1
  207. package/dist/i18n/dictionaryRuntime.js +2 -2
  208. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  209. package/dist/i18n/index.js +2 -2
  210. package/dist/i18n/index.js.map +1 -1
  211. package/dist/kernel/index.js +2 -2
  212. package/dist/kernel/index.js.map +1 -1
  213. package/dist/orm/index.js +2 -2
  214. package/dist/orm/index.js.map +1 -1
  215. package/dist/probe/index.js +2 -2
  216. package/dist/probe/index.js.map +1 -1
  217. package/dist/server/index.js +2 -2
  218. package/dist/server/index.js.map +1 -1
  219. package/dist/services/index.js +2 -2
  220. package/dist/services/index.js.map +1 -1
  221. package/dist/services/queue/work.js +2 -2
  222. package/dist/services/queue/work.js.map +1 -1
  223. package/dist/stats/route-table.js +1 -1
  224. package/dist/support/index.js +2 -2
  225. package/dist/support/index.js.map +1 -1
  226. package/dist/vitest/index.js +1 -1
  227. package/package.json +1 -1
  228. package/dist/chunk-g1b6zetz.js +0 -5
  229. package/dist/chunk-g1b6zetz.js.map +0 -13
  230. package/dist/chunk-rqa04dtq.js +0 -11
  231. package/dist/chunk-texzdarz.js +0 -5
  232. /package/dist/{chunk-1k6dn4ba.js.map → chunk-ee7xb9qr.js.map} +0 -0
  233. /package/dist/{chunk-gkjsanjh.js.map → chunk-h6knw9f0.js.map} +0 -0
  234. /package/dist/{chunk-xw241q0q.js.map → chunk-kggwk7hz.js.map} +0 -0
  235. /package/dist/{chunk-6cge785m.js.map → chunk-nhebjh6n.js.map} +0 -0
  236. /package/dist/{chunk-djpqt7kh.js.map → chunk-ppdfwnqw.js.map} +0 -0
  237. /package/dist/{chunk-rzhgcajs.js.map → chunk-v0sgcy87.js.map} +0 -0
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Q as ue}from"./chunk-mw4c05vw.js";import{V as _}from"./chunk-btf3t4qa.js";import"./chunk-362a52jj.js";import{X as w}from"./chunk-0a796avj.js";import{Y as l}from"./chunk-8q3pnwtj.js";import{Im as o,Mm as d}from"./chunk-0z8h6t7k.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-gwe9hbds.js"),{fromContainerMetadata:c}=await import("./chunk-0ah98rf4.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-0ah98rf4.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-rzhgcajs.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-twb7x8j8.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-yak9kt1x.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-ttz05z12.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-k9pch3e6.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-t5af0fjq.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
2
+ import{Q as ue}from"./chunk-6ncn8rdn.js";import{V as _}from"./chunk-b8tmmpcf.js";import"./chunk-3r7z4kc0.js";import{X as w}from"./chunk-at6zjajz.js";import{Y as l}from"./chunk-vawqmdh4.js";import{Km as o,Om as d}from"./chunk-yedb5vvg.js";var g=o(_(),1);var ie=o(l(),1);var O=o(w(),1),R=o(l(),1),J=o(_(),1);var j=o(w(),1),E=o(l(),1),U=(e,s,t)=>{let n={EcsContainer:async(r)=>{let{fromHttp:a}=await import("./chunk-xp5mmgfp.js"),{fromContainerMetadata:c}=await import("./chunk-17agj0r3.js");return t?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>E.chain(a(r??{}),c(r))().then(L)},Ec2InstanceMetadata:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-17agj0r3.js");return async()=>a(r)().then(L)},Environment:async(r)=>{t?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-v0sgcy87.js");return async()=>a(r)().then(L)}};if(e in n)return n[e];else throw new E.CredentialsProviderError(`Unsupported credential source in profile ${s}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:t})},L=(e)=>j.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var N=(e,{profile:s="default",logger:t}={})=>{return Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(he(e,{profile:s,logger:t})||ye(e,{profile:s,logger:t}))},he=(e,{profile:s,logger:t})=>{let n=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(n)t?.debug?.(` ${s} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return n},ye=(e,{profile:s,logger:t})=>{let n=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(n)t?.debug?.(` ${s} isCredentialSourceProfile credential_source=${e.credential_source}`);return n},v=async(e,s,t,n,r={},a)=>{t.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let c=s[e],{source_profile:h,region:I}=c;if(!t.roleAssumer){let{getDefaultRoleAssumer:i}=await import("./chunk-9c8e4nkz.js").then((m)=>o(m.default,1));t.roleAssumer=i({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...n,...t?.parentClientConfig,region:I??t?.parentClientConfig?.region??n?.region}},t.clientPlugins)}if(h&&h in r)throw new R.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${J.getProfileName(t)}. Profiles visited: `+Object.keys(r).join(", "),{logger:t.logger});t.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${h?`source_profile=[${h}]`:`profile=[${e}]`}`);let T=h?a(h,s,t,n,{...r,[h]:!0},G(s[h]??{})):(await U(c.credential_source,e,t.logger)(t))();if(G(c))return T.then((i)=>O.setCredentialFeature(i,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let i={RoleArn:c.role_arn,RoleSessionName:c.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:c.external_id,DurationSeconds:parseInt(c.duration_seconds||"3600",10)},{mfa_serial:u}=c;if(u){if(!t.mfaCodeProvider)throw new R.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:t.logger,tryNextLink:!1});i.SerialNumber=u,i.TokenCode=await t.mfaCodeProvider(u)}let y=await T;return t.roleAssumer(y,i).then((m)=>O.setCredentialFeature(m,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},G=(e)=>{return!e.role_arn&&!!e.credential_source};var V=o(w(),1);var C=o(w(),1),X=o(l(),1),K=o(_(),1);var k=o(l(),1),W=o(ue(),1),z=o(_(),1);import{createHash as de,createPrivateKey as we,createPublicKey as ke,sign as me}from"crypto";import{promises as D}from"fs";import{homedir as fe}from"os";import{dirname as Ie,join as Y}from"path";class b{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300000;constructor(e,s,t){this.profileData=e,this.init=s,this.callerClientConfig=t}async loadCredentials(){let e=await this.loadToken();if(!e)throw new k.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let s=e.accessToken,t=Date.now();if(new Date(s.expiresAt).getTime()-t<=b.REFRESH_THRESHOLD)return this.refresh(e);return{accessKeyId:s.accessKeyId,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,accountId:s.accountId,expiration:new Date(s.expiresAt)}}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}async refresh(e){let{SigninClient:s,CreateOAuth2TokenCommand:t}=await import("./chunk-m68cxnbv.js").then((m)=>o(m.default,1)),{logger:n,userAgentAppId:r}=this.callerClientConfig??{},c=((i)=>{return i?.metadata?.handlerProtocol==="h2"})(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,I=new s({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:c,logger:n,userAgentAppId:r,...this.init?.clientConfig});this.createDPoPInterceptor(I.middlewareStack);let T={tokenInput:{clientId:e.clientId,refreshToken:e.refreshToken,grantType:"refresh_token"}};try{let i=await I.send(new t(T)),{accessKeyId:u,secretAccessKey:y,sessionToken:m}=i.tokenOutput?.accessToken??{},{refreshToken:x,expiresIn:H}=i.tokenOutput??{};if(!u||!y||!m||!x)throw new k.CredentialsProviderError("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let A=(H??900)*1000,f=new Date(Date.now()+A),q={...e,accessToken:{...e.accessToken,accessKeyId:u,secretAccessKey:y,sessionToken:m,expiresAt:f.toISOString()},refreshToken:x};await this.saveToken(q);let S=q.accessToken;return{accessKeyId:S.accessKeyId,secretAccessKey:S.secretAccessKey,sessionToken:S.sessionToken,accountId:S.accountId,expiration:f}}catch(i){if(i.name==="AccessDeniedException"){let u=i.error,y;switch(u){case"TOKEN_EXPIRED":y="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":y="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":y="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:y=`Failed to refresh token: ${String(i)}. Please re-authenticate using \`aws login\``}throw new k.CredentialsProviderError(y,{logger:this.logger,tryNextLink:!1})}throw new k.CredentialsProviderError(`Failed to refresh token: ${String(i)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let s;try{s=await z.readFile(e,{ignoreCache:this.init?.ignoreCache})}catch{s=await D.readFile(e,"utf8")}let t=JSON.parse(s),n=["accessToken","clientId","refreshToken","dpopKey"].filter((r)=>!t[r]);if(!t.accessToken?.accountId)n.push("accountId");if(n.length>0)throw new k.CredentialsProviderError(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return t}catch(s){throw new k.CredentialsProviderError(`Failed to load token from ${e}: ${String(s)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let s=this.getTokenFilePath(),t=Ie(s);try{await D.mkdir(t,{recursive:!0})}catch(n){}await D.writeFile(s,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??Y(fe(),".aws","login","cache"),s=Buffer.from(this.loginSession,"utf8"),t=de("sha256").update(s).digest("hex");return Y(e,`${t}.json`)}derToRawSignature(e){let s=2;if(e[s]!==2)throw Error("Invalid DER signature");s++;let t=e[s++],n=e.subarray(s,s+t);if(s+=t,e[s]!==2)throw Error("Invalid DER signature");s++;let r=e[s++],a=e.subarray(s,s+r);n=n[0]===0?n.subarray(1):n,a=a[0]===0?a.subarray(1):a;let c=Buffer.concat([Buffer.alloc(32-n.length),n]),h=Buffer.concat([Buffer.alloc(32-a.length),a]);return Buffer.concat([c,h])}createDPoPInterceptor(e){e.add((s)=>async(t)=>{if(W.HttpRequest.isInstance(t.request)){let n=t.request,r=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,a=await this.generateDpop(n.method,r);n.headers={...n.headers,DPoP:a}}return s(t)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",s){let t=await this.loadToken();try{let n=we({key:t.dpopKey,format:"pem",type:"sec1"}),a=ke(n).export({format:"der",type:"spki"}),c=-1;for(let f=0;f<a.length;f++)if(a[f]===4){c=f;break}let h=a.slice(c+1,c+33),I=a.slice(c+33,c+65),T={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:h.toString("base64url"),y:I.toString("base64url")}},i={jti:crypto.randomUUID(),htm:e,htu:s,iat:Math.floor(Date.now()/1000)},u=Buffer.from(JSON.stringify(T)).toString("base64url"),y=Buffer.from(JSON.stringify(i)).toString("base64url"),m=`${u}.${y}`,x=me("sha256",Buffer.from(m),n),A=this.derToRawSignature(x).toString("base64url");return`${m}.${A}`}catch(n){throw new k.CredentialsProviderError(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}}var Q=(e)=>async({callerClientConfig:s}={})=>{e?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let t=await K.parseKnownFiles(e||{}),n=K.getProfileName({profile:e?.profile??s?.profile}),r=t[n];if(!r?.login_session)throw new X.CredentialsProviderError(`Profile ${n} does not contain login_session.`,{tryNextLink:!0,logger:e?.logger});let c=await new b(r,e,s).loadCredentials();return C.setCredentialFeature(c,"CREDENTIALS_LOGIN","AD")};var Z=(e)=>{return Boolean(e&&e.login_session)},M=async(e,s,t)=>{let n=await Q({...s,profile:e})({callerClientConfig:t});return V.setCredentialFeature(n,"CREDENTIALS_PROFILE_LOGIN","AC")};var p=o(w(),1),ee=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",te=async(e,s)=>import("./chunk-6b7z5h54.js").then(({fromProcess:t})=>t({...e,profile:s})().then((n)=>p.setCredentialFeature(n,"CREDENTIALS_PROFILE_PROCESS","v")));var $=o(w(),1),se=async(e,s,t={},n)=>{let{fromSSO:r}=await import("./chunk-w85wrer7.js");return r({profile:e,logger:t.logger,parentClientConfig:t.parentClientConfig,clientConfig:t.clientConfig})({callerClientConfig:n}).then((a)=>{if(s.sso_session)return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return $.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},ne=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var ce=o(w(),1),P=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,F=async(e,s)=>{s?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let t={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return ce.setCredentialFeature(t,"CREDENTIALS_PROFILE","n")};var re=o(w(),1),ae=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,oe=async(e,s,t)=>import("./chunk-r90djdx6.js").then(({fromTokenFile:n})=>n({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:s.roleAssumerWithWebIdentity,logger:s.logger,parentClientConfig:s.parentClientConfig})({callerClientConfig:t}).then((r)=>re.setCredentialFeature(r,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")));var B=async(e,s,t,n,r={},a=!1)=>{let c=s[e];if(Object.keys(r).length>0&&P(c))return F(c,t);if(a||N(c,{profile:e,logger:t.logger}))return v(e,s,t,n,r,B);if(P(c))return F(c,t);if(ae(c))return oe(c,t,n);if(ee(c))return te(t,e);if(ne(c))return await se(e,c,t,n);if(Z(c))return M(e,t,n);throw new ie.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:t.logger})};var Ne=(e={})=>async({callerClientConfig:s}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let t=await g.parseKnownFiles(e);return B(g.getProfileName({profile:e.profile??s?.profile}),t,e,s)};export{Ne as fromIni};
3
3
 
4
- //# debugId=856EDD9986275A5664756E2164756E21
4
+ //# debugId=A38D1F14764C66A664756E2164756E21
@@ -15,6 +15,6 @@
15
15
  "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => import(\"@aws-sdk/credential-provider-web-identity\").then(({ fromTokenFile }) => fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n})({\n callerClientConfig,\n}).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\")));\n"
16
16
  ],
17
17
  "mappings": ";4QAAA,SCAA,UCAA,SACA,KACA,KCFA,eACA,WACa,EAA0B,CAAC,EAAkB,EAAa,IAAW,CAC9E,IAAM,EAAqB,CACvB,aAAc,MAAO,IAAY,CAC7B,IAAQ,YAAa,KAAa,gCAC1B,yBAA0B,KAAa,+BAE/C,OADA,GAAQ,MAAM,sEAAsE,EAC7E,SAAY,QAAM,EAAS,GAAW,CAAC,CAAC,EAAG,EAAsB,CAAO,CAAC,EAAE,EAAE,KAAK,CAAgB,GAE7G,oBAAqB,MAAO,IAAY,CACpC,GAAQ,MAAM,6EAA6E,EAC3F,IAAQ,wBAAyB,KAAa,+BAC9C,MAAO,UAAY,EAAqB,CAAO,EAAE,EAAE,KAAK,CAAgB,GAE5E,YAAa,MAAO,IAAY,CAC5B,GAAQ,MAAM,qEAAqE,EACnF,IAAQ,WAAY,KAAa,+BACjC,MAAO,UAAY,EAAQ,CAAO,EAAE,EAAE,KAAK,CAAgB,EAEnE,EACA,GAAI,KAAoB,EACpB,OAAO,EAAmB,GAG1B,WAAM,IAAI,2BAAyB,4CAA4C,UAAoB,kEAC/B,CAAE,QAAO,CAAC,GAGhF,EAAmB,CAAC,IAAU,uBAAqB,EAAO,qCAAsC,GAAG,EDzBlG,IAAM,EAAsB,CAAC,GAAO,UAAU,UAAW,UAAW,CAAC,IAAM,CAC9E,OAAQ,QAAQ,CAAG,GACf,OAAO,IAAQ,UACf,OAAO,EAAI,WAAa,UACxB,CAAC,YAAa,QAAQ,EAAE,QAAQ,OAAO,EAAI,iBAAiB,EAAI,IAChE,CAAC,YAAa,QAAQ,EAAE,QAAQ,OAAO,EAAI,WAAW,EAAI,IAC1D,CAAC,YAAa,QAAQ,E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66A664756E2164756E21",
19
19
  "names": []
20
20
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  import{constants as M}from"os";var R=Symbol.for("gemi.server.shutdown");function K(){let j=globalThis,z=j[R]??={};return z.shuttingDown??=!1,z.drained??=!1,z.held??=new Set,z.controller??=new AbortController,z}function C(){return K().shuttingDown}function q(){let j=K();if(j.shuttingDown=!0,!j.controller.signal.aborted)j.controller.abort()}function L(){return K().controller.signal}function w(j){let z=K().held,B=j.then(()=>z.delete(B),()=>z.delete(B));return z.add(B),j}function Y(){return K().held.size}async function _(){let j=K().held;while(j.size>0)await Promise.allSettled(j)}function b(){K().drained=!0}function A(j=process.env){let z={timeoutMs:$(j.GEMI_SHUTDOWN_TIMEOUT,20),delayMs:$(j.GEMI_SHUTDOWN_DELAY,0),providerTimeoutMs:$(j.GEMI_SHUTDOWN_PROVIDER_TIMEOUT,5)};if(z.delayMs>0&&z.delayMs>=z.timeoutMs)console.warn(`[gemi] GEMI_SHUTDOWN_DELAY (${z.delayMs/1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${z.timeoutMs/1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`);return z}function $(j,z){let B=j===void 0||j.trim()===""?NaN:Number(j);if(Number.isFinite(B)&&B>=0)return B*1000;if(j!==void 0)console.warn(`[gemi] Ignoring shutdown setting "${j}": expected a number of seconds.`);return z*1000}async function D(j){let{server:z,settings:B}=j,J=Date.now()+B.timeoutMs;q(),console.log(`[gemi] Shutting down: draining in-flight requests (up to ${B.timeoutMs/1000}s).`);let H=!0,V=_();if(z){if(B.delayMs>0)await E(Math.min(B.delayMs,J-Date.now()));let X=z.stop(),F=Promise.resolve();try{F=Promise.resolve(j.closeSockets?.()).catch(()=>{})}catch(Z){console.error("[gemi] Closing the broadcast sockets failed:",Z)}let O=J-Date.now(),x=j.closeSockets?Promise.race([X,Promise.all([F,y(z)])]):X,G=Promise.all([x,V]);if(H=O>0?await P(G,O):z.pendingRequests===0&&Y()===0,!H){let Z=[z.pendingRequests>0?`${z.pendingRequests} request(s)`:void 0,Y()>0?`${Y()} held background task(s)`:void 0].filter(Boolean);console.error(`[gemi] Shutdown grace period elapsed with ${Z.join(" and ")||"work"} still in flight; abandoning them.`),z.stop(!0).catch(()=>{})}}else if(Y()>0){let X=J-Date.now();if(H=X>0&&await P(V,X),!H)console.error(`[gemi] Shutdown grace period elapsed with ${Y()} held background task(s) still running; abandoning them.`)}b();let Q=await j.shutdownProviders({timeoutMs:B.providerTimeoutMs}),U=H&&Q.failed.length===0&&Q.timedOut.length===0;return console.log(`[gemi] Shutdown ${U?"complete":"finished with errors"}.`),U?0:1}function y(j){return new Promise((z)=>{let B=()=>{if(j.pendingRequests===0){z();return}setTimeout(B,50).unref?.()};B()})}async function P(j,z){if(z<=0)return!1;let B,J=await Promise.race([j.then(()=>!0,()=>!0),new Promise((H)=>{B=setTimeout(()=>H(!1),z)})]);return clearTimeout(B),J}function E(j){return new Promise((z)=>setTimeout(z,Math.max(0,j)))}function N(j){if(!C())return j;try{return j.headers.set("Connection","close"),j}catch{let z=new Response(j.body,j);return z.headers.set("Connection","close"),z}}function W(j){return async(z,B)=>{if(K().drained)return new Response("Service Unavailable",{status:503,headers:{Connection:"close"}});return N(await j(z,B))}}var f=Symbol.for("gemi.server.signalsInstalled"),T=1000;function S(j,z={}){let B=globalThis;if(B[f])return;B[f]=!0;let J=z.repeatWindowMs??T,H,V=(Q)=>{if(H!==void 0){if(Date.now()-H<J)return;console.error(`[gemi] ${Q} received again; exiting without waiting for the drain.`),process.exit(128+M.signals[Q])}H=Date.now(),console.log(`[gemi] ${Q} received.`),j().then((U)=>process.exit(U),(U)=>{console.error("[gemi] Shutdown failed:",U),process.exit(1)})};process.on("SIGTERM",V),process.on("SIGINT",V)}
3
- export{C as qm,q as rm,L as sm,w as tm,Y as um,_ as vm,A as wm,D as xm,N as ym,W as zm,S as Am};
3
+ export{C as sm,q as tm,L as um,w as vm,Y as wm,_ as xm,A as ym,D as zm,N as Am,W as Bm,S as Cm};
4
4
 
5
- //# debugId=19B490F9EF25AA3764756E2164756E21
5
+ //# debugId=D79BB47526EFD56F64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { constants } from \"node:os\";\nimport type { ShutdownReport } from \"../foundation/Application\";\nimport type { Instrumentation } from \"./types\";\n\n// On `globalThis` under a registry symbol rather than in a module variable, so\n// the flag an app's health route reads is the one the server set even when two\n// copies of this module are loaded — the built CLI bundles its own gemi (see\n// `app/App.ts`), and `bun --hot` re-evaluates every module on a reload.\nconst STATE = Symbol.for(\"gemi.server.shutdown\");\n\ntype ShutdownState = {\n shuttingDown: boolean;\n drained: boolean;\n /** `holdShutdown`'s work still running (#1210). */\n held: Set<Promise<unknown>>;\n /** Aborted by `markShuttingDown`. See `shutdownSignal`. */\n controller: AbortController;\n};\n\nfunction state(): ShutdownState {\n const global = globalThis as { [STATE]?: Partial<ShutdownState> };\n const current = (global[STATE] ??= {});\n // Filled field by field: a copy of this module from before #1210 may have\n // created the object with only the two flags.\n current.shuttingDown ??= false;\n current.drained ??= false;\n current.held ??= new Set();\n current.controller ??= new AbortController();\n return current as ShutdownState;\n}\n\n/**\n * True from the moment this server process has been told to stop — before it\n * stops accepting connections — until it exits.\n *\n * gemi's built-in health route (`./health`) answers `503` while this is true,\n * and so should an app's own health route, so the platform's probe pulls the\n * instance while the in-flight requests are still draining. Every response sent in that window also carries\n * `Connection: close`, so a client that honours it opens its next request on a\n * new connection — one the load balancer can route elsewhere — instead of\n * reusing this one.\n */\nexport function isShuttingDown(): boolean {\n return state().shuttingDown;\n}\n\nexport function markShuttingDown() {\n const current = state();\n current.shuttingDown = true;\n if (!current.controller.signal.aborted) current.controller.abort();\n}\n\n/**\n * Aborted the moment this process is told to stop, when `isShuttingDown()`\n * turns true (#1210). For background work that should wind down at once\n * rather than notice at its next check: pass it where an `AbortSignal` is\n * taken, or listen for `abort`.\n */\nexport function shutdownSignal(): AbortSignal {\n return state().controller.signal;\n}\n\n/**\n * Holds the shutdown's drain until `work` settles (#1210), as an in-flight\n * request does: background work started by a request that outlives its\n * response (an agent run, an upload being processed), so it shares the\n * `GEMI_SHUTDOWN_TIMEOUT` grace period instead of getting only what is left\n * of the providers' deadline after it.\n *\n * Returns `work`, so it wraps where the work is started:\n *\n * ```ts\n * holdShutdown(runAgent(thread));\n * ```\n *\n * The drain waits for every held promise until the timeout; whatever is still\n * running then is abandoned like a request would be, and the shutdown exits\n * `1`. A rejection counts as settled and is not reported here. Work should\n * stop early on `shutdownSignal()` and checkpoint, then let a `Service` or\n * provider `shutdown()` save what is left. Outside a server's or worker's\n * shutdown (in dev, a CLI command) it does nothing but return `work`.\n */\nexport function holdShutdown<T>(work: Promise<T>): Promise<T> {\n const held = state().held;\n const entry: Promise<unknown> = work.then(\n () => held.delete(entry),\n () => held.delete(entry),\n );\n held.add(entry);\n return work;\n}\n\n/** How many `holdShutdown` promises are still running. */\nexport function heldWork(): number {\n return state().held.size;\n}\n\n/**\n * Resolves once no `holdShutdown` work is running, including work held while\n * waiting. @internal\n */\nexport async function heldWorkSettled(): Promise<void> {\n const held = state().held;\n while (held.size > 0) {\n await Promise.allSettled(held);\n }\n}\n\n/**\n * The request drain is over and the providers' `shutdown()` may be running:\n * from here on a request must not reach the app. See `serveForShutdown`.\n */\nexport function markDrained() {\n state().drained = true;\n}\n\n/** Test seam: a fresh process starts false, and so should each test. */\nexport function resetShuttingDown() {\n const current = state();\n current.shuttingDown = false;\n current.drained = false;\n current.held.clear();\n current.controller = new AbortController();\n}\n\nexport type ShutdownSettings = {\n /**\n * From the signal to the end of the request drain, in milliseconds — the\n * delay below included. Requests still in flight when it runs out are\n * abandoned. `GEMI_SHUTDOWN_TIMEOUT`, in seconds; default 20. `0` means\n * \"close the listener and do not wait\": a shutdown with nothing in flight is\n * still a clean one.\n */\n timeoutMs: number;\n /**\n * How long to keep accepting new requests after `isShuttingDown()` turns\n * true, in milliseconds, so a health probe can see the `503` and the load\n * balancer stop routing here before the listener closes.\n * `GEMI_SHUTDOWN_DELAY`, in seconds; default 0.\n */\n delayMs: number;\n /**\n * The shared deadline for every provider's `shutdown()`, in milliseconds,\n * after the drain. `GEMI_SHUTDOWN_PROVIDER_TIMEOUT`, in seconds; default 5.\n * `0` skips the hooks — deliberately, so it is not reported as a failure.\n */\n providerTimeoutMs: number;\n};\n\n/**\n * 20s to drain plus 5s for providers is 25s: under the 30s that Kubernetes,\n * Azure Container Apps and ECS give by default between `SIGTERM` and `SIGKILL`,\n * with 5s left for the `gemi start` relay, the process exit and clock skew\n * between the platform's timer and ours. A platform with a shorter window\n * (Cloud Run's 10s, Fly's 5s) needs these lowered, not the other way round —\n * a drain that outlives the grace period ends in the same `SIGKILL` as no drain.\n *\n * The delay defaults to 0 because it only helps where a probe is watching, and\n * otherwise every shutdown would pay it for nothing.\n */\nexport function shutdownSettings(\n env: Record<string, string | undefined> = process.env,\n): ShutdownSettings {\n const settings = {\n timeoutMs: seconds(env.GEMI_SHUTDOWN_TIMEOUT, 20),\n delayMs: seconds(env.GEMI_SHUTDOWN_DELAY, 0),\n providerTimeoutMs: seconds(env.GEMI_SHUTDOWN_PROVIDER_TIMEOUT, 5),\n };\n // Warned, not clamped: the delay is sized to a probe, the timeout to the\n // platform's grace period, and which one is wrong only the operator knows.\n // Left alone, every shutdown spends the whole timeout in the delay and then\n // abandons whatever is in flight without draining it.\n if (settings.delayMs > 0 && settings.delayMs >= settings.timeoutMs) {\n console.warn(\n `[gemi] GEMI_SHUTDOWN_DELAY (${settings.delayMs / 1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${settings.timeoutMs / 1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`,\n );\n }\n return settings;\n}\n\nfunction seconds(value: string | undefined, fallback: number): number {\n const parsed = value === undefined || value.trim() === \"\" ? NaN : Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1000;\n if (value !== undefined) {\n console.warn(`[gemi] Ignoring shutdown setting \"${value}\": expected a number of seconds.`);\n }\n return fallback * 1000;\n}\n\n/** The part of `Bun.Server` a drain needs. */\nexport type Stoppable = {\n stop(closeActiveConnections?: boolean): Promise<void>;\n readonly pendingRequests: number;\n};\n\n/**\n * The shutdown sequence, in its order:\n *\n * 1. `isShuttingDown()` turns true — first, so the health route answers `503`\n * and responses carry `Connection: close` while the listener is still open.\n * 2. After `delayMs`, the listener closes (`server.stop()` without force):\n * new connections are refused, while every request in flight — a streamed\n * response included, to its last chunk — runs to completion.\n * Broadcast sockets are told `bye` and closed (`closeSockets`): a graceful\n * stop waits for open WebSockets, which never close on their own.\n * 3. That completion is awaited until `timeoutMs` from the start.\n * 4. From here a request is refused with a `503` before it reaches the app\n * (`serveForShutdown`), and every provider's `shutdown()` runs, reverse\n * order, `providerTimeoutMs`.\n *\n * Resolves with the exit code: 0 when every step finished in time, 1 when the\n * drain was cut short or a provider failed or overran.\n *\n * Two things `stop()` does not do, both measured on Bun 1.3.14, and both why\n * the process exit that follows is what actually ends the server:\n *\n * - It does not close a kept-alive connection. One that is idle when the\n * listener closes stays open, and a request sent down it afterwards is\n * served. That is what the `Connection: close` on every response in the\n * window is for: a client (or a proxy in front) that honours it opens its\n * next request on a new connection, which the closed listener refuses. A\n * client that does not honour it is what step 4's `503` is for — Bun does\n * not close the socket after a `Connection: close` response either (#566).\n * - `stop(true)` issued after a graceful `stop()` does not cut the remaining\n * requests off; it waits for the same ones. It is still called when the\n * drain times out, for a Bun that does, but nothing here depends on it. Nor\n * does it close an idle kept-alive connection. Only a `stop(true)` issued\n * *first* does that, and it cuts off the requests in flight with it, which\n * is the drain given up — so the idle ones are refused, not closed.\n */\nexport async function drain(params: {\n server: Stoppable | undefined;\n /**\n * Says `bye` to the broadcast sockets and closes them, right after the\n * listener closes, and resolves once they are closed or cut. A graceful\n * `stop()` waits for open WebSockets, which otherwise never close on their\n * own.\n */\n closeSockets?: () => void | Promise<void>;\n shutdownProviders: (options: { timeoutMs: number }) => Promise<ShutdownReport>;\n settings: ShutdownSettings;\n}): Promise<number> {\n const { server, settings } = params;\n const deadline = Date.now() + settings.timeoutMs;\n\n markShuttingDown();\n console.log(\n `[gemi] Shutting down: draining in-flight requests (up to ${settings.timeoutMs / 1000}s).`,\n );\n\n let drained = true;\n // Background work held with `holdShutdown` (#1210) is waited for beside the\n // requests, under the same deadline.\n const heldDone = heldWorkSettled();\n if (server) {\n if (settings.delayMs > 0) {\n await sleep(Math.min(settings.delayMs, deadline - Date.now()));\n }\n const stopped = server.stop();\n let socketsClosed: Promise<unknown> = Promise.resolve();\n try {\n socketsClosed = Promise.resolve(params.closeSockets?.()).catch(() => {});\n } catch (error) {\n console.error(\"[gemi] Closing the broadcast sockets failed:\", error);\n }\n // No time left to wait — a `GEMI_SHUTDOWN_TIMEOUT` of 0, or a delay that\n // spent all of it — is \"do not wait for what is in flight\", and that is\n // only a failure when something *is* in flight. Reading it as one made\n // every clean shutdown log an abandonment and exit 1 for the operator who\n // zeroed the budget to fit a 5s grace period, with nothing to abandon.\n const remaining = deadline - Date.now();\n // With broadcast sockets, the stop's own promise has been seen to stay\n // pending for good after every request finished and every socket was\n // closed or terminated (Bun 1.4.2 on a loaded Linux CI runner, with its\n // `pendingWebSockets` stuck above 0). So the drain also ends on its real\n // condition: no request in flight, and the hub's sockets closed or cut.\n const requestsDone = params.closeSockets\n ? Promise.race([stopped, Promise.all([socketsClosed, noRequestInFlight(server)])])\n : stopped;\n const done = Promise.all([requestsDone, heldDone]);\n drained =\n remaining > 0\n ? await settlesWithin(done, remaining)\n : server.pendingRequests === 0 && heldWork() === 0;\n if (!drained) {\n const parts = [\n server.pendingRequests > 0 ? `${server.pendingRequests} request(s)` : undefined,\n heldWork() > 0 ? `${heldWork()} held background task(s)` : undefined,\n ].filter(Boolean);\n console.error(\n `[gemi] Shutdown grace period elapsed with ${parts.join(\" and \") || \"work\"} still in flight; abandoning them.`,\n );\n void server.stop(true).catch(() => {});\n }\n } else if (heldWork() > 0) {\n // A signal during the boot: no listener, but work may already be held.\n const remaining = deadline - Date.now();\n drained = remaining > 0 && (await settlesWithin(heldDone, remaining));\n if (!drained) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${heldWork()} held background task(s) still running; abandoning them.`,\n );\n }\n }\n\n // Whether or not the drain finished: a request that arrives now, down a\n // kept-alive connection the listener's close left open, would run against\n // providers that are being shut down underneath it.\n markDrained();\n const report = await params.shutdownProviders({ timeoutMs: settings.providerTimeoutMs });\n const clean = drained && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n}\n\n/**\n * Resolves once `server` has no request in flight. A streamed response counts\n * until its last chunk (measured on Bun 1.4, macOS and Linux).\n */\nfunction noRequestInFlight(server: Stoppable): Promise<void> {\n return new Promise((resolve) => {\n const check = () => {\n if (server.pendingRequests === 0) {\n resolve();\n return;\n }\n const timer = setTimeout(check, 50);\n (timer as { unref?: () => void }).unref?.();\n };\n check();\n });\n}\n\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n // `drain` decides for itself what a budget that is already spent means, so\n // this is only a guard: a race against `setTimeout(0)` is a coin toss, and\n // \"did not settle within no time at all\" is the honest answer to it.\n if (ms <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n promise.then(\n () => true,\n () => true,\n ),\n new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n }),\n ]);\n clearTimeout(timer);\n return result;\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\n/**\n * `Connection: close` on a response sent while shutting down, so the client's\n * next request opens a connection — which the load balancer can send elsewhere\n * — instead of reusing this one.\n *\n * The spec makes some responses' headers immutable (a `Response.redirect`, a\n * proxied `fetch`), and setting one throws. Bun 1.3.14 lets both be set, so\n * the copy is for a Bun that follows the spec — a throw here would turn every\n * such response in the drain window into a 500.\n */\nexport function closeConnectionWhileShuttingDown(res: Response): Response {\n if (!isShuttingDown()) return res;\n try {\n res.headers.set(\"Connection\", \"close\");\n return res;\n } catch {\n const copy = new Response(res.body, res);\n copy.headers.set(\"Connection\", \"close\");\n return copy;\n }\n}\n\n/**\n * What every response goes through while this process serves: the app's\n * instrumentation, with the two changes a shutdown makes to it.\n *\n * - While the requests in flight drain, a response carries `Connection: close`\n * (`closeConnectionWhileShuttingDown`).\n * - Once they have drained, a request is answered `503` with\n * `Connection: close` and reaches neither the app nor its instrumentation.\n * The listener is closed by then, so only a kept-alive connection can still\n * deliver one, and `server.stop()` leaves those open. Serving it would run a\n * handler against providers whose `shutdown()` is closing the pool, the\n * queue or the cache it uses — until the process exits. The instrumentation\n * is skipped too because it is app code, and a tracer or error reporter is\n * exactly what a provider flushes and closes at this point.\n */\nexport function serveForShutdown(instrumentation: Instrumentation): Instrumentation {\n return async (req, next) => {\n if (state().drained) {\n return new Response(\"Service Unavailable\", {\n status: 503,\n headers: { Connection: \"close\" },\n });\n }\n return closeConnectionWhileShuttingDown(await instrumentation(req, next));\n };\n}\n\n// Installed once per process, not once per `Server`: a listener per instance\n// would each start a shutdown of its own, and read the other's signal as the\n// second one.\nconst SIGNALS_INSTALLED = Symbol.for(\"gemi.server.signalsInstalled\");\n\n/**\n * A repeat of the first signal inside this window is the same shutdown\n * delivered twice, not an operator asking to skip the drain. One shutdown\n * routinely arrives more than once, milliseconds apart: Ctrl+C on\n * `bun run start` reaches the server directly (the whole foreground group is\n * signalled), and again through `gemi start`'s relay — twice over, since\n * `bun run` forwards it to `gemi start` too. systemd's default\n * `KillMode=control-group` and `tini -g` do the same to every process in the\n * group. A person pressing Ctrl+C again is well outside a second.\n */\nconst REPEAT_WINDOW_MS = 1000;\n\n/**\n * `SIGTERM` or `SIGINT` runs `stop` and exits with the code it resolves with.\n * Another signal of either kind, more than `repeatWindowMs` after the first,\n * exits at once with `128 + n` — an operator pressing Ctrl+C again does not\n * want to wait out the grace period. Without a listener the first signal would\n * do that too: the default action for both is to terminate the process on the\n * spot.\n */\nexport function installShutdownSignals(\n stop: () => Promise<number>,\n options: { repeatWindowMs?: number } = {},\n) {\n const global = globalThis as { [SIGNALS_INSTALLED]?: boolean };\n if (global[SIGNALS_INSTALLED]) return;\n global[SIGNALS_INSTALLED] = true;\n\n const repeatWindowMs = options.repeatWindowMs ?? REPEAT_WINDOW_MS;\n let receivedAt: number | undefined;\n const onSignal = (signal: \"SIGTERM\" | \"SIGINT\") => {\n if (receivedAt !== undefined) {\n if (Date.now() - receivedAt < repeatWindowMs) return;\n console.error(`[gemi] ${signal} received again; exiting without waiting for the drain.`);\n process.exit(128 + constants.signals[signal]);\n }\n receivedAt = Date.now();\n console.log(`[gemi] ${signal} received.`);\n stop().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"[gemi] Shutdown failed:\", error);\n process.exit(1);\n },\n );\n };\n process.on(\"SIGTERM\", onSignal);\n process.on(\"SIGINT\", onSignal);\n}\n"
6
6
  ],
7
7
  "mappings": ";AAAA,oBAAS,WAQT,IAAM,EAAQ,OAAO,IAAI,sBAAsB,EAW/C,SAAS,CAAK,EAAkB,CAC9B,IAAM,EAAS,WACT,EAAW,EAAO,KAAW,CAAC,EAOpC,OAJA,EAAQ,eAAiB,GACzB,EAAQ,UAAY,GACpB,EAAQ,OAAS,IAAI,IACrB,EAAQ,aAAe,IAAI,gBACpB,EAcF,SAAS,CAAc,EAAY,CACxC,OAAO,EAAM,EAAE,aAGV,SAAS,CAAgB,EAAG,CACjC,IAAM,EAAU,EAAM,EAEtB,GADA,EAAQ,aAAe,GACnB,CAAC,EAAQ,WAAW,OAAO,QAAS,EAAQ,WAAW,MAAM,EAS5D,SAAS,CAAc,EAAgB,CAC5C,OAAO,EAAM,EAAE,WAAW,OAuBrB,SAAS,CAAe,CAAC,EAA8B,CAC5D,IAAM,EAAO,EAAM,EAAE,KACf,EAA0B,EAAK,KACnC,IAAM,EAAK,OAAO,CAAK,EACvB,IAAM,EAAK,OAAO,CAAK,CACzB,EAE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,QAAQ,EAAO,EAE9C,EAAa,KAAK,IAAI,EACtB,QAAQ,IAAI,UAAU,aAAkB,EACxC,EAAK,EAAE,KACL,CAAC,IAAS,QAAQ,KAAK,CAAI,EAC3B,CAAC,IAAU,CACT,QAAQ,MAAM,0BAA2B,CAAK,EAC9C,QAAQ,KAAK,CAAC,EAElB,GAEF,QAAQ,GAAG,UAAW,CAAQ,EAC9B,QAAQ,GAAG,SAAU,CAAQ",
8
- "debugId": "19B490F9EF25AA3764756E2164756E21",
8
+ "debugId": "D79BB47526EFD56F64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Cc as B3,Pc as P3,ic as E3,mc as H2,nc as b3,oc as N3,ud as I3,wc as F3}from"./chunk-aqjjknyk.js";import{Gd as l}from"./chunk-g1b6zetz.js";import{fe as i2,he as I2,ke as i3,le as l3,me as F$,oe as A$}from"./chunk-v7bbn1m0.js";import{Fe as q,Ge as d3,He as c3,Je as p3,Ke as D$,re as h3,we as m3,ye as u3}from"./chunk-q677pnq5.js";import{Ne as B}from"./chunk-5cf59esb.js";import{$g as $$,Af as F2,Bf as K2,Fh as C$,Hg as e2,Sg as a2,Tf as d2,Ug as s,Yg as r3,Ze as t,Zg as r2,_e as Y$,_g as e3,bf as R3,dh as g2,eh as f2,ff as S$,fg as G2,if as J$,ih as w2,jh as Z$,kh as X2,lf as N$,lg as J2,lh as z$,mg as u2,mh as G$,ng as k,nh as v2,oh as $2,qg as U$,rg as K$,rh as M$,sg as Q$,sh as o,th as p2,ug as g,vf as B$,wf as l2,yh as H$,zh as V$}from"./chunk-9pjvetym.js";import{Aj as x$,Bj as L2,Cj as B2,Dj as W2,Ri as u,fj as o2,vj as J3}from"./chunk-g1th1dfa.js";import{Kj as t3}from"./chunk-5ya7fbfg.js";import{Vj as m}from"./chunk-naj8bmj5.js";import{Yj as i}from"./chunk-95yr9y9v.js";import{dk as c2}from"./chunk-dpm875be.js";import{gk as P$,hk as n2,kk as P2,lk as s2,ok as L$}from"./chunk-hknnxxg6.js";import{Ck as s3,Hk as o3}from"./chunk-5m0vh0rg.js";import{Xk as g3,Zk as d}from"./chunk-a6yge4kh.js";import{_k as S}from"./chunk-zbxvyanj.js";import{el as j$}from"./chunk-kc1y747c.js";import{Zl as t2}from"./chunk-xg5r0383.js";import{em as N2,hm as E}from"./chunk-kd6z1t9z.js";import{qm as m2}from"./chunk-hea3rwj3.js";import{Gm as a3}from"./chunk-bw1mvk6n.js";var k$="mcp",R$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class D extends l{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $3=/^[A-Za-z0-9_-]{1,64}$/,E$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z3=4000,R=1e5,b$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function J8($){return L3.get($)}class n{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=g$(z.files),this.featureOn=z.featureOn??K2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,y$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(Y3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){D2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new D(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!Y2(X))throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new D(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let H=Q.value,U={caller:$,req:$.req,tool:K,input:H,ctx:G},V=await this.fillPath(Y,U),{path:N}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(N!==K.url)throw new D(`"${Z}" has nothing at ${V}.`,404);let I={};for(let A of Y.jsonKeys)if(H[A]!==void 0)I[A]=H[A];let P,J="";if(Y.fileFields.length>0)P=await this.formData(Y,I,U);else if(K.method==="GET")J=t$(I);else if(Y.jsonKeys.length>0)P=I;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(U)):void 0,O={...j?{credentials:j}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let A=J?`${V}?${J}`:V;T=Object.keys(O).length>0?await this.dispatcher.dispatchAs($.req,K.method,A,P,O):await this.dispatcher.dispatchAs($.req,K.method,A,P)}catch(A){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,A),new D(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await V3(Z,T);return await this.project(Y,U,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(E$)].map(([,F,C])=>({name:F,modifier:C})),Q=X.params??{};for(let F of K)if(!(F.name in Q))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,C]of Object.entries(Q)){if(!K.some((w)=>w.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(Q3(C))c$(z,`params.${F}`,C);else K3(z,`params.${F}`,C)}let H=[],U;if(X.input){if(U=X.input.toJSONSchema(),U.type!=="object"||!U.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(U.properties)}let V=Object.entries(X.files??{}).map(([F,C])=>({name:F,binder:C}));for(let F of V)K3(z,`files.${F.name}`,F.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let N=H3(z,G,X.annotations);if(V.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let I={},P=(F,C)=>{if(F in I)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);I[F]=C},J=new Map,j=new Map;for(let F of K){let C=Q[F.name];if(C==="input"){let w=i.string().describe(`The ":${F.name}" segment of the url.`);P(F.name,F.modifier==="?"||F.modifier==="*"?w.optional():w)}else if(Q3(C)){let w=C.as??F.name;P(w,C.input),j.set(F.name,{key:w,param:C})}else J.set(F.name,C)}let O={};for(let F of V)if(F.binder==="input")P(F.name,i.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),O[F.name]=this.remoteFileSchema();let T=[...Object.keys(I),...V.map((F)=>F.name)];for(let F of new Set(T))if(H.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let A=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:U3(X.input,U,i.object(I)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:N,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),x=!V.every((F)=>F.binder==="input")?null:V.length===0?A:Object.freeze({...A,inputSchema:U3(X.input,U,i.object(l$(I,Object.keys(O))),O)});return{kind:"route",descriptor:A,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let H of Object.keys(Y))if(!W.includes(H))K.push(`a file has no field "${H}"`);for(let H of W){let U=Y[H];if(U===void 0||U===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof U!=="string")K.push(`a file's "${H}" must be a string`);else Q[H]=U}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:H3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!Y2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let H=G.signal??new AbortController().signal;return X3(X,Y.value,W3(G3(X,Q,H,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Y2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(D2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new D(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return L3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new D(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(x,F)=>{if(!W.progress)return;let C;try{C=$.meta.remote?.progress?$.meta.remote.progress(x,F):w$(x,F)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(C)W.progress(C)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z3(this.runNative($,{...K,ctx:G},G),Q)}let H=$.meta.remote,U=await this.bind($,"the remote context",()=>H.context(K));if(typeof U!=="object"||U===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,U),new D(`"${X}" failed on the server.`,500);let V=$.tool.timeoutMs,N=[...W.signal?[W.signal]:[],...V!==void 0?[AbortSignal.timeout(V)]:[]],I=N.length===0?new AbortController().signal:N.length===1?N[0]:AbortSignal.any(N),P=[],J=G3($,U,I,P);if(!W.approved&&Y2($)&&await X3($,K.input,W3(J)))throw new h(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await z3(this.runNative($,{...K,ctx:J},J),Q,I)}catch(x){if(I.aborted&&x===I.reason){if(W.signal?.aborted)throw new D(`"${X}" was cancelled.`,499);throw new D(`"${X}" did not finish within ${V} ms.`,504)}if(x instanceof D)throw x;if(x instanceof l||x instanceof h)throw new D(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new D(`"${X}" failed on the server.`,500)}let O=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new D(`"${X}" failed on the server.`,500)};if(F3(j))throw O("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(P)}catch(x){throw O(`could not read an image it showed: ${x}`)}let A=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(A);if(x.ok===!1)throw O(`answered what its output schema refuses: ${x.errors.join(", ")}`);A=x.value}for(let x of T)W.images?.(x);if(A===void 0)return null;if(typeof A==="string")return A.length>R?`${A.slice(0,R)}\u2026 [cut at ${R} of ${A.length} characters]`:A;let Z2=JSON.stringify(A);if(Z2!==void 0&&Z2.length>R)return`${Z2.slice(0,R)}\u2026 [cut at ${R} of ${Z2.length} characters]`;return A}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new D(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let H=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new D(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${H}`,"");continue}W=W.replace(H,n$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,H]of Object.entries(Z))O2(K,Q,H);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new D(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(U)=>new D(`"${Z}" of "${$}" ${U}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!h$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!m$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let U=W.data.replace(/\s+/g,"");if(Math.floor(U.length*3/4)-d$(U)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(U.length%4!==0||!u$.test(U))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(U,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(H.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let U=await J3(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!U.ok)throw G(`could not be fetched: ${H.host} answered ${U.status}.`);let V=await U.arrayBuffer();return new File([V],W.name,{type:W.mimeType})}catch(U){if(U instanceof D)throw U;throw G(`could not be fetched from ${H.host}: ${U instanceof Error?U.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(k$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!R$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await V3(G,z);let X=(V,N)=>{if(N===void 0)console.error(`[gemi/mcp] "${G}" ${V}`);else console.error(`[gemi/mcp] "${G}" ${V}`,N);return new D(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=Q;if($.result)try{H=await $.result(Q,Z)}catch(V){throw X("failed in its result projection:",V)}if(W){let V=W.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let U=JSON.stringify(H);if(U!==void 0&&U.length>R)return`${U.slice(0,R)}\u2026 [cut at ${R} of ${U.length} characters]`;return H}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof l)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new D(`"${$.descriptor.name}" failed on the server.`,500)}}}function y$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function f$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!f$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function w$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function G3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(U)=>async()=>{throw new l(`"${W}" was called by a remote MCP client, which has no ${U}.`,{retryable:!1})},H={put:async(U,V={})=>{if(!V.showModel)return K("attachment store")();let N=V.mimeType||U.type;if(!/^image\//i.test(N))throw new l(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${N?`"${N}"`:"a blob with no type"}.`,{retryable:!1});let I=U.arrayBuffer().then((P)=>({type:"image",data:Buffer.from(P).toString("base64"),mimeType:N}));return I.catch(()=>{}),G.push(I),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:V.name??(U instanceof File?U.name:"image"),mimeType:N,size:U.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:H,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(U)=>I3({...U,signal:U.signal?AbortSignal.any([z,U.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:B3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:N3().meter}}function Y2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function D2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Y3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var v$=10485760;function g$($){let Z=$?.maxBytes??v$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function h$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var m$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,u$=/^[A-Za-z0-9+/]*={0,2}$/;function d$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function c$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var p$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function i$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function H3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?i$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!p$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function U3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,H])=>[Q,H.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let H=[],U={};if($){let N=$.safeParse(Q);if(N.ok===!1)H.push(...N.errors);else U={...N.value}}let V=z.safeParse(Q);if(V.ok===!1)H.push(...V.errors);else U={...U,...V.value};for(let[N,I]of Object.entries(G)){let P=Q[N];if(P===void 0){H.push(`"${N}" is required`);continue}let J=I.safeParse(P);if(J.ok===!1)H.push(...J.errors.map((j)=>`${N}: ${j}`));else U[N]=J.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:U}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let H=K(Q);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function l$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function n$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new D(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function O2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function t$($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function V3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!b$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>R)return`${W.slice(0,R)}\u2026 [cut at ${R} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>Z3?`${z.slice(0,Z3)}\u2026`:z;throw new D(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new D(`"${$}" failed on the server.`,Z.status)}import{createHash as s$,randomBytes as o$,timingSafeEqual as a$}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class r${options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${o$(32).toString("base64url")}`}static hash($){return s$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&a$(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as y3,randomBytes as j3}from"crypto";async function A2($,Z){let z=e$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function e$(){try{let $=E();return $.bound(t)?$.make(t):null}catch{return null}}var x2=["2026-07-28"],Q2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...Q2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",_={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _3($){if(Array.isArray($))throw new L(_.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(_.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new L(_.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(_.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new L(_.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as $6,timingSafeEqual as Z6}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=O3($,Z,X);if(K.length!==Q.length||!Z6(K,Q))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=G)return null;return H}function O3($,Z,z){return $6("sha256",H2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",A3="gemi.mcp.session.v1",z6=86400000,x3=600000,C3="gemi_approval",b2=2000,G6={limit:600,window:60},W6={limit:30,window:60};class z2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=K6(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,H2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??G6,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new E3,this.approvalTimeoutMs=Z.approvalTimeoutMs??x3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??K2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new L(_.InvalidRequest,"Origin not allowed.")),403);let G=z?Y6(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return S3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await X6($,this.maxBodyBytes))}catch(Y){if(Y instanceof V2)return v(b(null,new L(_.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new L(_.ParseError,"Parse error.")),400)}let X=new u($,{},"api",this.endpoint.pathname);return await m.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new L(_.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let P=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===P.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:J}),T3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(_.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let H=this.session($,z),U=$.headers.get("mcp-protocol-version");if(U!==null&&U!==H.state.v)throw new L(_.InvalidRequest,`MCP-Protocol-Version ${U} is not the session's ${H.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,N=new AbortController;this.inflight.set(V,N);let I=AbortSignal.any([N.signal,$.signal]);try{return await this.respond(Y,async(P,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:J}),T3(K)||H6(this.registry,Y,H.state),I,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Q2.includes(G)?G:Q2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q3(X.elicitation),p:U2(z),exp:Date.now()+z6},K=k2(A3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(_.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(A3,"gms1",z);if(!G||G.p!==U2(Z))throw new L(_.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new L(_.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new L(_.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||D3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new L(_.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,j)=>{G.outcome="denied",G.reason=J,G.message=j},K=(J,j,O)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(O!==void 0)G.error=O},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(_.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let O=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(O),this.toolResult($,{content:[{type:"text",text:O}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let O=await this.approval($,Q,z,Y,G);if(O.kind==="answer")return O.result;G.approved=!0}}let H=U6($),U=[],V;try{V=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>U.push(J),...H?{progress:H}:{}})}catch(J){if(J instanceof D){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof h){let O=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,O),new L(_.InvalidParams,O)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let j=`"${Z}" failed on the server.`;return K(j,void 0,J),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}let N=typeof V==="string"?V:JSON.stringify(V??null),I=Q.outputSchema&&($.era.modern||M(V))?{structuredContent:V}:{},P=[...U.length>0&&V===null?[]:[{type:"text",text:N}],...U];return G.outcome="ok",this.toolResult($,{content:P,...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=V6(Z,z),Y=(N,I="approval-declined")=>{return G(I,N),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}},K=(N,I)=>{return G(N,I.message),I};if($.era.modern){let N=M($.params._meta)?$.params._meta:{},I=M(N[q2])?N[q2]:{},P=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=Q6(z);if(P&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==U2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new L(_.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new L(_.InvalidParams,"requestState has already been used."));return M3(P[C3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q3(I.elicitation))throw K("approval-unavailable",new L(_.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let O={p:U2($.principal),t:Z.name,a:j,n:j3(16).toString("base64url"),exp:Date.now()+x3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",O),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let H=`gemi-approval-${j3(12).toString("base64url")}`,U=Q.sessionId,V=await new Promise((N)=>{let I=setTimeout(()=>{this.pending.delete(H),N(null)},this.approvalTimeoutMs),P=(J)=>{clearTimeout(I),N(J)};this.pending.set(H,{session:U,resolve:P}),$.signal.addEventListener("abort",()=>{this.pending.delete(H),P(null)}),$.stream.send({jsonrpc:"2.0",id:H,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return V&&!V.error&&M3(V.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new L(_.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new L(_.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R3(new u($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,W6);return z===null?null:k3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:k3(Z)}}class f3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
2
+ import{Cc as B3,Pc as P3,ic as E3,mc as H2,nc as b3,oc as N3,ud as I3,wc as F3}from"./chunk-tsjg2k2h.js";import{Gd as l}from"./chunk-bcfwa370.js";import{he as i2,je as I2,me as i3,ne as l3,oe as F$,qe as A$}from"./chunk-b1btq22a.js";import{Ae as u3,He as q,Ie as d3,Je as c3,Le as p3,Me as D$,te as h3,ye as m3}from"./chunk-wkmd81k4.js";import{Pe as B}from"./chunk-sqqh78tf.js";import{$e as t,$g as r2,Ah as H$,Bh as V$,Cf as F2,Df as K2,Hh as C$,Jg as e2,Ug as a2,Vf as d2,Wg as s,_g as r3,af as Y$,ah as e3,bh as $$,df as R3,fh as g2,gh as f2,hf as S$,hg as G2,kf as J$,kh as w2,lh as Z$,mh as X2,nf as N$,ng as J2,nh as z$,og as u2,oh as G$,pg as k,ph as v2,qh as $2,sg as U$,tg as K$,th as M$,ug as Q$,uh as o,vh as p2,wg as g,xf as B$,yf as l2}from"./chunk-sxxkkx75.js";import{Cj as x$,Dj as L2,Ej as B2,Fj as W2,Ti as u,hj as o2,xj as J3}from"./chunk-xese0rng.js";import{Mj as t3}from"./chunk-eh3ktv8k.js";import{Xj as m}from"./chunk-snt0523y.js";import{_j as i}from"./chunk-ww62b10k.js";import{fk as c2}from"./chunk-gxfyd8wr.js";import{ik as P$,jk as n2,mk as P2,nk as s2,qk as L$}from"./chunk-m0pfdc1n.js";import{Ek as s3,Jk as o3}from"./chunk-ncw3zjxm.js";import{$k as d,Zk as g3}from"./chunk-xb0evp2m.js";import{al as S}from"./chunk-yxtfg4wy.js";import{gl as j$}from"./chunk-xyv3y476.js";import{$l as t2}from"./chunk-zyvmbqcx.js";import{gm as N2,jm as E}from"./chunk-aes0ecnp.js";import{sm as m2}from"./chunk-q0d45r2j.js";import{Im as a3}from"./chunk-rp2f9mq1.js";var k$="mcp",R$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class D extends l{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $3=/^[A-Za-z0-9_-]{1,64}$/,E$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z3=4000,R=1e5,b$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function J8($){return L3.get($)}class n{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=g$(z.files),this.featureOn=z.featureOn??K2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,y$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(Y3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){D2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new D(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!Y2(X))throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new D(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let H=Q.value,U={caller:$,req:$.req,tool:K,input:H,ctx:G},V=await this.fillPath(Y,U),{path:N}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(N!==K.url)throw new D(`"${Z}" has nothing at ${V}.`,404);let I={};for(let A of Y.jsonKeys)if(H[A]!==void 0)I[A]=H[A];let P,J="";if(Y.fileFields.length>0)P=await this.formData(Y,I,U);else if(K.method==="GET")J=t$(I);else if(Y.jsonKeys.length>0)P=I;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(U)):void 0,O={...j?{credentials:j}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let A=J?`${V}?${J}`:V;T=Object.keys(O).length>0?await this.dispatcher.dispatchAs($.req,K.method,A,P,O):await this.dispatcher.dispatchAs($.req,K.method,A,P)}catch(A){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,A),new D(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await V3(Z,T);return await this.project(Y,U,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(E$)].map(([,F,C])=>({name:F,modifier:C})),Q=X.params??{};for(let F of K)if(!(F.name in Q))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,C]of Object.entries(Q)){if(!K.some((w)=>w.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(Q3(C))c$(z,`params.${F}`,C);else K3(z,`params.${F}`,C)}let H=[],U;if(X.input){if(U=X.input.toJSONSchema(),U.type!=="object"||!U.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(U.properties)}let V=Object.entries(X.files??{}).map(([F,C])=>({name:F,binder:C}));for(let F of V)K3(z,`files.${F.name}`,F.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let N=H3(z,G,X.annotations);if(V.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let I={},P=(F,C)=>{if(F in I)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);I[F]=C},J=new Map,j=new Map;for(let F of K){let C=Q[F.name];if(C==="input"){let w=i.string().describe(`The ":${F.name}" segment of the url.`);P(F.name,F.modifier==="?"||F.modifier==="*"?w.optional():w)}else if(Q3(C)){let w=C.as??F.name;P(w,C.input),j.set(F.name,{key:w,param:C})}else J.set(F.name,C)}let O={};for(let F of V)if(F.binder==="input")P(F.name,i.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),O[F.name]=this.remoteFileSchema();let T=[...Object.keys(I),...V.map((F)=>F.name)];for(let F of new Set(T))if(H.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let A=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:U3(X.input,U,i.object(I)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:N,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),x=!V.every((F)=>F.binder==="input")?null:V.length===0?A:Object.freeze({...A,inputSchema:U3(X.input,U,i.object(l$(I,Object.keys(O))),O)});return{kind:"route",descriptor:A,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let H of Object.keys(Y))if(!W.includes(H))K.push(`a file has no field "${H}"`);for(let H of W){let U=Y[H];if(U===void 0||U===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof U!=="string")K.push(`a file's "${H}" must be a string`);else Q[H]=U}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:H3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!Y2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let H=G.signal??new AbortController().signal;return X3(X,Y.value,W3(G3(X,Q,H,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Y2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(D2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new D(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return L3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new D(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(x,F)=>{if(!W.progress)return;let C;try{C=$.meta.remote?.progress?$.meta.remote.progress(x,F):w$(x,F)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(C)W.progress(C)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z3(this.runNative($,{...K,ctx:G},G),Q)}let H=$.meta.remote,U=await this.bind($,"the remote context",()=>H.context(K));if(typeof U!=="object"||U===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,U),new D(`"${X}" failed on the server.`,500);let V=$.tool.timeoutMs,N=[...W.signal?[W.signal]:[],...V!==void 0?[AbortSignal.timeout(V)]:[]],I=N.length===0?new AbortController().signal:N.length===1?N[0]:AbortSignal.any(N),P=[],J=G3($,U,I,P);if(!W.approved&&Y2($)&&await X3($,K.input,W3(J)))throw new h(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await z3(this.runNative($,{...K,ctx:J},J),Q,I)}catch(x){if(I.aborted&&x===I.reason){if(W.signal?.aborted)throw new D(`"${X}" was cancelled.`,499);throw new D(`"${X}" did not finish within ${V} ms.`,504)}if(x instanceof D)throw x;if(x instanceof l||x instanceof h)throw new D(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new D(`"${X}" failed on the server.`,500)}let O=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new D(`"${X}" failed on the server.`,500)};if(F3(j))throw O("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(P)}catch(x){throw O(`could not read an image it showed: ${x}`)}let A=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(A);if(x.ok===!1)throw O(`answered what its output schema refuses: ${x.errors.join(", ")}`);A=x.value}for(let x of T)W.images?.(x);if(A===void 0)return null;if(typeof A==="string")return A.length>R?`${A.slice(0,R)}\u2026 [cut at ${R} of ${A.length} characters]`:A;let Z2=JSON.stringify(A);if(Z2!==void 0&&Z2.length>R)return`${Z2.slice(0,R)}\u2026 [cut at ${R} of ${Z2.length} characters]`;return A}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new D(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let H=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new D(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${H}`,"");continue}W=W.replace(H,n$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,H]of Object.entries(Z))O2(K,Q,H);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new D(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(U)=>new D(`"${Z}" of "${$}" ${U}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!h$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!m$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let U=W.data.replace(/\s+/g,"");if(Math.floor(U.length*3/4)-d$(U)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(U.length%4!==0||!u$.test(U))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(U,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(H.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let U=await J3(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!U.ok)throw G(`could not be fetched: ${H.host} answered ${U.status}.`);let V=await U.arrayBuffer();return new File([V],W.name,{type:W.mimeType})}catch(U){if(U instanceof D)throw U;throw G(`could not be fetched from ${H.host}: ${U instanceof Error?U.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(k$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!R$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await V3(G,z);let X=(V,N)=>{if(N===void 0)console.error(`[gemi/mcp] "${G}" ${V}`);else console.error(`[gemi/mcp] "${G}" ${V}`,N);return new D(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=Q;if($.result)try{H=await $.result(Q,Z)}catch(V){throw X("failed in its result projection:",V)}if(W){let V=W.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let U=JSON.stringify(H);if(U!==void 0&&U.length>R)return`${U.slice(0,R)}\u2026 [cut at ${R} of ${U.length} characters]`;return H}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof l)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new D(`"${$.descriptor.name}" failed on the server.`,500)}}}function y$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function f$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!f$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function w$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function G3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(U)=>async()=>{throw new l(`"${W}" was called by a remote MCP client, which has no ${U}.`,{retryable:!1})},H={put:async(U,V={})=>{if(!V.showModel)return K("attachment store")();let N=V.mimeType||U.type;if(!/^image\//i.test(N))throw new l(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${N?`"${N}"`:"a blob with no type"}.`,{retryable:!1});let I=U.arrayBuffer().then((P)=>({type:"image",data:Buffer.from(P).toString("base64"),mimeType:N}));return I.catch(()=>{}),G.push(I),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:V.name??(U instanceof File?U.name:"image"),mimeType:N,size:U.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:H,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(U)=>I3({...U,signal:U.signal?AbortSignal.any([z,U.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:B3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:N3().meter}}function Y2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function D2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Y3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var v$=10485760;function g$($){let Z=$?.maxBytes??v$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function h$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var m$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,u$=/^[A-Za-z0-9+/]*={0,2}$/;function d$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function c$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var p$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function i$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function H3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?i$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!p$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function U3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,H])=>[Q,H.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let H=[],U={};if($){let N=$.safeParse(Q);if(N.ok===!1)H.push(...N.errors);else U={...N.value}}let V=z.safeParse(Q);if(V.ok===!1)H.push(...V.errors);else U={...U,...V.value};for(let[N,I]of Object.entries(G)){let P=Q[N];if(P===void 0){H.push(`"${N}" is required`);continue}let J=I.safeParse(P);if(J.ok===!1)H.push(...J.errors.map((j)=>`${N}: ${j}`));else U[N]=J.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:U}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let H=K(Q);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function l$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function n$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new D(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function O2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function t$($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function V3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!b$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>R)return`${W.slice(0,R)}\u2026 [cut at ${R} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>Z3?`${z.slice(0,Z3)}\u2026`:z;throw new D(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new D(`"${$}" failed on the server.`,Z.status)}import{createHash as s$,randomBytes as o$,timingSafeEqual as a$}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class r${options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${o$(32).toString("base64url")}`}static hash($){return s$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&a$(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as y3,randomBytes as j3}from"crypto";async function A2($,Z){let z=e$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function e$(){try{let $=E();return $.bound(t)?$.make(t):null}catch{return null}}var x2=["2026-07-28"],Q2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...Q2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",_={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _3($){if(Array.isArray($))throw new L(_.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(_.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new L(_.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(_.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new L(_.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as $6,timingSafeEqual as Z6}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=O3($,Z,X);if(K.length!==Q.length||!Z6(K,Q))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=G)return null;return H}function O3($,Z,z){return $6("sha256",H2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",A3="gemi.mcp.session.v1",z6=86400000,x3=600000,C3="gemi_approval",b2=2000,G6={limit:600,window:60},W6={limit:30,window:60};class z2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=K6(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,H2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??G6,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new E3,this.approvalTimeoutMs=Z.approvalTimeoutMs??x3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??K2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new L(_.InvalidRequest,"Origin not allowed.")),403);let G=z?Y6(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return S3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await X6($,this.maxBodyBytes))}catch(Y){if(Y instanceof V2)return v(b(null,new L(_.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new L(_.ParseError,"Parse error.")),400)}let X=new u($,{},"api",this.endpoint.pathname);return await m.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new L(_.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let P=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===P.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:J}),T3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(_.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let H=this.session($,z),U=$.headers.get("mcp-protocol-version");if(U!==null&&U!==H.state.v)throw new L(_.InvalidRequest,`MCP-Protocol-Version ${U} is not the session's ${H.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,N=new AbortController;this.inflight.set(V,N);let I=AbortSignal.any([N.signal,$.signal]);try{return await this.respond(Y,async(P,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:J}),T3(K)||H6(this.registry,Y,H.state),I,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Q2.includes(G)?G:Q2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q3(X.elicitation),p:U2(z),exp:Date.now()+z6},K=k2(A3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(_.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(A3,"gms1",z);if(!G||G.p!==U2(Z))throw new L(_.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new L(_.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new L(_.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||D3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new L(_.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,j)=>{G.outcome="denied",G.reason=J,G.message=j},K=(J,j,O)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(O!==void 0)G.error=O},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(_.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let O=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(O),this.toolResult($,{content:[{type:"text",text:O}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let O=await this.approval($,Q,z,Y,G);if(O.kind==="answer")return O.result;G.approved=!0}}let H=U6($),U=[],V;try{V=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>U.push(J),...H?{progress:H}:{}})}catch(J){if(J instanceof D){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof h){let O=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,O),new L(_.InvalidParams,O)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let j=`"${Z}" failed on the server.`;return K(j,void 0,J),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}let N=typeof V==="string"?V:JSON.stringify(V??null),I=Q.outputSchema&&($.era.modern||M(V))?{structuredContent:V}:{},P=[...U.length>0&&V===null?[]:[{type:"text",text:N}],...U];return G.outcome="ok",this.toolResult($,{content:P,...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=V6(Z,z),Y=(N,I="approval-declined")=>{return G(I,N),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}},K=(N,I)=>{return G(N,I.message),I};if($.era.modern){let N=M($.params._meta)?$.params._meta:{},I=M(N[q2])?N[q2]:{},P=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=Q6(z);if(P&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==U2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new L(_.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new L(_.InvalidParams,"requestState has already been used."));return M3(P[C3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q3(I.elicitation))throw K("approval-unavailable",new L(_.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let O={p:U2($.principal),t:Z.name,a:j,n:j3(16).toString("base64url"),exp:Date.now()+x3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",O),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let H=`gemi-approval-${j3(12).toString("base64url")}`,U=Q.sessionId,V=await new Promise((N)=>{let I=setTimeout(()=>{this.pending.delete(H),N(null)},this.approvalTimeoutMs),P=(J)=>{clearTimeout(I),N(J)};this.pending.set(H,{session:U,resolve:P}),$.signal.addEventListener("abort",()=>{this.pending.delete(H),P(null)}),$.stream.send({jsonrpc:"2.0",id:H,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return V&&!V.error&&M3(V.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new L(_.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new L(_.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R3(new u($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,W6);return z===null?null:k3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:k3(Z)}}class f3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
3
3
  data: ${JSON.stringify($)}
4
4
 
5
5
  `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class V2 extends Error{}async function X6($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new V2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function S3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function Y6($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function K6($){let Z;try{Z=new URL($)}catch{throw Error(`route.mcp.remote.url: "${$}" is not a URL.`)}let z=Z.hostname==="localhost"||Z.hostname==="127.0.0.1"||Z.hostname==="[::1]";if(Z.protocol!=="https:"&&!(Z.protocol==="http:"&&z))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if(Z.search||Z.hash||Z.username||Z.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if(Z.pathname==="/"||Z.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return Z}function U2($){return y3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function Q6($){return y3("sha256").update(b3($??{})).digest("base64url")}function q3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function T3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function H6($,Z,z){if(Z.method!=="tools/call"||!z.e)return!1;let G=Z.params?.name;return typeof G==="string"&&$.descriptors({names:[G]})[0]?.requiresApproval===!0}function U6($){let z=(M($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function V6($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
@@ -7,4 +7,4 @@ data: ${JSON.stringify($)}
7
7
  Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function M3($){return M($)&&$.action==="accept"&&M($.content)&&$.content.approve===!0}function k3($){return v(b(null,new L(_.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function J6($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=N6($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y2($);return}let G;try{if(G=Z.locks?.()??F6(),$.onOneServer){let W=Math.floor((Z.now??Date.now())/60000);if(!await G.store.advance(`gemi:cron-tick:${$.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${$.name}; skipped it:`,W);return}if(z===void 0){await y2($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y2($,W))}catch(W){if(W instanceof g3)console.error(`Cron job ${$.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,W);else console.error(`Could not take the withoutOverlapping lock of cron job ${$.name}:`,W)}}var w3=300000;function N6($){if(!$)return;if($===!0)return w3;return $.expiresAfter??w3}var v3;function F6(){return v3??=new d(new h3),v3}async function y2($,Z){try{await $.onTick.call($)}catch(z){console.error(`Error executing cron job ${$.name}:`,z)}try{await $.callback.call($,Z)}catch(z){console.error(`Error in cron job ${$.name}:`,z)}try{await $.onComplete.call($)}catch(z){console.error(`Error completing cron job ${$.name}:`,z)}}class c{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor($){this.resolved=$.jobs}get jobs(){return[...this.resolved]}useJobs($){this.resolved=$}useLocks($){this.locks=$}start($=(Z)=>Z()){if(this.stopped=!1,this.resolved.length===0)return;let Z=globalThis.__gemiCronJobs??=new Map,z=new Map;for(let G of this.resolved){let W=new G;if(!W.name){console.error(`Cron job must have a name \u2014 ${G.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let X=z.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${G.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}z.set(W.name,G.name||"an anonymous class"),Z.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(W.name,()=>$(()=>J6(W,{locks:K})))});Z.set(W.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let $ of this.handles)$.stop();this.handles=[]}async drain($=1/0){this.stop();let Z,z=new Promise((G)=>{if($!==1/0)Z=setTimeout(G,$)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((G)=>G.done)),z]),clearTimeout(Z),{unfinished:[...this.inFlight.values()].map((G)=>({...G.tick}))}}get running(){return this.inFlight.size}track($,Z){let z={},G=Promise.resolve().then(Z).finally(()=>this.inFlight.delete(z));return this.inFlight.set(z,{tick:{name:$,startedAt:new Date},done:G}),G}}import{isMainThread as B6}from"worker_threads";var P6=100,I6=($)=>Math.min(P6,Math.floor($/10));class L6 extends B{register(){this.app.singleton(q,()=>new q(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(d,()=>this.app.make(q).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=S(m3(),$);if($.jobs===void 0)this.app.make(q).useJobs(await i3(Z));if($.workflows===void 0){let G=await l3(z);if(G.length>0)this.app.make(q).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(q))return;let Z=this.app.make(q);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running queued job(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-I6(z)));if(G.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+G.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function t8($){if(D6($),Bun.env.NODE_ENV!=="production")return O6($);if(n3($))return;if(!d3())return;if(!$.bound(q))return;$.make(q).start()}function n3($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof u3}function _6($){if(n3($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(q))return!1;try{return!$.make(q).durable}catch{return!1}}function D6($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||p3())return;if(process.env.ROOT_DIR===void 0||!B6)return;if(c3()){if(!_6($))return;console.warn('[gemi] GEMI_QUEUE_CLAIM=off is ignored: the memory queue driver keeps jobs in the process that dispatched them, so no worker could run them. This server runs its own jobs. Use a driver other processes can read, such as "database", to hand jobs to `gemi queue:work`.')}else if(Z.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${Z}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function O6($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(q))$.make(q).start()}var j6=new Set,A6={refusal:null,apply:($)=>$,carried:null};async function W$($){let Z=E(s);if(Z.config.global.length===0)return A6;let{pathname:z}=new URL($.url),G=a3(z),W=new u($,{},G?"api":"view","");return await m.run(W,async()=>{let X=m.getStore(),{headers:Y,cookies:K}=X,Q=(H)=>{if(!g2(H)){let V=v2(H,Y,K);return G?V:C6(V,z)}let U=new Headers(Y);return U.delete("Set-Cookie"),v2(H,U,j6)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(H){let U=!G&&x6(z);if(H?.kind===t3){let V=G?G$(H.payload.api):U?Z$(H.payload.viewData??H.payload.api):w2(H.payload.view);return{refusal:Q(V),apply:Q,carried:null}}if(s3(H)&&(G||U))return{refusal:Q(z$()),apply:Q,carried:null};if(o3(H)){console.error(H);let V=G||U?e3():w2($$());return{refusal:Q(V),apply:Q,carried:null}}throw H}finally{X.destroy()}})}function x6($){if(!$.endsWith(".json"))return!1;let Z=E().config;if(!Z.get("route.api")||!Z.get("route.view"))return!0;return E(o).viewDispatchers().every((z)=>r3(z.flatViewRoutes,$))}function C6($,Z){if(!g2($)||$.headers.getSetCookie().length===0)return $;try{return f2($.headers,Z),$}catch{let z=new Headers($.headers);return f2(z,Z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}var S6=120,q6=2000,T6=3;class r{manager;application;static token="broadcast.sockets";server=null;sockets=new Set;byTopic=new Map;topicReady=new Map;perIp=new Map;perUser=new Map;connections=0;revocationSeq=0;revokedAt=new Map;closing=!1;closed=null;onAllClosed=null;startPromise=null;constructor($,Z){this.manager=$;this.application=Z}get config(){return this.manager.config}matches($){try{return new URL($.url).pathname===this.config.path}catch{return!1}}get size(){return this.sockets.size}start($){return this.server=$,this.startPromise??=this.manager.start((Z,z)=>this.deliver(Z,z),{onGap:()=>this.onGap(),onRevoke:(Z)=>this.applyRevocation(Z)}).catch((Z)=>{this.startPromise=null,console.error("[gemi] The broadcast driver could not start; events reach no socket.",Z)}),this.startPromise}upgrade($,Z){return this.run(()=>this.tryUpgrade($,Z))}async tryUpgrade($,Z){if(this.closing||m2())return f(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return f(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(J2))return f(400,`Open the socket with the "${J2}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return f(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return f(503,"Too many connections.",{"Retry-After":"10"});let W=E6($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return f(429,"Too many connections from this address.",{"Retry-After":"30"});let X=this.reserve(W),Y=!1;try{let K=await this.authenticate($,Z,X);return Y=K===void 0,K}finally{if(!Y)this.release(X)}}async authenticate($,Z,z){let G=await W$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||m2())return f(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let U=new u($,{},"api",this.config.path);X=await m.run(U,async()=>{let V=m.getStore();try{return await H$(U)}finally{V.destroy()}},W)}catch(U){return console.error("[gemi] Resolving the session of a socket upgrade failed.",U),f(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=R6(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return f(429,"Too many connections for this user.",{"Retry-After":"30"});if(Y)z.userId=Y,this.perUser.set(Y,(this.perUser.get(Y)??0)+1);let K=Q$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:K$(K),request:{url:$.url,headers:[...$.headers]},carried:W,userId:Y,ip:z.ip,subs:new Map,topics:new Map,rate:{windowStart:Date.now(),subs:0,pings:0},reservation:z,closing:!1,closed:!1};if(!Z.upgrade($,{headers:{"Sec-WebSocket-Protocol":J2},data:Q}))return f(400,"The WebSocket upgrade failed.");return}checkOrigin($){let Z=$.headers.get("origin"),z=Boolean($.headers.get("cookie"));if(!Z)return z?"A socket that carries cookies must send an Origin header.":!0;return this.originAllowed(Z,$)?!0:"This origin may not open a socket."}originAllowed($,Z){let z;try{z=new URL($)}catch{return!1}if(z.protocol!=="https:"&&z.protocol!=="http:")return!1;let G=Z.headers.get("host");if(G&&z.host.toLowerCase()===G.toLowerCase())return!0;for(let W of[process.env.APP_URL,process.env.HOST_NAME,...this.config.allowedOrigins])if(W&&M6(W.trim(),z))return!0;return!1}reserve($){if(this.connections++,$)this.perIp.set($,(this.perIp.get($)??0)+1);return{ip:$,userId:null}}release($){this.connections--,X$(this.perIp,$.ip),X$(this.perUser,$.userId)}get websocket(){return{open:($)=>$.data.hub.onOpen($),message:($,Z)=>$.data.hub.onMessage($,Z),close:($)=>$.data.hub.onClose($),...this.socketOptions()}}socketOptions(){return{maxPayloadLength:this.config.maxInboundMessageBytes,idleTimeout:this.config.idleTimeout,backpressureLimit:this.config.backpressureLimit*2,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1}}onOpen($){let Z=$.data;if(this.closing){this.sayBye($);return}this.sockets.add($),a($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(k.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(k.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(k.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))a($,{op:"pong"});return;case"sub":this.subscribe($,z).catch((G)=>{if(console.error("[gemi] A socket subscription failed.",G),typeof z.id==="string"&&$.data.subs.has(z.id)){let W=$.data.subs.get(z.id);if($.data.subs.delete(z.id),W.topic&&!$.data.closed)this.leave($,W.topic);if(!$.data.closed)y($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(k.UnsupportedData,"Unknown op.")}}onClose($){let Z=$.data;if(Z.closed)return;Z.closed=!0;for(let[,z]of Z.subs)if(z.topic)this.leave($,z.topic);if(Z.subs.clear(),this.sockets.delete($),Z.reservation)this.release(Z.reservation),Z.reservation=null;if(this.closing&&this.sockets.size===0)this.onAllClosed?.()}rateWindow($){let Z=$.data.rate,z=Date.now();if(z-Z.windowStart>=this.config.subscribeRate.windowMs)Z.windowStart=z,Z.subs=0,Z.pings=0;return Z}countSub($){let{limit:Z}=this.config.subscribeRate,z=this.rateWindow($);if(z.subs++,z.subs>Z*2)return console.warn("[gemi] Socket closed for sending too many subscribe frames (1008)."),$.close(k.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=S6)return!0;return $.close(k.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!u2.test(G)){$.close(k.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return y($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!k6(Y))return y($,G,"invalid");if(z.subs.has(G))return y($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return y($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),y($,G,"unknown_channel");let Q;for(let H=1;;H++){let U=this.revocationSeq;if(Q=await this.authorize($,K),z.closed||z.subs.get(G)!==K)return;if(Q.ok!==!0)break;if((this.revokedAt.get(Q.topic)??0)<=U)break;if(H>=T6)return z.subs.delete(G),y($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),y($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(H){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,H),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);y($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;a($,{op:"subscribed",id:G,t:Q.topic})}authorize($,Z){let z=$.data,G=this.manager.channels;if(!G)return Promise.resolve({ok:!1,code:"unknown_channel"});return this.run(()=>G.authorize(new Request(z.request.url,{headers:z.request.headers}),Z.pattern,Z.params,{carried:z.carried}))}unsubscribeFrame($,Z){let z=Z.id;if(typeof z!=="string"||!u2.test(z)){$.close(k.UnsupportedData,"An unsub needs an id.");return}let G=$.data.subs.get(z);if(!G)return;if($.data.subs.delete(z),G.topic)this.leave($,G.topic)}join($,Z){let z=$.data,G=z.topics.get(Z)??0;if(z.topics.set(Z,G+1),G===0){$.subscribe(Z);let W=this.byTopic.get(Z);if(!W){W=new Set,this.byTopic.set(Z,W);let X=Promise.resolve().then(()=>this.manager.topicAdded(Z));this.topicReady.set(Z,X),X.catch(()=>{if(this.topicReady.get(Z)===X)this.topicReady.delete(Z)})}W.add($)}return this.topicReady.get(Z)??Promise.resolve()}leave($,Z){let z=$.data,G=z.topics.get(Z)??0;if(G>1){z.topics.set(Z,G-1);return}if(z.topics.delete(Z),!z.closed)$.unsubscribe(Z);let W=this.byTopic.get(Z);if(!W)return;if(W.delete($),W.size>0)return;this.byTopic.delete(Z),this.topicReady.delete(Z),Promise.resolve().then(()=>this.manager.topicRemoved(Z)).catch((X)=>console.error(`[gemi] The broadcast driver could not unsubscribe from "${Z}".`,X))}deliver($,Z){let z=this.byTopic.get($);if(!z||!this.server)return;let G=this.config.backpressureLimit;for(let W of z)if(!W.data.closing&&W.getBufferedAmount()>G)console.warn(`[gemi] Socket closed for backpressure (1013) on "${$}".`),h2(W,k.TryAgainLater,"Too far behind; reconnect.");this.server.publish($,Z)}onGap(){this.sendAll({op:"gap"});for(let $ of this.byTopic.keys()){let Z=Math.floor(Math.random()*q6);setTimeout(()=>{if(!this.closing)this.applyRevocation({topic:$})},Z).unref?.()}}applyRevocation($){if("user"in $){for(let W of this.sockets)if(W.data.userId===$.user&&!W.data.closing)h2(W,k.Revoked,"Revoked.");return}let Z=$.topic,z=++this.revocationSeq;this.revokedAt.set(Z,z);let G=this.byTopic.get(Z);if(!G)return;for(let W of G)this.reauthorize(W,Z,z)}async reauthorize($,Z,z){let G=$.data,W=[...G.subs].filter(([,Y])=>Y.topic===Z);if(W.length===0)return;$.unsubscribe(Z);let X=await Promise.all(W.map(([,Y])=>this.authorize($,Y).catch((K)=>{return console.error(`[gemi] Authorizing "${Z}" again after a revoke failed.`,K),{ok:!1,code:"revoked"}})));if(G.closed)return;if(this.revokedAt.get(Z)!==z)return;if(W.forEach(([Y,K],Q)=>{let H=X[Q];if(G.subs.get(Y)!==K)return;if(H.ok===!0&&H.topic===Z)return;G.subs.delete(Y),this.leave($,Z),y($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)a($,{op:"subscribed",id:Y,t:Z})}sendAll($){let Z=JSON.stringify($);for(let z of this.sockets)z.send(Z)}shutdown($={}){if(this.closed)return this.closed;this.closing=!0,this.closed=new Promise((G)=>{this.onAllClosed=G});let Z=[...this.sockets];if(Z.length===0)this.onAllClosed?.();if(Z.length>0)console.log(`[gemi] Closing ${Z.length} broadcast socket(s) (1012).`);for(let G of Z)this.sayBye(G);return setTimeout(()=>{for(let G of Z)try{G.terminate()}catch{}this.onAllClosed?.()},$.terminateAfterMs??2000).unref?.(),this.closed}get isClosing(){return this.closing}sayBye($){a($,{op:"bye",code:k.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),h2($,k.Restart,"Server restarting.")}run($){return N2.run(this.application,$)}}function M6($,Z){let z=/^(?:(https?):\/\/)?\*\.([^/:]+)(?::(\d+))?\/?$/i.exec($);if(z){let[,G,W,X]=z;if(G&&`${G.toLowerCase()}:`!==Z.protocol)return!1;if((X??"")!==Z.port)return!1;return Z.hostname.toLowerCase().endsWith(`.${W.toLowerCase().replace(/\.$/,"")}`)}if(/^https?:\/\//i.test($))try{return new URL($).origin===Z.origin}catch{return!1}return $.toLowerCase().replace(/\/$/,"")===Z.host.toLowerCase()}function h2($,Z,z){$.data.closing=!0,$.close(Z,z)}function a($,Z){$.send(JSON.stringify(Z))}function y($,Z,z){a($,{op:"denied",id:Z,code:z})}function f($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function k6($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function R6($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function E6($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return Y$(z)??z;try{return Z.requestIP($)?.address??null}catch{return null}}function X$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class b6 extends B{register(){this.app.singleton(g,()=>new g(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(r,()=>new r(this.app.make(g),this.app))}boot(){let $=this.app.config.get("route.channels");if($)V$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(g).driver:void 0;y6(Z,process.env,z)}async shutdown(){if(this.app.resolved(r))this.app.make(r).shutdown();if(!this.app.resolved(g))return;await this.app.make(g).close()}}function y6($,Z=process.env,z){if(!($.driver==="redis"||z instanceof U$)||Z.SECRET)return;let W=`[gemi] The "redis" broadcast driver needs SECRET set, the same on every instance: Broadcast.toOthers tags the sender's socket with a key derived from it, and every instance must derive the same one.`;if(Z.NODE_ENV==="production")throw Error(W);console.warn(W)}class f6 extends B{register(){this.app.singleton(d2,()=>new d2(this.app.config.get("cache",{}),{application:this.app}))}}class w6 extends B{register(){this.app.singleton(G2,()=>new G2(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(G2))return;await this.app.make(G2).close()}}class v6 extends B{register(){this.app.singleton(p2,()=>new p2(this.app.config.get("auth",{}))),this.app.singleton(c2,()=>{let $=this.app.config.get("auth",{});return new c2({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){let $=this.app.config.get("auth",{});N$($),J$($?.emailCode??{},{warn:!0})}}var g6=100,h6=($)=>Math.min(g6,Math.floor($/10));class m6 extends B{register(){this.app.singleton(c,()=>new c(S(i2(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(c),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=S(i2(),Z);$.useJobs(await F$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let z=this.app;if(z.bound(d))$.useLocks(()=>z.make(d));$.start((G)=>N2.run(z,G))}async shutdown($){if(!this.app.resolved(c))return;let Z=this.app.make(c);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running cron tick(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-h6(z)));if(G.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+G.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class e extends B${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return P$(this.modelName)}async load(){if(!this.available)throw new l2(this.modelName);let $=n2(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new l2(this.modelName);let G=n2(this.modelName),W=this.hasActorColumn(G),X={active:Z};if(W)X.updatedBy=z.actor;return await G.asSystem(()=>G.upsert({where:{key:$},create:{key:$,...X},update:X})),{actorRecorded:W}}hasActorColumn($){let Z=$?.$schema?.fields?.updatedBy;return Z!==void 0&&Z.type==="String"}}function a9($){return $}function I$(){return{features:void 0,enabled:!0,source:new e,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class u6 extends B{register(){this.app.singleton(F2,()=>{let $=this.app.config.get("features",{}),Z=S(I$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new e($.model);else if($?.model!==void 0&&$.source instanceof e&&$.source.modelName!==$.model)B2.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new F2(Z,(z)=>B2.warning(z))})}async boot(){let $=this.app.make(F2);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){B2.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class d6 extends B{register(){this.app.singleton(t2,()=>new t2(this.app.config.get("mail",{})))}}class c6 extends B{register(){this.app.singleton(P2,()=>new P2(this.app.config.get("encryption",{})))}boot(){if(this.app.make(P2).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new s2(`auth.connections (${z.join(", ")}) keeps OAuth tokens encrypted, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`);let G=L$();if(G.length===0)return;throw new s2(`${G.join(", ")} ${G.length===1?"is an encrypted column":"are encrypted columns"}, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`)}}var p6=Symbol.for("gemi.broadcastEvent");function _$($){return typeof $==="object"&&$!==null&&$[p6]===!0}function i6($){return`listener:${$}`}function O$($,Z){l6($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends D${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,H]=n6(K),U=E(p).rehydrate(Q,H);await new $().handle(U)}onFail(K){console.error(`The listener ${$.name} threw while handling ${X} off the queue. The queue will retry it up to ${z} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${$.name} failed every one of its ${z} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,K)}};return Object.defineProperty(Y,"name",{value:i6($.name),writable:!0}),Y}function l6($){if(Object.getOwnPropertyDescriptor($,"name")?.writable)return;throw Error(`The listener ${$.name} sets \`queued = true\` but does not declare \`static name\`, so it would be registered with the queue `+"under its class name \u2014 which a production build renames while the "+`payload that names it does not. Add: static name = "${$.name}";`)}function n6($){return typeof $[0]==="string"?$:$[0]}class p{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=S(I2(),$),this.useListeners(this.config.listeners)}useListeners($){this.config.listeners=$,this.listeners={},this.events={};let Z=new Set;for(let z of $){if(!z.event){console.error(`Listener ${z.name} does not declare \`static event\`, so there is no event name to register it under and its handle will never run. Add: static event = SomeEvent;`);continue}if(Z.has(z.name)){console.error(`Two event listeners are named "${z.name}" \u2014 the first is `+"registered and this one is not. A listener's name identifies it across the framework, so only one class can hold it. Rename one.");continue}Z.add(z.name);let G=z.event.name,W=new z;this.events[G]??=z.event,(this.listeners[G]??=[]).push({listener:z,job:W.queued?O$(z,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:$})=>$?[$]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch($,Z){if(this.deferToCommit($,Z,!1))return;this.runListeners($,Z)}async dispatchAndWait($,Z){if(this.deferToCommit($,Z,!0))return;return this.runListeners($,Z)}deferToCommit($,Z,z){let{name:G,afterCommit:W}=$.constructor;if(!W)return!1;let X=j$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=_$($);if(G.length===0&&!W){this.warnNothingIsListening(z);return}for(let{listener:X,job:Y}of G){if(Y){this.enqueue(Y,X,z,Z);continue}try{await new X().handle($)}catch(K){console.error(`The listener ${X.name} threw while handling ${z}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",K)}}if(W)this.broadcast($,z)}broadcast($,Z){try{E(g).broadcastEvent($)}catch(z){console.error(`The event ${Z} could not be broadcast.`,z)}}rehydrate($,Z=[]){let z=this.events[$];if(!z)throw Error(`Cannot rebuild the event "${$}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${$}"\`.`);return new z(...Z)}enqueue($,Z,z,G){if(G===void 0){console.error(`The listener ${Z.name} is queued, but ${z} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${z}.dispatch(...) or ${z}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${Z.name} could not be queued for ${z}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{E(q).push($,JSON.stringify([z,G]),{reportFailure:!1}).catch(W)}catch(X){W(X)}}warnNothingIsWaitedFor($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has($))return;this.warnedAboutWaiting.add($),console.warn(`[gemi] ${$}.dispatchAndWait() was called inside a transaction and ${$} declares \`static afterCommit = true\`, so it resolved `+"immediately with no listener having run \u2014 they run when the "+"transaction commits. Await the transaction instead, or drop afterCommit if the caller needs the side effects first. Development only.")}warnNothingIsListening($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has($))return;this.warnedFor.add($),console.warn(`[gemi] ${$} was dispatched and nothing is listening for it. A listener registers under the name its event declares, so check that app/listeners holds a Listener with \`static event = ${$}\` and that ${$} declares \`static name = "${$}"\`. Development only.`)}}class t6 extends B{register(){this.app.singleton(p,()=>new p(this.app.config.get("events",{})))}async boot(){let $=this.app.make(p),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=S(I2(),Z);$.useListeners(await A$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(q);for(let W of z)G.registerJob(W)}}class s6 extends B{register(){this.app.singleton(o2,()=>new o2(this.app.config.get("filesystem",{})))}}class o6 extends B{register(){this.app.singleton(a2,()=>new a2(this.app.config.get("image",{})))}}class a6 extends B{register(){this.app.instance(r2,new r2)}}class r6 extends B{register(){this.app.singleton(L2,()=>new L2(S(x$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(L2).boot()}}class e6 extends B{register(){this.app.singleton(s,()=>new s(S(C$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(s).assertGlobalMiddleware()}}function Z4($){return $}function q$(){return{driver:new S$,limit:1000,window:60}}class $8 extends B{register(){this.app.singleton(t,()=>new t(S(q$(),this.app.config.get("ratelimiter",{}))))}}function Q4($){return $}function T$(){return{url:process.env.REDIS_URL,options:void 0}}class Z8 extends B{register(){this.app.singleton(W2,()=>new W2(S(T$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(W2))return;this.app.make(W2).close()}}function _2($,Z){let z=$.get(Z);if(!z)throw Error(`Missing "${Z}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return z}class z8 extends B{register(){this.app.singleton($2,()=>new $2(_2(this.app.config,"route.api"))),this.app.singleton(X2,()=>new X2(_2(this.app.config,"route.view"),this.app.config.get("auth",{}))),this.app.singleton(o,()=>new o({api:this.app.make($2),view:this.app.make(X2)},{api:_2(this.app.config,"route.api"),view:_2(this.app.config,"route.view"),auth:this.app.config.get("auth",{}),domains:this.app.config.get("route.domains"),clientIpTrust:M$(process.env)})),this.app.singleton(n,()=>{let $=this.app.config.get("route.mcp");if(!$?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new n(new $.router,this.app.make($2),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton(z2,()=>{let $=this.app.config.get("route.mcp");if(!$?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new z2(this.app.make(n),$.remote)})}boot(){if(this.app.make($2),this.app.make(X2),this.app.make(o),this.app.config.get("route.mcp"))this.app.make(n);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make(z2);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class G8 extends B{register(){this.app.singleton(e2,()=>new e2(this.app.config.get("runs",{}),{application:this.app}))}}
8
8
  export{k$ as sb,D as tb,h as ub,J8 as vb,n as wb,j2 as xb,r$ as yb,A2 as zb,k2 as Ab,R2 as Bb,z2 as Cb,c as Db,L6 as Eb,t8 as Fb,W$ as Gb,r as Hb,b6 as Ib,f6 as Jb,w6 as Kb,v6 as Lb,m6 as Mb,e as Nb,a9 as Ob,I$ as Pb,u6 as Qb,d6 as Rb,c6 as Sb,p6 as Tb,_$ as Ub,p as Vb,t6 as Wb,s6 as Xb,o6 as Yb,a6 as Zb,r6 as _b,e6 as $b,Z4 as ac,q$ as bc,$8 as cc,Q4 as dc,T$ as ec,Z8 as fc,z8 as gc,G8 as hc};
9
9
 
10
- //# debugId=A4F49800270C99E264756E2164756E21
10
+ //# debugId=6AB33447A76B899464756E2164756E21