gemi 0.144.0 → 0.145.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 (208) hide show
  1. package/dist/ai/AgentController.d.ts +2 -2
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/index.d.ts +2 -2
  4. package/dist/ai/index.d.ts.map +1 -1
  5. package/dist/ai/index.js +11 -11
  6. package/dist/ai/index.js.map +3 -3
  7. package/dist/ai/store/Nonces.d.ts +68 -0
  8. package/dist/ai/store/Nonces.d.ts.map +1 -1
  9. package/dist/ai/store/index.d.ts +1 -1
  10. package/dist/ai/store/index.d.ts.map +1 -1
  11. package/dist/app/index.js +1 -1
  12. package/dist/bun/plugin.js +1 -1
  13. package/dist/bun/preload.js +1 -1
  14. package/dist/{chunk-fg2k18d2.js → chunk-0k8fk96c.js} +2 -2
  15. package/dist/{chunk-fg2k18d2.js.map → chunk-0k8fk96c.js.map} +1 -1
  16. package/dist/{chunk-y5yac6n1.js → chunk-0mt7kqwx.js} +2 -2
  17. package/dist/{chunk-y5yac6n1.js.map → chunk-0mt7kqwx.js.map} +1 -1
  18. package/dist/{chunk-1ed75a7b.js → chunk-1fyn63ka.js} +3 -3
  19. package/dist/{chunk-1ed75a7b.js.map → chunk-1fyn63ka.js.map} +1 -1
  20. package/dist/{chunk-tkvamktq.js → chunk-1ttd4rn9.js} +2 -2
  21. package/dist/{chunk-tkvamktq.js.map → chunk-1ttd4rn9.js.map} +1 -1
  22. package/dist/{chunk-m70hn4eg.js → chunk-1wz6kwjc.js} +2 -2
  23. package/dist/{chunk-m70hn4eg.js.map → chunk-1wz6kwjc.js.map} +1 -1
  24. package/dist/{chunk-fsem81ec.js → chunk-29jmaj16.js} +1 -1
  25. package/dist/{chunk-fpz9e3xx.js → chunk-2b3hh9xw.js} +3 -3
  26. package/dist/{chunk-fpz9e3xx.js.map → chunk-2b3hh9xw.js.map} +1 -1
  27. package/dist/{chunk-n9zycjm1.js → chunk-2djjs8f1.js} +3 -3
  28. package/dist/{chunk-n9zycjm1.js.map → chunk-2djjs8f1.js.map} +1 -1
  29. package/dist/{chunk-p81qeav5.js → chunk-2ery6a75.js} +3 -3
  30. package/dist/{chunk-p81qeav5.js.map → chunk-2ery6a75.js.map} +1 -1
  31. package/dist/{chunk-hyhbk12v.js → chunk-2k3935ke.js} +2 -2
  32. package/dist/{chunk-hyhbk12v.js.map → chunk-2k3935ke.js.map} +1 -1
  33. package/dist/{chunk-qt6x2r6a.js → chunk-2x6cv37t.js} +2 -2
  34. package/dist/{chunk-qt6x2r6a.js.map → chunk-2x6cv37t.js.map} +1 -1
  35. package/dist/{chunk-68f0jpje.js → chunk-313593t3.js} +2 -2
  36. package/dist/{chunk-68f0jpje.js.map → chunk-313593t3.js.map} +1 -1
  37. package/dist/{chunk-5qfzvnyp.js → chunk-3csz8pfk.js} +3 -3
  38. package/dist/{chunk-5qfzvnyp.js.map → chunk-3csz8pfk.js.map} +1 -1
  39. package/dist/{chunk-rezmtdyt.js → chunk-3x8zrsby.js} +2 -2
  40. package/dist/{chunk-rezmtdyt.js.map → chunk-3x8zrsby.js.map} +1 -1
  41. package/dist/{chunk-6d3m2w2p.js → chunk-43ws58db.js} +2 -2
  42. package/dist/{chunk-6d3m2w2p.js.map → chunk-43ws58db.js.map} +1 -1
  43. package/dist/chunk-49s8wwp2.js +5 -0
  44. package/dist/{chunk-b6mgrrk6.js.map → chunk-49s8wwp2.js.map} +1 -1
  45. package/dist/{chunk-ncb1qtae.js → chunk-4d4td4k9.js} +2 -2
  46. package/dist/{chunk-ncb1qtae.js.map → chunk-4d4td4k9.js.map} +1 -1
  47. package/dist/{chunk-v57ndv0h.js → chunk-4jd25v6d.js} +2 -2
  48. package/dist/{chunk-v57ndv0h.js.map → chunk-4jd25v6d.js.map} +1 -1
  49. package/dist/{chunk-78bfmwp0.js → chunk-4m0eqq80.js} +2 -2
  50. package/dist/{chunk-78bfmwp0.js.map → chunk-4m0eqq80.js.map} +1 -1
  51. package/dist/{chunk-ktrm6y5j.js → chunk-563ksar3.js} +3 -3
  52. package/dist/{chunk-ktrm6y5j.js.map → chunk-563ksar3.js.map} +1 -1
  53. package/dist/{chunk-z80v4z8y.js → chunk-5q2pmve9.js} +2 -2
  54. package/dist/{chunk-z80v4z8y.js.map → chunk-5q2pmve9.js.map} +1 -1
  55. package/dist/{chunk-20d0n391.js → chunk-5yz684rw.js} +2 -2
  56. package/dist/{chunk-20d0n391.js.map → chunk-5yz684rw.js.map} +1 -1
  57. package/dist/{chunk-236be97q.js → chunk-63xwah5k.js} +1 -1
  58. package/dist/{chunk-b4jx4fzq.js → chunk-65wy1r1a.js} +1 -1
  59. package/dist/{chunk-9tgcmx4h.js → chunk-70yz9e7f.js} +2 -2
  60. package/dist/{chunk-9tgcmx4h.js.map → chunk-70yz9e7f.js.map} +1 -1
  61. package/dist/{chunk-t03nda3s.js → chunk-73rzf7ys.js} +2 -2
  62. package/dist/{chunk-t03nda3s.js.map → chunk-73rzf7ys.js.map} +1 -1
  63. package/dist/{chunk-1cn7ets3.js → chunk-7txqv2qq.js} +3 -3
  64. package/dist/{chunk-1cn7ets3.js.map → chunk-7txqv2qq.js.map} +1 -1
  65. package/dist/{chunk-1skdsmjx.js → chunk-86zhngpg.js} +2 -2
  66. package/dist/{chunk-1skdsmjx.js.map → chunk-86zhngpg.js.map} +1 -1
  67. package/dist/{chunk-ce9wm3r9.js → chunk-877yc341.js} +3 -3
  68. package/dist/{chunk-ce9wm3r9.js.map → chunk-877yc341.js.map} +1 -1
  69. package/dist/{chunk-wffc5k3m.js → chunk-87y2nrjy.js} +2 -2
  70. package/dist/{chunk-wffc5k3m.js.map → chunk-87y2nrjy.js.map} +1 -1
  71. package/dist/{chunk-9zd7c4wq.js → chunk-8k346pjw.js} +14 -14
  72. package/dist/{chunk-9zd7c4wq.js.map → chunk-8k346pjw.js.map} +3 -3
  73. package/dist/{chunk-27xsjq8a.js → chunk-8km4drvv.js} +3 -3
  74. package/dist/{chunk-27xsjq8a.js.map → chunk-8km4drvv.js.map} +1 -1
  75. package/dist/{chunk-sa6a0wy1.js → chunk-94hcjdbe.js} +2 -2
  76. package/dist/{chunk-sa6a0wy1.js.map → chunk-94hcjdbe.js.map} +1 -1
  77. package/dist/{chunk-kaphqnpp.js → chunk-9z8zq4rx.js} +3 -3
  78. package/dist/{chunk-kaphqnpp.js.map → chunk-9z8zq4rx.js.map} +1 -1
  79. package/dist/{chunk-8ex0y47w.js → chunk-apga49vp.js} +2 -2
  80. package/dist/{chunk-8ex0y47w.js.map → chunk-apga49vp.js.map} +1 -1
  81. package/dist/{chunk-yjszzjyj.js → chunk-attr793y.js} +2 -2
  82. package/dist/{chunk-yjszzjyj.js.map → chunk-attr793y.js.map} +1 -1
  83. package/dist/{chunk-1x9ghjpt.js → chunk-bsa6b82q.js} +1 -1
  84. package/dist/{chunk-ceb4jcrm.js → chunk-bstn00nx.js} +2 -2
  85. package/dist/{chunk-ceb4jcrm.js.map → chunk-bstn00nx.js.map} +1 -1
  86. package/dist/{chunk-azd6da5h.js → chunk-bykkqvd8.js} +2 -2
  87. package/dist/{chunk-azd6da5h.js.map → chunk-bykkqvd8.js.map} +1 -1
  88. package/dist/{chunk-9k46m1vf.js → chunk-cee5gq7t.js} +2 -2
  89. package/dist/{chunk-9k46m1vf.js.map → chunk-cee5gq7t.js.map} +1 -1
  90. package/dist/{chunk-9dkpv8ev.js → chunk-dxh8njb4.js} +2 -2
  91. package/dist/{chunk-9dkpv8ev.js.map → chunk-dxh8njb4.js.map} +1 -1
  92. package/dist/{chunk-maqkrbsb.js → chunk-e06t0625.js} +2 -2
  93. package/dist/{chunk-maqkrbsb.js.map → chunk-e06t0625.js.map} +1 -1
  94. package/dist/{chunk-0839f72f.js → chunk-e9z8p2fy.js} +2 -2
  95. package/dist/{chunk-0839f72f.js.map → chunk-e9z8p2fy.js.map} +1 -1
  96. package/dist/{chunk-6hs102jh.js → chunk-eqv7yxk7.js} +2 -2
  97. package/dist/{chunk-6hs102jh.js.map → chunk-eqv7yxk7.js.map} +1 -1
  98. package/dist/{chunk-m6t5a0me.js → chunk-fqqbnp0z.js} +2 -2
  99. package/dist/{chunk-m6t5a0me.js.map → chunk-fqqbnp0z.js.map} +1 -1
  100. package/dist/{chunk-1w5dnkd1.js → chunk-g22kph4n.js} +2 -2
  101. package/dist/{chunk-1w5dnkd1.js.map → chunk-g22kph4n.js.map} +1 -1
  102. package/dist/{chunk-rvm5mkwm.js → chunk-g8sh9btf.js} +2 -2
  103. package/dist/{chunk-rvm5mkwm.js.map → chunk-g8sh9btf.js.map} +1 -1
  104. package/dist/{chunk-a78b9v7h.js → chunk-gvdg52ew.js} +4 -4
  105. package/dist/{chunk-a78b9v7h.js.map → chunk-gvdg52ew.js.map} +1 -1
  106. package/dist/{chunk-8ky8cmde.js → chunk-h8eawyhx.js} +2 -2
  107. package/dist/{chunk-8ky8cmde.js.map → chunk-h8eawyhx.js.map} +1 -1
  108. package/dist/{chunk-r567t83k.js → chunk-hcw671mg.js} +4 -4
  109. package/dist/{chunk-r567t83k.js.map → chunk-hcw671mg.js.map} +1 -1
  110. package/dist/{chunk-ej4kf7m5.js → chunk-hh5bs656.js} +3 -3
  111. package/dist/{chunk-ej4kf7m5.js.map → chunk-hh5bs656.js.map} +1 -1
  112. package/dist/{chunk-3q7sc68p.js → chunk-j6ygdvj8.js} +2 -2
  113. package/dist/{chunk-3q7sc68p.js.map → chunk-j6ygdvj8.js.map} +1 -1
  114. package/dist/{chunk-t2nsn0r2.js → chunk-jzpbwvbt.js} +2 -2
  115. package/dist/{chunk-t2nsn0r2.js.map → chunk-jzpbwvbt.js.map} +1 -1
  116. package/dist/{chunk-en33hg1c.js → chunk-k79ajvtc.js} +2 -2
  117. package/dist/{chunk-en33hg1c.js.map → chunk-k79ajvtc.js.map} +1 -1
  118. package/dist/{chunk-t0wfj6hy.js → chunk-k8pn2qvf.js} +2 -2
  119. package/dist/{chunk-t0wfj6hy.js.map → chunk-k8pn2qvf.js.map} +1 -1
  120. package/dist/{chunk-83cvkhzn.js → chunk-kmh402m4.js} +2 -2
  121. package/dist/{chunk-83cvkhzn.js.map → chunk-kmh402m4.js.map} +1 -1
  122. package/dist/{chunk-b4mg6v4g.js → chunk-m9am5fqq.js} +5 -5
  123. package/dist/{chunk-b4mg6v4g.js.map → chunk-m9am5fqq.js.map} +3 -3
  124. package/dist/{chunk-m8yd59gg.js → chunk-mr3szvr3.js} +2 -2
  125. package/dist/{chunk-m8yd59gg.js.map → chunk-mr3szvr3.js.map} +1 -1
  126. package/dist/{chunk-mkw35cz7.js → chunk-mtamgvf4.js} +2 -2
  127. package/dist/{chunk-mkw35cz7.js.map → chunk-mtamgvf4.js.map} +1 -1
  128. package/dist/{chunk-5xfpqda5.js → chunk-mv1rs9he.js} +1 -1
  129. package/dist/{chunk-s29tgy4y.js → chunk-mzkzgp2j.js} +2 -2
  130. package/dist/{chunk-s29tgy4y.js.map → chunk-mzkzgp2j.js.map} +1 -1
  131. package/dist/{chunk-9xzg05xg.js → chunk-n9n4qt20.js} +3 -3
  132. package/dist/{chunk-9xzg05xg.js.map → chunk-n9n4qt20.js.map} +1 -1
  133. package/dist/{chunk-2ra5skyk.js → chunk-p27y4xrw.js} +2 -2
  134. package/dist/{chunk-2ra5skyk.js.map → chunk-p27y4xrw.js.map} +1 -1
  135. package/dist/{chunk-sgwgj2q0.js → chunk-pq657qcp.js} +1 -1
  136. package/dist/{chunk-63q7ycwt.js → chunk-pwbm3x1y.js} +2 -2
  137. package/dist/{chunk-63q7ycwt.js.map → chunk-pwbm3x1y.js.map} +1 -1
  138. package/dist/{chunk-w4ma7978.js → chunk-q4qw629n.js} +2 -2
  139. package/dist/{chunk-w4ma7978.js.map → chunk-q4qw629n.js.map} +1 -1
  140. package/dist/{chunk-f2e7n064.js → chunk-q9na1syb.js} +2 -2
  141. package/dist/{chunk-f2e7n064.js.map → chunk-q9na1syb.js.map} +1 -1
  142. package/dist/{chunk-x0t3t7g3.js → chunk-rkbwb3v5.js} +2 -2
  143. package/dist/{chunk-x0t3t7g3.js.map → chunk-rkbwb3v5.js.map} +1 -1
  144. package/dist/{chunk-0t2ym9ap.js → chunk-rma7afjd.js} +3 -3
  145. package/dist/{chunk-0t2ym9ap.js.map → chunk-rma7afjd.js.map} +1 -1
  146. package/dist/{chunk-f5qdyw45.js → chunk-tr9ynv3w.js} +2 -2
  147. package/dist/{chunk-f5qdyw45.js.map → chunk-tr9ynv3w.js.map} +1 -1
  148. package/dist/{chunk-kzc6bn8n.js → chunk-twrf6d08.js} +2 -2
  149. package/dist/{chunk-kzc6bn8n.js.map → chunk-twrf6d08.js.map} +1 -1
  150. package/dist/{chunk-6jd0e1dz.js → chunk-v9z4x5j2.js} +2 -2
  151. package/dist/{chunk-6jd0e1dz.js.map → chunk-v9z4x5j2.js.map} +1 -1
  152. package/dist/{chunk-jmhrpfqn.js → chunk-vm5t0j24.js} +2 -2
  153. package/dist/{chunk-jmhrpfqn.js.map → chunk-vm5t0j24.js.map} +1 -1
  154. package/dist/{chunk-a37shxb1.js → chunk-xv58jnpb.js} +2 -2
  155. package/dist/{chunk-a37shxb1.js.map → chunk-xv58jnpb.js.map} +1 -1
  156. package/dist/{chunk-p57nt0pm.js → chunk-ydkv9e8w.js} +3 -3
  157. package/dist/{chunk-p57nt0pm.js.map → chunk-ydkv9e8w.js.map} +1 -1
  158. package/dist/{chunk-aw8gj99f.js → chunk-ymdpt00k.js} +2 -2
  159. package/dist/{chunk-aw8gj99f.js.map → chunk-ymdpt00k.js.map} +1 -1
  160. package/dist/{chunk-5g7m7g4a.js → chunk-z7tsh9qr.js} +3 -3
  161. package/dist/{chunk-5g7m7g4a.js.map → chunk-z7tsh9qr.js.map} +1 -1
  162. package/dist/config/index.js +1 -1
  163. package/dist/console/run.js +2 -2
  164. package/dist/console/run.js.map +1 -1
  165. package/dist/container/index.js +2 -2
  166. package/dist/container/index.js.map +1 -1
  167. package/dist/database/index.js +2 -2
  168. package/dist/database/index.js.map +1 -1
  169. package/dist/email/index.js +2 -2
  170. package/dist/email/index.js.map +1 -1
  171. package/dist/facades/index.js +2 -2
  172. package/dist/facades/index.js.map +1 -1
  173. package/dist/foundation/index.js +2 -2
  174. package/dist/foundation/index.js.map +1 -1
  175. package/dist/http/index.js +2 -2
  176. package/dist/http/index.js.map +1 -1
  177. package/dist/i18n/dictionaryRuntime.js +2 -2
  178. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  179. package/dist/i18n/index.js +2 -2
  180. package/dist/i18n/index.js.map +1 -1
  181. package/dist/kernel/index.js +2 -2
  182. package/dist/kernel/index.js.map +1 -1
  183. package/dist/orm/index.js +2 -2
  184. package/dist/orm/index.js.map +1 -1
  185. package/dist/server/index.js +2 -2
  186. package/dist/server/index.js.map +1 -1
  187. package/dist/services/index.d.ts +2 -1
  188. package/dist/services/index.d.ts.map +1 -1
  189. package/dist/services/index.js +9 -9
  190. package/dist/services/index.js.map +4 -3
  191. package/dist/services/mcp/http/McpHttpServer.d.ts +81 -1
  192. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
  193. package/dist/services/mcp/http/oauth/prismaStore.d.ts +112 -0
  194. package/dist/services/mcp/http/oauth/prismaStore.d.ts.map +1 -0
  195. package/dist/services/queue/work.js +2 -2
  196. package/dist/services/queue/work.js.map +1 -1
  197. package/dist/stats/route-table.js +1 -1
  198. package/dist/support/index.js +2 -2
  199. package/dist/support/index.js.map +1 -1
  200. package/dist/vitest/index.js +1 -1
  201. package/package.json +1 -1
  202. package/dist/chunk-b6mgrrk6.js +0 -5
  203. /package/dist/{chunk-fsem81ec.js.map → chunk-29jmaj16.js.map} +0 -0
  204. /package/dist/{chunk-236be97q.js.map → chunk-63xwah5k.js.map} +0 -0
  205. /package/dist/{chunk-b4jx4fzq.js.map → chunk-65wy1r1a.js.map} +0 -0
  206. /package/dist/{chunk-1x9ghjpt.js.map → chunk-bsa6b82q.js.map} +0 -0
  207. /package/dist/{chunk-5xfpqda5.js.map → chunk-mv1rs9he.js.map} +0 -0
  208. /package/dist/{chunk-sgwgj2q0.js.map → chunk-pq657qcp.js.map} +0 -0
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- import{$b as M9,Jc as F9,Xb as k9,_b as K3,dc as e,ld as N9,qc as U9,wc as J9}from"./chunk-9zd7c4wq.js";import{Bd as L$,sd as c3,ud as B3,xd as d9,yd as c9,zd as V$}from"./chunk-fpz9e3xx.js";import{Ed as w9,Jd as v9,Ld as g9,Sd as x,Td as h9,Ud as m9,Wd as u9,Xd as B$}from"./chunk-ce9wm3r9.js";import{_d as N}from"./chunk-6hs102jh.js";import{Ag as L3,Bg as d3,Cf as Y$,Df as G$,Ef as W$,Fe as H$,Ge as p3,Gf as w,Gg as X$,Hg as K$,Ke as J3,Le as X3,Ng as D$,Tf as a3,cg as s3,df as m3,eg as n,ig as o3,jg as t9,ke as l,kg as s9,le as z$,oe as T9,qg as f3,rf as Z3,rg as o9,se as O$,sg as G3,tg as r9,ug as e9,ve as Q$,vg as w3,wg as a,xf as H3,yf as h3,zf as q,zg as A$}from"./chunk-a78b9v7h.js";import{Ai as F3,Bi as z3,Sh as p,Uh as m,hi as t3,vi as H9,zi as P3}from"./chunk-27xsjq8a.js";import{Hi as i9}from"./chunk-9k46m1vf.js";import{Si as g}from"./chunk-fg2k18d2.js";import{Yi as u3}from"./chunk-ktrm6y5j.js";import{$i as U$,aj as i3,dj as N3,ej as n3,hj as F$}from"./chunk-9xzg05xg.js";import{Aj as n9,vj as l9}from"./chunk-a37shxb1.js";import{Qj as f9,Sj as u}from"./chunk-1skdsmjx.js";import{Tj as j}from"./chunk-yjszzjyj.js";import{Zj as I$}from"./chunk-p81qeav5.js";import{Nk as l3}from"./chunk-5g7m7g4a.js";import{Uk as U3,Xk as y}from"./chunk-1ed75a7b.js";import{el as g3}from"./chunk-s29tgy4y.js";import{pl as a9}from"./chunk-m6t5a0me.js";var C$="mcp",S$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class D extends e{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class v extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var r3=/^[A-Za-z0-9_-]{1,64}$/,q$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,e3=4000,T=1e5,T$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,B9=new WeakMap;function X6($){return B9.get($)}class i{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=b$(z.files),this.featureOn=z.featureOn??X3;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,k$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D3($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(W9(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(W9(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={}){D3($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new v(`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 v(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!W3(X))throw new v(`"${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 V=Q.value,H={caller:$,req:$.req,tool:K,input:V,ctx:G},U=await this.fillPath(Y,H),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${U}`));if(F!==K.url)throw new D(`"${Z}" has nothing at ${U}.`,404);let O={};for(let L of Y.jsonKeys)if(V[L]!==void 0)O[L]=V[L];let B,I="";if(Y.fileFields.length>0)B=await this.formData(Y,O,H);else if(K.method==="GET")I=c$(O);else if(Y.jsonKeys.length>0)B=O;let k=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(H)):void 0,A={...k?{credentials:k}:{},...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}:{}}}}:{}},M;try{let L=I?`${U}?${I}`:U;M=Object.keys(A).length>0?await this.dispatcher.dispatchAs($.req,K.method,L,B,A):await this.dispatcher.dispatchAs($.req,K.method,L,B)}catch(L){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,L),new D(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await V9(Z,M);return await this.project(Y,H,M)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!r3.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(q$)].map(([,J,C])=>({name:J,modifier:C})),Q=X.params??{};for(let J of K)if(!(J.name in Q))throw Error(`${z}: the path param "${J.name}" must be bound or declared "input".`);for(let[J,C]of Object.entries(Q)){if(!K.some((h)=>h.name===J))throw Error(`${z}: "${J}" in params is not a param of the url.`);if(Y9(C))g$(z,`params.${J}`,C);else X9(z,`params.${J}`,C)}let V=[],H;if(X.input){if(H=X.input.toJSONSchema(),H.type!=="object"||!H.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);V=Object.keys(H.properties)}let U=Object.entries(X.files??{}).map(([J,C])=>({name:J,binder:C}));for(let J of U)X9(z,`files.${J.name}`,J.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 F=K9(z,G,X.annotations);if(U.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let O={},B=(J,C)=>{if(J in O)throw Error(`${z}: "${J}" is the input key of two params or files, and the model can only send one.`);O[J]=C},I=new Map,k=new Map;for(let J of K){let C=Q[J.name];if(C==="input"){let h=p.string().describe(`The ":${J.name}" segment of the url.`);B(J.name,J.modifier==="?"||J.modifier==="*"?h.optional():h)}else if(Y9(C)){let h=C.as??J.name;B(h,C.input),k.set(J.name,{key:h,param:C})}else I.set(J.name,C)}let A={};for(let J of U)if(J.binder==="input")B(J.name,p.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),A[J.name]=this.remoteFileSchema();let M=[...Object.keys(O),...U.map((J)=>J.name)];for(let J of new Set(M))if(V.includes(J))throw Error(`${z}: "${J}" is both an input field and a param or file, and the model can only send one.`);let L=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:Q9(X.input,H,p.object(O)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),r=!U.every((J)=>J.binder==="input")?null:U.length===0?L:Object.freeze({...L,inputSchema:Q9(X.input,H,p.object(u$(O,Object.keys(A))),A)});return{kind:"route",descriptor:L,remote:r,params:K,paramBinders:I,modelParams:k,fileFields:U,jsonKeys:V,...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 V of Object.keys(Y))if(!W.includes(V))K.push(`a file has no field "${V}"`);for(let V of W){let H=Y[V];if(H===void 0||H===null){if(V==="name"||V==="mimeType")K.push(`a file needs "${V}"`);continue}if(typeof H!=="string")K.push(`a file's "${V}" must be a string`);else Q[V]=H}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(!r3.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:K9(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(!W3(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 V=G.signal??new AbortController().signal;return G9(X,Y.value,z9(Z9(X,Q,V)))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return W3(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(D3($),$.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 B9.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=(L,_3)=>{if(!W.progress)return;let r;try{r=$.meta.remote?.progress?$.meta.remote.progress(L,_3):R$(L,_3)}catch(J){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,J);return}if(r)W.progress(r)};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 $9(this.runNative($,{...K,ctx:G},G),Q)}let V=$.meta.remote,H=await this.bind($,"the remote context",()=>V.context(K));if(typeof H!=="object"||H===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,H),new D(`"${X}" failed on the server.`,500);let U=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...U!==void 0?[AbortSignal.timeout(U)]:[]],O=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),B=Z9($,H,O);if(!W.approved&&W3($)&&await G9($,K.input,z9(B)))throw new v(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let I;try{I=await $9(this.runNative($,{...K,ctx:B},B),Q,O)}catch(L){if(O.aborted&&L===O.reason){if(W.signal?.aborted)throw new D(`"${X}" was cancelled.`,499);throw new D(`"${X}" did not finish within ${U} ms.`,504)}if(L instanceof D)throw L;if(L instanceof e||L instanceof v)throw new D(L.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,L),new D(`"${X}" failed on the server.`,500)}let k=(L)=>{return console.error(`[gemi/mcp] "${X}" ${L}`),new D(`"${X}" failed on the server.`,500)};if(U9(I))throw k("answered a job handle, and a remote call has no background jobs.");let A=I;if($.descriptor.outputSchema){let L=$.descriptor.outputSchema.safeParse(A);if(L.ok===!1)throw k(`answered what its output schema refuses: ${L.errors.join(", ")}`);A=L.value}if(A===void 0)return null;if(typeof A==="string")return A.length>T?`${A.slice(0,T)}\u2026 [cut at ${T} of ${A.length} characters]`:A;let M=JSON.stringify(A);if(M!==void 0&&M.length>T)return`${M.slice(0,T)}\u2026 [cut at ${T} of ${M.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 V=`:${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(`/${V}`,"");continue}W=W.replace(V,d$($.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,V]of Object.entries(Z))O3(K,Q,V);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))O3(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=(H)=>new D(`"${Z}" of "${$}" ${H}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!y$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!f$.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 H=W.data.replace(/\s+/g,"");if(Math.floor(H.length*3/4)-v$(H)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(H.length%4!==0||!w$.test(H))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(H,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let V;try{V=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(V.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let H=await H9(V.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!H.ok)throw G(`could not be fetched: ${V.host} answered ${H.status}.`);let U=await H.arrayBuffer();return new File([U],W.name,{type:W.mimeType})}catch(H){if(H instanceof D)throw H;throw G(`could not be fetched from ${V.host}: ${H instanceof Error?H.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(C$,{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(!S$.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 V9(G,z);let X=(U,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${U}`);else console.error(`[gemi/mcp] "${G}" ${U}`,F);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 V=Q;if($.result)try{V=await $.result(Q,Z)}catch(U){throw X("failed in its result projection:",U)}if(W){let U=W.safeParse(V);if(U.ok===!1)throw X(`answered what its output schema refuses: ${U.errors.join(", ")}`);V=U.value}if(V===void 0)return null;let H=JSON.stringify(V);if(H!==void 0&&H.length>T)return`${H.slice(0,T)}\u2026 [cut at ${T} of ${H.length} characters]`;return V}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof e)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new D(`"${$.descriptor.name}" failed on the server.`,500)}}}function k$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function M$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function $9($,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(!M$($))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 R$($,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 Z9($,Z,z){let G=$.descriptor.name,W=`mcp_${crypto.randomUUID()}`,X=`mcp_call_${crypto.randomUUID()}`,Y=(Q)=>async()=>{throw new e(`"${G}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},K={put:Y("attachment store"),get:Y("attachment store"),read:Y("attachment store"),file:Y("attachment store")};return{context:Z,body:{},runId:W,toolCallId:X,signal:z,step:1,depth:0,resumed:!1,attachments:K,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:Y("agent run to nest a sub-agent in"),generateImage:Y("attachment store to put an image in"),editImage:Y("attachment store to put an image in"),generate:(Q)=>N9({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:G,runId:W,toolCallId:X}}),jobs:J9({jobs:void 0,threadId:void 0,runId:W,toolCallId:X,toolName:G,depth:0,async:$.tool.async,attachments:null}),memory:F9()}}function W3($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function z9($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function G9($,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 D3($){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 W9($,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 E$=10485760;function b$($){let Z=$?.maxBytes??E$;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 y$($){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 f$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,w$=/^[A-Za-z0-9+/]*={0,2}$/;function v$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function X9($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Y9($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function g$($,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 h$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function m$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function K9($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?m$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!h$.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 Q9($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,V])=>[Q,V.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 V=[],H={};if($){let F=$.safeParse(Q);if(F.ok===!1)V.push(...F.errors);else H={...F.value}}let U=z.safeParse(Q);if(U.ok===!1)V.push(...U.errors);else H={...H,...U.value};for(let[F,O]of Object.entries(G)){let B=Q[F];if(B===void 0){V.push(`"${F}" is required`);continue}let I=O.safeParse(B);if(I.ok===!1)V.push(...I.errors.map((k)=>`${F}: ${k}`));else H[F]=I.value}return V.length>0?{ok:!1,errors:V}:{ok:!0,value:H}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let V=K(Q);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function u$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function d$($,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 O3($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O3($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function c$($){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 V9($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!T$.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>T)return`${W.slice(0,T)}\u2026 [cut at ${T} 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>e3?`${z.slice(0,e3)}\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 p$,randomBytes as i$,timingSafeEqual as l$}from"crypto";function j3($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class n${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`${$}${i$(32).toString("base64url")}`}static hash($){return p$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&l$(z,G)}async resolve($){let Z=j3($);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 R9,randomBytes as _9}from"crypto";async function x3($,Z){let z=t$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function t$(){try{let $=y();return $.bound(l)?$.make(l):null}catch{return null}}var A3=["2026-07-28"],Y3=["2025-11-25","2025-06-18","2025-03-26"],C3=[...A3,...Y3],S3="io.modelcontextprotocol/protocolVersion",q3="io.modelcontextprotocol/clientCapabilities";var T3="io.modelcontextprotocol/serverInfo",_={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class P extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function R($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function P9($){if(Array.isArray($))throw new P(_.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new P(_.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 P(_.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new P(_.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 P(_.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function k3($,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 S($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function I9($){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 s$,timingSafeEqual as o$}from"crypto";function M3($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${L9($,Z,G).toString("base64url")}`}function R3($,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=L9($,Z,X);if(K.length!==Q.length||!o$(K,Q))return null;let V;try{V=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof V!=="object"||V===null)return null;if(typeof V.exp!=="number"||V.exp<=G)return null;return V}function L9($,Z,z){return s$("sha256",K3($)).update(`${Z}.${z}`).digest()}var E3="gemi.mcp.request-state.v1",D9="gemi.mcp.session.v1",a$=86400000,O9=600000,j9="gemi_approval",b3=2000,r$={limit:600,window:60},e$={limit:30,window:60};class $3{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;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=z2(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().");if(this.resolvers=G,K3(E3),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.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??r$,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 k9,this.approvalTimeoutMs=Z.approvalTimeoutMs??O9,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??X3;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(Z.host!==this.endpoint.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 f(R(null,new P(_.InvalidRequest,"Origin not allowed.")),403);let G=z?Z2(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 x9(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return x9(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(j3($)!==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 $2($,this.maxBodyBytes))}catch(Y){if(Y instanceof V3)return f(R(null,new P(_.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return f(R(null,new P(_.ParseError,"Parse error.")),400)}let X=new m($,{},"api",this.endpoint.pathname);return await g.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof P){let K=S(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return f(R(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),f(R(null,new P(_.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=P9(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let B=this.session($,z),I=this.pending.get(String(W.message.id));if(I&&I.session===B.id)this.pending.delete(String(W.message.id)),I.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=S(K._meta)?K._meta:{};if(typeof Q[S3]==="string"){if(this.checkModernHeaders($,Y,Q[S3]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(B,I)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:B,signal:I}),C9(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new P(_.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let V=this.session($,z),H=$.headers.get("mcp-protocol-version");if(H!==null&&H!==V.state.v)throw new P(_.InvalidRequest,`MCP-Protocol-Version ${H} is not the session's ${V.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let B=K.requestId;this.inflight.get(`${V.id}:${String(B)}`)?.abort()}return new Response(null,{status:202})}let U=`${V.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(U,F);let O=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(B,I)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:V.state,sessionId:V.id},stream:B,signal:I}),C9(K)||W2(this.registry,Y,V.state),O,()=>this.inflight.delete(U))}catch(B){throw this.inflight.delete(U),B}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C3,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)=>k3(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new P(_.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)=>k3(Z,!1))};case"tools/call":return await this.callTool($);default:throw new P(_.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T3]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Y3.includes(G)?G:Y3[0],X=S(Z.capabilities)?Z.capabilities:{},Y={v:W,e:A9(X.elicitation),p:Q3(z),exp:Date.now()+a$},K=M3(D9,"gms1",Y);return f({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 P(_.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R3(D9,"gms1",z);if(!G||G.p!==Q3(Z))throw new P(_.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A3.includes(z))throw new P(_.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C3,requested:z},400);let G=(Y)=>new P(_.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||I9(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let{params:Z,caller:z,principal:G}=$,W=Z.name;if(typeof W!=="string")throw new P(_.InvalidParams,"tools/call needs a tool name.");let X=Z.arguments??{},Y=(await this.registry.available(z,{names:[W]}))[0];if(!Y)throw new P(_.InvalidParams,`Unknown tool: ${W}`);let K=!1;if(Y.requiresApproval){let F=Y.inputSchema.safeParse(X);if(F.ok===!1)return this.toolResult($,{content:[{type:"text",text:`Invalid arguments for "${W}": ${F.errors.join(", ")}`}],isError:!0});if($.era.modern&&S($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(z,W,X,{signal:$.signal})){let B=await this.approval($,Y,X);if(B.kind==="answer")return B.result;K=!0}}let Q=X2($),V;try{V=await this.registry.execute(z,W,X,void 0,{approved:K,signal:$.signal,...Q?{progress:Q}:{}})}catch(F){if(F instanceof D)return this.toolResult($,{content:[{type:"text",text:F.message}],isError:!0});if(F instanceof v)throw new P(_.InvalidParams,F.reason==="unknown-tool"?`Unknown tool: ${W}`:F.message);return console.error(`[gemi/mcp] "${W}" failed for ${G.via}:${G.id}:`,F),this.toolResult($,{content:[{type:"text",text:`"${W}" failed on the server.`}],isError:!0})}let H=typeof V==="string"?V:JSON.stringify(V??null),U=Y.outputSchema&&($.era.modern||S(V))?{structuredContent:V}:{};return this.toolResult($,{content:[{type:"text",text:H}],...U,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z){let G=Y2(Z,z),W=(V)=>({kind:"answer",result:this.toolResult($,{content:[{type:"text",text:V}],isError:!0})});if($.era.modern){let V=S($.params._meta)?$.params._meta:{},H=S(V[q3])?V[q3]:{},U=S($.params.inputResponses)?$.params.inputResponses:null,F=$.params.requestState,O=G2(z);if(U&&F!==void 0){let I=R3(E3,"grs1",F);if(!I||I.p!==Q3($.principal)||I.t!==Z.name||I.a!==O)throw new P(_.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(I.n,I.exp))throw new P(_.InvalidParams,"requestState has already been used.");return S9(U[j9])?{kind:"approved"}:W(`The user did not approve "${Z.name}", and it did not run.`)}if(!A9(H.elicitation))throw new P(_.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let B={p:Q3($.principal),t:Z.name,a:O,n:_9(16).toString("base64url"),exp:Date.now()+O9};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[j9]:{method:"elicitation/create",params:{mode:"form",...G}}},requestState:M3(E3,"grs1",B),_meta:{[T3]:this.serverInfo}}}}let X=$.era;if(!X.session.e||!$.stream)return W(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${_9(12).toString("base64url")}`,K=X.sessionId,Q=await new Promise((V)=>{let H=setTimeout(()=>{this.pending.delete(Y),V(null)},this.approvalTimeoutMs),U=(F)=>{clearTimeout(H),V(F)};this.pending.set(Y,{session:K,resolve:U}),$.signal.addEventListener("abort",()=>{this.pending.delete(Y),U(null)}),$.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...G}:G})});return Q&&!Q.error&&S9(Q.result)?{kind:"approved"}:W(`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 f({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new E9(()=>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 P)K.send(R($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(R($.id,new P(_.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 f(R(null,new P(_.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=T9(new m($,{},"api",this.endpoint.pathname)),z=await x3(`mcp-auth-failed:${Z}`,e$);return z===null?null:q9(z)}async spend($){if(!this.rateLimit)return null;let Z=await x3(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:q9(Z)}}class E9{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{$b as K3,Kc as F9,Xb as k9,ac as M9,ec as e,md as N9,rc as U9,xc as J9}from"./chunk-8k346pjw.js";import{Ad as V$,Cd as L$,td as p3,vd as B3,yd as d9,zd as p9}from"./chunk-2b3hh9xw.js";import{Fd as w9,Kd as v9,Md as h9,Td as x,Ud as g9,Vd as m9,Xd as u9,Yd as B$}from"./chunk-877yc341.js";import{$d as P}from"./chunk-eqv7yxk7.js";import{Af as k,Ag as x$,Bg as L3,Cg as d3,Df as Y$,Ef as G$,Ff as W$,Ge as H$,He as c3,Hf as w,Hg as X$,Ig as K$,Le as J3,Me as X3,Og as D$,Uf as a3,dg as t3,ef as m3,fg as n,jg as o3,kg as s9,le as l,lg as t9,me as z$,pe as T9,rg as f3,sf as Z3,sg as o9,te as O$,tg as G3,ug as r9,vg as e9,we as Q$,wg as w3,xg as a,yf as H3,zf as g3}from"./chunk-gvdg52ew.js";import{Ai as P3,Bi as F3,Ci as z3,Th as c,Vh as m,ii as s3,wi as H9}from"./chunk-8km4drvv.js";import{Ii as i9}from"./chunk-cee5gq7t.js";import{Ti as h}from"./chunk-0k8fk96c.js";import{Zi as u3}from"./chunk-563ksar3.js";import{aj as U$,bj as i3,ej as N3,fj as n3,ij as F$}from"./chunk-n9n4qt20.js";import{Bj as n9,wj as l9}from"./chunk-xv58jnpb.js";import{Rj as f9,Tj as u}from"./chunk-86zhngpg.js";import{Uj as A}from"./chunk-attr793y.js";import{_j as I$}from"./chunk-2ery6a75.js";import{Ok as l3}from"./chunk-z7tsh9qr.js";import{Vk as U3,Yk as y}from"./chunk-1fyn63ka.js";import{fl as h3}from"./chunk-mzkzgp2j.js";import{ql as a9}from"./chunk-fqqbnp0z.js";var C$="mcp",S$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends e{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class v extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var r3=/^[A-Za-z0-9_-]{1,64}$/,q$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,e3=4000,M=1e5,T$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,B9=new WeakMap;function X6($){return B9.get($)}class i{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=b$(z.files),this.featureOn=z.featureOn??X3;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,k$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D3($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(W9(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(W9(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={}){D3($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new v(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new v(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!W3(X))throw new v(`"${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 O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let V=Q.value,H={caller:$,req:$.req,tool:K,input:V,ctx:G},J=await this.fillPath(Y,H),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${J}`));if(I!==K.url)throw new O(`"${Z}" has nothing at ${J}.`,404);let U={};for(let _ of Y.jsonKeys)if(V[_]!==void 0)U[_]=V[_];let F,B="";if(Y.fileFields.length>0)F=await this.formData(Y,U,H);else if(K.method==="GET")B=p$(U);else if(Y.jsonKeys.length>0)F=U;let T=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(H)):void 0,j={...T?{credentials:T}:{},...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}:{}}}}:{}},C;try{let _=B?`${J}?${B}`:J;C=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,_,F,j):await this.dispatcher.dispatchAs($.req,K.method,_,F)}catch(_){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,_),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await V9(Z,C);return await this.project(Y,H,C)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!r3.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(q$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((g)=>g.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(Y9(S))h$(z,`params.${N}`,S);else X9(z,`params.${N}`,S)}let V=[],H;if(X.input){if(H=X.input.toJSONSchema(),H.type!=="object"||!H.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);V=Object.keys(H.properties)}let J=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of J)X9(z,`files.${N.name}`,N.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 I=K9(z,G,X.annotations);if(J.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let U={},F=(N,S)=>{if(N in U)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);U[N]=S},B=new Map,T=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let g=c.string().describe(`The ":${N.name}" segment of the url.`);F(N.name,N.modifier==="?"||N.modifier==="*"?g.optional():g)}else if(Y9(S)){let g=S.as??N.name;F(g,S.input),T.set(N.name,{key:g,param:S})}else B.set(N.name,S)}let j={};for(let N of J)if(N.binder==="input")F(N.name,c.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let C=[...Object.keys(U),...J.map((N)=>N.name)];for(let N of new Set(C))if(V.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let _=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:Q9(X.input,H,c.object(U)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),r=!J.every((N)=>N.binder==="input")?null:J.length===0?_:Object.freeze({..._,inputSchema:Q9(X.input,H,c.object(u$(U,Object.keys(j))),j)});return{kind:"route",descriptor:_,remote:r,params:K,paramBinders:B,modelParams:T,fileFields:J,jsonKeys:V,...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 V of Object.keys(Y))if(!W.includes(V))K.push(`a file has no field "${V}"`);for(let V of W){let H=Y[V];if(H===void 0||H===null){if(V==="name"||V==="mimeType")K.push(`a file needs "${V}"`);continue}if(typeof H!=="string")K.push(`a file's "${V}" must be a string`);else Q[V]=H}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(!r3.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:K9(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(!W3(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 V=G.signal??new AbortController().signal;return G9(X,Y.value,z9(Z9(X,Q,V)))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return W3(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(D3($),$.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 O(`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 B9.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 O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(_,_3)=>{if(!W.progress)return;let r;try{r=$.meta.remote?.progress?$.meta.remote.progress(_,_3):R$(_,_3)}catch(N){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,N);return}if(r)W.progress(r)};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 $9(this.runNative($,{...K,ctx:G},G),Q)}let V=$.meta.remote,H=await this.bind($,"the remote context",()=>V.context(K));if(typeof H!=="object"||H===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,H),new O(`"${X}" failed on the server.`,500);let J=$.tool.timeoutMs,I=[...W.signal?[W.signal]:[],...J!==void 0?[AbortSignal.timeout(J)]:[]],U=I.length===0?new AbortController().signal:I.length===1?I[0]:AbortSignal.any(I),F=Z9($,H,U);if(!W.approved&&W3($)&&await G9($,K.input,z9(F)))throw new v(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let B;try{B=await $9(this.runNative($,{...K,ctx:F},F),Q,U)}catch(_){if(U.aborted&&_===U.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${J} ms.`,504)}if(_ instanceof O)throw _;if(_ instanceof e||_ instanceof v)throw new O(_.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,_),new O(`"${X}" failed on the server.`,500)}let T=(_)=>{return console.error(`[gemi/mcp] "${X}" ${_}`),new O(`"${X}" failed on the server.`,500)};if(U9(B))throw T("answered a job handle, and a remote call has no background jobs.");let j=B;if($.descriptor.outputSchema){let _=$.descriptor.outputSchema.safeParse(j);if(_.ok===!1)throw T(`answered what its output schema refuses: ${_.errors.join(", ")}`);j=_.value}if(j===void 0)return null;if(typeof j==="string")return j.length>M?`${j.slice(0,M)}\u2026 [cut at ${M} of ${j.length} characters]`:j;let C=JSON.stringify(j);if(C!==void 0&&C.length>M)return`${C.slice(0,M)}\u2026 [cut at ${M} of ${C.length} characters]`;return j}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 O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let V=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${V}`,"");continue}W=W.replace(V,d$($.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,V]of Object.entries(Z))O3(K,Q,V);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))O3(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 O(`"${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=(H)=>new O(`"${Z}" of "${$}" ${H}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!y$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!f$.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 H=W.data.replace(/\s+/g,"");if(Math.floor(H.length*3/4)-v$(H)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(H.length%4!==0||!w$.test(H))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(H,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let V;try{V=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(V.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let H=await H9(V.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!H.ok)throw G(`could not be fetched: ${V.host} answered ${H.status}.`);let J=await H.arrayBuffer();return new File([J],W.name,{type:W.mimeType})}catch(H){if(H instanceof O)throw H;throw G(`could not be fetched from ${V.host}: ${H instanceof Error?H.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(C$,{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(!S$.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 V9(G,z);let X=(J,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${G}" ${J}`);else console.error(`[gemi/mcp] "${G}" ${J}`,I);return new O(`"${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 V=Q;if($.result)try{V=await $.result(Q,Z)}catch(J){throw X("failed in its result projection:",J)}if(W){let J=W.safeParse(V);if(J.ok===!1)throw X(`answered what its output schema refuses: ${J.errors.join(", ")}`);V=J.value}if(V===void 0)return null;let H=JSON.stringify(V);if(H!==void 0&&H.length>M)return`${H.slice(0,M)}\u2026 [cut at ${M} of ${H.length} characters]`;return V}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof e)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function k$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function M$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function $9($,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(!M$($))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 R$($,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 Z9($,Z,z){let G=$.descriptor.name,W=`mcp_${crypto.randomUUID()}`,X=`mcp_call_${crypto.randomUUID()}`,Y=(Q)=>async()=>{throw new e(`"${G}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},K={put:Y("attachment store"),get:Y("attachment store"),read:Y("attachment store"),file:Y("attachment store")};return{context:Z,body:{},runId:W,toolCallId:X,signal:z,step:1,depth:0,resumed:!1,attachments:K,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:Y("agent run to nest a sub-agent in"),generateImage:Y("attachment store to put an image in"),editImage:Y("attachment store to put an image in"),generate:(Q)=>N9({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:G,runId:W,toolCallId:X}}),jobs:J9({jobs:void 0,threadId:void 0,runId:W,toolCallId:X,toolName:G,depth:0,async:$.tool.async,attachments:null}),memory:F9()}}function W3($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function z9($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function G9($,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 D3($){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 W9($,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 E$=10485760;function b$($){let Z=$?.maxBytes??E$;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 y$($){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 f$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,w$=/^[A-Za-z0-9+/]*={0,2}$/;function v$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function X9($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Y9($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function h$($,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 g$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function m$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function K9($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?m$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!g$.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 Q9($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,V])=>[Q,V.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 V=[],H={};if($){let I=$.safeParse(Q);if(I.ok===!1)V.push(...I.errors);else H={...I.value}}let J=z.safeParse(Q);if(J.ok===!1)V.push(...J.errors);else H={...H,...J.value};for(let[I,U]of Object.entries(G)){let F=Q[I];if(F===void 0){V.push(`"${I}" is required`);continue}let B=U.safeParse(F);if(B.ok===!1)V.push(...B.errors.map((T)=>`${I}: ${T}`));else H[I]=B.value}return V.length>0?{ok:!1,errors:V}:{ok:!0,value:H}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let V=K(Q);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function u$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function d$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function O3($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O3($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function p$($){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 V9($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!T$.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>M)return`${W.slice(0,M)}\u2026 [cut at ${M} 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>e3?`${z.slice(0,e3)}\u2026`:z;throw new O(`"${$}" 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 O(`"${$}" failed on the server.`,Z.status)}import{createHash as c$,randomBytes as i$,timingSafeEqual as l$}from"crypto";function j3($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class n${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`${$}${i$(32).toString("base64url")}`}static hash($){return c$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&l$(z,G)}async resolve($){let Z=j3($);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 R9,randomBytes as _9}from"crypto";async function A3($,Z){let z=s$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function s$(){try{let $=y();return $.bound(l)?$.make(l):null}catch{return null}}var x3=["2026-07-28"],Y3=["2025-11-25","2025-06-18","2025-03-26"],C3=[...x3,...Y3],S3="io.modelcontextprotocol/protocolVersion",q3="io.modelcontextprotocol/clientCapabilities";var T3="io.modelcontextprotocol/serverInfo",D={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 R($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function P9($){if(Array.isArray($))throw new L(D.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(D.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(D.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(D.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(D.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function k3($,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 q($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function I9($){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 t$,timingSafeEqual as o$}from"crypto";function M3($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${L9($,Z,G).toString("base64url")}`}function R3($,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=L9($,Z,X);if(K.length!==Q.length||!o$(K,Q))return null;let V;try{V=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof V!=="object"||V===null)return null;if(typeof V.exp!=="number"||V.exp<=G)return null;return V}function L9($,Z,z){return t$("sha256",K3($)).update(`${Z}.${z}`).digest()}var E3="gemi.mcp.request-state.v1",D9="gemi.mcp.session.v1",a$=86400000,O9=600000,j9="gemi_approval",b3=2000,r$={limit:600,window:60},e$={limit:30,window:60};class $3{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;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=z2(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().");if(this.resolvers=G,K3(E3),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.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??r$,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 k9,this.approvalTimeoutMs=Z.approvalTimeoutMs??O9,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??X3;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(Z.host!==this.endpoint.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 f(R(null,new L(D.InvalidRequest,"Origin not allowed.")),403);let G=z?Z2(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 A9(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return A9(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(j3($)!==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 $2($,this.maxBodyBytes))}catch(Y){if(Y instanceof V3)return f(R(null,new L(D.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return f(R(null,new L(D.ParseError,"Parse error.")),400)}let X=new m($,{},"api",this.endpoint.pathname);return await h.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=q(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return f(R(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),f(R(null,new L(D.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=P9(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let F=this.session($,z),B=this.pending.get(String(W.message.id));if(B&&B.session===F.id)this.pending.delete(String(W.message.id)),B.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=q(K._meta)?K._meta:{};if(typeof Q[S3]==="string"){if(this.checkModernHeaders($,Y,Q[S3]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(F,B)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:F,signal:B}),C9(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(D.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let V=this.session($,z),H=$.headers.get("mcp-protocol-version");if(H!==null&&H!==V.state.v)throw new L(D.InvalidRequest,`MCP-Protocol-Version ${H} is not the session's ${V.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let F=K.requestId;this.inflight.get(`${V.id}:${String(F)}`)?.abort()}return new Response(null,{status:202})}let J=`${V.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(J,I);let U=AbortSignal.any([I.signal,$.signal]);try{return await this.respond(Y,async(F,B)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:V.state,sessionId:V.id},stream:F,signal:B}),C9(K)||W2(this.registry,Y,V.state),U,()=>this.inflight.delete(J))}catch(F){throw this.inflight.delete(J),F}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C3,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)=>k3(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(D.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)=>k3(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(D.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T3]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Y3.includes(G)?G:Y3[0],X=q(Z.capabilities)?Z.capabilities:{},Y={v:W,e:x9(X.elicitation),p:Q3(z),exp:Date.now()+a$},K=M3(D9,"gms1",Y);return f({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(D.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R3(D9,"gms1",z);if(!G||G.p!==Q3(Z))throw new L(D.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x3.includes(z))throw new L(D.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C3,requested:z},400);let G=(Y)=>new L(D.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||I9(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(D.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=(U,F)=>{G.outcome="denied",G.reason=U,G.message=F},K=(U,F,B)=>{if(G.outcome="error",G.message=U,F!==void 0)G.status=F;if(B!==void 0)G.error=B},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(D.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let U=Q.inputSchema.safeParse(z);if(U.ok===!1){let B=`Invalid arguments for "${Z}": ${U.errors.join(", ")}`;return K(B),this.toolResult($,{content:[{type:"text",text:B}],isError:!0})}if($.era.modern&&q($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let B=await this.approval($,Q,z,Y,G);if(B.kind==="answer")return B.result;G.approved=!0}}let V=X2($),H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,...V?{progress:V}:{}})}catch(U){if(U instanceof O){if(U.status===401||U.status===403)Y("forbidden",U.message),G.status=U.status;else K(U.message,U.status);return this.toolResult($,{content:[{type:"text",text:U.message}],isError:!0})}if(U instanceof v){let B=U.reason==="unknown-tool"?`Unknown tool: ${Z}`:U.message;throw Y(U.reason,B),new L(D.InvalidParams,B)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,U);let F=`"${Z}" failed on the server.`;return K(F,void 0,U),this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}let J=typeof H==="string"?H:JSON.stringify(H??null),I=Q.outputSchema&&($.era.modern||q(H))?{structuredContent:H}:{};return G.outcome="ok",this.toolResult($,{content:[{type:"text",text:J}],...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=Y2(Z,z),Y=(I,U="approval-declined")=>{return G(U,I),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:I}],isError:!0})}},K=(I,U)=>{return G(I,U.message),U};if($.era.modern){let I=q($.params._meta)?$.params._meta:{},U=q(I[q3])?I[q3]:{},F=q($.params.inputResponses)?$.params.inputResponses:null,B=$.params.requestState,T=G2(z);if(F&&B!==void 0){let C=R3(E3,"grs1",B);if(!C||C.p!==Q3($.principal)||C.t!==Z.name||C.a!==T)throw K("approval-invalid",new L(D.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(C.n,C.exp))throw K("approval-replayed",new L(D.InvalidParams,"requestState has already been used."));return S9(F[j9])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!x9(U.elicitation))throw K("approval-unavailable",new L(D.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:Q3($.principal),t:Z.name,a:T,n:_9(16).toString("base64url"),exp:Date.now()+O9};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[j9]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:M3(E3,"grs1",j),_meta:{[T3]: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 V=`gemi-approval-${_9(12).toString("base64url")}`,H=Q.sessionId,J=await new Promise((I)=>{let U=setTimeout(()=>{this.pending.delete(V),I(null)},this.approvalTimeoutMs),F=(B)=>{clearTimeout(U),I(B)};this.pending.set(V,{session:H,resolve:F}),$.signal.addEventListener("abort",()=>{this.pending.delete(V),F(null)}),$.stream.send({jsonrpc:"2.0",id:V,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return J&&!J.error&&S9(J.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 f({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new E9(()=>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(R($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(R($.id,new L(D.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 f(R(null,new L(D.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=T9(new m($,{},"api",this.endpoint.pathname)),z=await A3(`mcp-auth-failed:${Z}`,e$);return z===null?null:q9(z)}async spend($){if(!this.rateLimit)return null;let Z=await A3(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:q9(Z)}}class E9{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
- `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class V3 extends Error{}async function $2($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V3;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 V3;W.push(K)}return Buffer.concat(W).toString("utf8")}function f($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function x9($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function Z2($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function z2($){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 Q3($){return R9("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function G2($){return R9("sha256").update(M9($??{})).digest("base64url")}function A9($){if(!S($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function C9($){let Z=S($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function W2($,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 X2($){let z=(S($.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 Y2($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b3?`${z.slice(0,b3)}\u2026 (${z.length-b3} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
5
+ `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class V3 extends Error{}async function $2($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V3;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 V3;W.push(K)}return Buffer.concat(W).toString("utf8")}function f($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function A9($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function Z2($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function z2($){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 Q3($){return R9("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function G2($){return R9("sha256").update(M9($??{})).digest("base64url")}function x9($){if(!q($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function C9($){let Z=q($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function W2($,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 X2($){let z=(q($.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 Y2($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b3?`${z.slice(0,b3)}\u2026 (${z.length-b3} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
6
6
 
7
- Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function S9($){return S($)&&$.action==="accept"&&S($.content)&&$.content.approve===!0}function q9($){return f(R(null,new P(_.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function K2($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=Q2($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y3($);return}let G;try{if(G=Z.locks?.()??V2(),$.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 y3($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y3($,W))}catch(W){if(W instanceof f9)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 b9=300000;function Q2($){if(!$)return;if($===!0)return b9;return $.expiresAfter??b9}var y9;function V2(){return y9??=new u(new w9),y9}async function y3($,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 d{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,()=>$(()=>K2(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 H2}from"worker_threads";var U2=100,J2=($)=>Math.min(U2,Math.floor($/10));class F2 extends N{register(){this.app.singleton(x,()=>new x(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(u,()=>this.app.make(x).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=j(v9(),$);if($.jobs===void 0)this.app.make(x).useJobs(await d9(Z));if($.workflows===void 0){let G=await c9(z);if(G.length>0)this.app.make(x).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(x))return;let Z=this.app.make(x);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-J2(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 u6($){if(B2($),Bun.env.NODE_ENV!=="production")return P2($);if(p9($))return;if(!h9())return;if(!$.bound(x))return;$.make(x).start()}function p9($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof g9}function N2($){if(p9($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(x))return!1;try{return!$.make(x).durable}catch{return!1}}function B2($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||u9())return;if(process.env.ROOT_DIR===void 0||!H2)return;if(m9()){if(!N2($))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 P2($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(x))$.make(x).start()}function I2($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var L2=new Set,_2={refusal:null,apply:($)=>$,carried:null};async function $$($){let Z=y(n);if(Z.config.global.length===0)return _2;let{pathname:z}=new URL($.url),G=a9(z),W=new m($,{},G?"api":"view","");return await g.run(W,async()=>{let X=g.getStore(),{headers:Y,cookies:K}=X,Q=(V)=>{if(!I2(V))return w3(V,Y,K);let H=new Headers(Y);return H.delete("Set-Cookie"),w3(V,H,L2)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(V){let H=!G&&z.endsWith(".json");if(V?.kind===i9){let U=G?e9(V.payload.api):H?o9(V.payload.viewData??V.payload.api):f3(V.payload.view);return{refusal:Q(U),apply:Q,carried:null}}if(l9(V)&&(G||H))return{refusal:Q(r9()),apply:Q,carried:null};if(n9(V)){console.error(V);let U=G||H?t9():f3(s9());return{refusal:Q(U),apply:Q,carried:null}}throw V}finally{X.destroy()}})}var D2=120,O2=2000,j2=3;class s{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||g3())return b(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return b(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(H3))return b(400,`Open the socket with the "${H3}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return b(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return b(503,"Too many connections.",{"Retry-After":"10"});let W=S2($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return b(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 $$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||g3())return b(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let H=new m($,{},"api",this.config.path);X=await g.run(H,async()=>{let U=g.getStore();try{return await X$(H)}finally{U.destroy()}},W)}catch(H){return console.error("[gemi] Resolving the session of a socket upgrade failed.",H),b(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=C2(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return b(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=W$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:G$(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":H3},data:Q}))return b(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&&x2(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--,Z$(this.perIp,$.ip),Z$(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($),t($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(q.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(q.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(q.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))t($,{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)E($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(q.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(q.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=D2)return!0;return $.close(q.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!h3.test(G)){$.close(q.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return E($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!A2(Y))return E($,G,"invalid");if(z.subs.has(G))return E($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return E($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),E($,G,"unknown_channel");let Q;for(let V=1;;V++){let H=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)<=H)break;if(V>=j2)return z.subs.delete(G),E($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),E($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(V){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,V),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);E($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;t($,{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"||!h3.test(z)){$.close(q.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 "${$}".`),v3(W,q.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()*O2);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)v3(W,q.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 V=X[Q];if(G.subs.get(Y)!==K)return;if(V.ok===!0&&V.topic===Z)return;G.subs.delete(Y),this.leave($,Z),E($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)t($,{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($){t($,{op:"bye",code:q.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),v3($,q.Restart,"Server restarting.")}run($){return U3.run(this.application,$)}}function x2($,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 v3($,Z,z){$.data.closing=!0,$.close(Z,z)}function t($,Z){$.send(JSON.stringify(Z))}function E($,Z,z){t($,{op:"denied",id:Z,code:z})}function b($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function A2($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function C2($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function S2($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return z$(z)??z;try{return Z.requestIP($)?.address??null}catch{return null}}function Z$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class q2 extends N{register(){this.app.singleton(w,()=>new w(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(s,()=>new s(this.app.make(w),this.app))}boot(){let $=this.app.config.get("route.channels");if($)K$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(w).driver:void 0;T2(Z,process.env,z)}async shutdown(){if(this.app.resolved(s))this.app.make(s).shutdown();if(!this.app.resolved(w))return;await this.app.make(w).close()}}function T2($,Z=process.env,z){if(!($.driver==="redis"||z instanceof Y$)||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 k2 extends N{register(){this.app.singleton(m3,()=>new m3(this.app.config.get("cache",{}),{application:this.app}))}}class M2 extends N{register(){this.app.singleton(Z3,()=>new Z3(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(Z3))return;await this.app.make(Z3).close()}}class R2 extends N{register(){this.app.singleton(d3,()=>new d3(this.app.config.get("auth",{}))),this.app.singleton(u3,()=>{let $=this.app.config.get("auth",{});return new u3({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){Q$(this.app.config.get("auth",{}))}}var E2=100,b2=($)=>Math.min(E2,Math.floor($/10));class y2 extends N{register(){this.app.singleton(d,()=>new d(j(c3(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(d),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=j(c3(),Z);$.useJobs(await V$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let z=this.app;if(z.bound(u))$.useLocks(()=>z.make(u));$.start((G)=>U3.run(z,G))}async shutdown($){if(!this.app.resolved(d))return;let Z=this.app.make(d);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-b2(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 o extends H${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return U$(this.modelName)}async load(){if(!this.available)throw new p3(this.modelName);let $=i3(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new p3(this.modelName);let G=i3(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 m8($){return $}function J$(){return{features:void 0,enabled:!0,source:new o,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class f2 extends N{register(){this.app.singleton(J3,()=>{let $=this.app.config.get("features",{}),Z=j(J$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new o($.model);else if($?.model!==void 0&&$.source instanceof o&&$.source.modelName!==$.model)F3.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new J3(Z,(z)=>F3.warning(z))})}async boot(){let $=this.app.make(J3);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){F3.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class w2 extends N{register(){this.app.singleton(l3,()=>new l3(this.app.config.get("mail",{})))}}class v2 extends N{register(){this.app.singleton(N3,()=>new N3(this.app.config.get("encryption",{})))}boot(){if(this.app.make(N3).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new n3(`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=F$();if(G.length===0)return;throw new n3(`${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 g2=Symbol.for("gemi.broadcastEvent");function N$($){return typeof $==="object"&&$!==null&&$[g2]===!0}function h2($){return`listener:${$}`}function P$($,Z){m2($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends B${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,V]=u2(K),H=y(c).rehydrate(Q,V);await new $().handle(H)}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:h2($.name),writable:!0}),Y}function m2($){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 u2($){return typeof $[0]==="string"?$:$[0]}class c{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=j(B3(),$),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?P$(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=I$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=N$($);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{y(w).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{y(x).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 d2 extends N{register(){this.app.singleton(c,()=>new c(this.app.config.get("events",{})))}async boot(){let $=this.app.make(c),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=j(B3(),Z);$.useListeners(await L$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(x);for(let W of z)G.registerJob(W)}}class c2 extends N{register(){this.app.singleton(t3,()=>new t3(this.app.config.get("filesystem",{})))}}class p2 extends N{register(){this.app.singleton(s3,()=>new s3(this.app.config.get("image",{})))}}class i2 extends N{register(){this.app.instance(o3,new o3)}}function bZ($){return $}function _$(){let $=Bun.env.NODE_ENV==="development";return{maxFileSize:10485760,console:$,consoleFormat:$?"text":"json",onLogFileClosed:()=>{},onLogCreated:()=>{}}}class l2 extends N{register(){this.app.singleton(P3,()=>new P3(j(_$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(P3).boot()}}class n2 extends N{register(){this.app.singleton(n,()=>new n(j(D$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(n).assertGlobalMiddleware()}}function lZ($){return $}function j$(){return{driver:new O$,limit:1000,window:60}}class t2 extends N{register(){this.app.singleton(l,()=>new l(j(j$(),this.app.config.get("ratelimiter",{}))))}}function eZ($){return $}function x$(){return{url:process.env.REDIS_URL,options:void 0}}class s2 extends N{register(){this.app.singleton(z3,()=>new z3(j(x$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(z3))return;this.app.make(z3).close()}}function I3($,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 o2 extends N{register(){this.app.singleton(a,()=>new a(I3(this.app.config,"route.api"))),this.app.singleton(G3,()=>new G3(I3(this.app.config,"route.view"))),this.app.singleton(L3,()=>new L3({api:this.app.make(a),view:this.app.make(G3)},{api:I3(this.app.config,"route.api"),view:I3(this.app.config,"route.view"),domains:this.app.config.get("route.domains"),clientIpTrust:A$(process.env)})),this.app.singleton(i,()=>{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 i(new $.router,this.app.make(a),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton($3,()=>{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 $3(this.app.make(i),$.remote)})}boot(){if(this.app.make(a),this.app.make(G3),this.app.make(L3),this.app.config.get("route.mcp"))this.app.make(i);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make($3);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class a2 extends N{register(){this.app.singleton(a3,()=>new a3(this.app.config.get("runs",{}),{application:this.app}))}}
8
- export{C$ as db,D as eb,v as fb,X6 as gb,i as hb,j3 as ib,n$ as jb,x3 as kb,M3 as lb,R3 as mb,$3 as nb,d as ob,F2 as pb,u6 as qb,$$ as rb,s as sb,q2 as tb,k2 as ub,M2 as vb,R2 as wb,y2 as xb,o as yb,m8 as zb,J$ as Ab,f2 as Bb,w2 as Cb,v2 as Db,g2 as Eb,N$ as Fb,c as Gb,d2 as Hb,c2 as Ib,p2 as Jb,i2 as Kb,bZ as Lb,_$ as Mb,l2 as Nb,n2 as Ob,lZ as Pb,j$ as Qb,t2 as Rb,eZ as Sb,x$ as Tb,s2 as Ub,o2 as Vb,a2 as Wb};
7
+ Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function S9($){return q($)&&$.action==="accept"&&q($.content)&&$.content.approve===!0}function q9($){return f(R(null,new L(D.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function K2($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=Q2($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y3($);return}let G;try{if(G=Z.locks?.()??V2(),$.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 y3($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y3($,W))}catch(W){if(W instanceof f9)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 b9=300000;function Q2($){if(!$)return;if($===!0)return b9;return $.expiresAfter??b9}var y9;function V2(){return y9??=new u(new w9),y9}async function y3($,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 d{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,()=>$(()=>K2(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 H2}from"worker_threads";var U2=100,J2=($)=>Math.min(U2,Math.floor($/10));class F2 extends P{register(){this.app.singleton(x,()=>new x(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(u,()=>this.app.make(x).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=A(v9(),$);if($.jobs===void 0)this.app.make(x).useJobs(await d9(Z));if($.workflows===void 0){let G=await p9(z);if(G.length>0)this.app.make(x).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(x))return;let Z=this.app.make(x);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-J2(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 u6($){if(B2($),Bun.env.NODE_ENV!=="production")return P2($);if(c9($))return;if(!g9())return;if(!$.bound(x))return;$.make(x).start()}function c9($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof h9}function N2($){if(c9($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(x))return!1;try{return!$.make(x).durable}catch{return!1}}function B2($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||u9())return;if(process.env.ROOT_DIR===void 0||!H2)return;if(m9()){if(!N2($))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 P2($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(x))$.make(x).start()}function I2($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var L2=new Set,_2={refusal:null,apply:($)=>$,carried:null};async function $$($){let Z=y(n);if(Z.config.global.length===0)return _2;let{pathname:z}=new URL($.url),G=a9(z),W=new m($,{},G?"api":"view","");return await h.run(W,async()=>{let X=h.getStore(),{headers:Y,cookies:K}=X,Q=(V)=>{if(!I2(V))return w3(V,Y,K);let H=new Headers(Y);return H.delete("Set-Cookie"),w3(V,H,L2)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(V){let H=!G&&z.endsWith(".json");if(V?.kind===i9){let J=G?e9(V.payload.api):H?o9(V.payload.viewData??V.payload.api):f3(V.payload.view);return{refusal:Q(J),apply:Q,carried:null}}if(l9(V)&&(G||H))return{refusal:Q(r9()),apply:Q,carried:null};if(n9(V)){console.error(V);let J=G||H?s9():f3(t9());return{refusal:Q(J),apply:Q,carried:null}}throw V}finally{X.destroy()}})}var D2=120,O2=2000,j2=3;class t{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||h3())return b(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return b(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(H3))return b(400,`Open the socket with the "${H3}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return b(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return b(503,"Too many connections.",{"Retry-After":"10"});let W=S2($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return b(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 $$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||h3())return b(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let H=new m($,{},"api",this.config.path);X=await h.run(H,async()=>{let J=h.getStore();try{return await X$(H)}finally{J.destroy()}},W)}catch(H){return console.error("[gemi] Resolving the session of a socket upgrade failed.",H),b(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=C2(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return b(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=W$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:G$(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":H3},data:Q}))return b(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&&A2(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--,Z$(this.perIp,$.ip),Z$(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($),s($,{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($))s($,{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)E($,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<=D2)return!0;return $.close(k.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!g3.test(G)){$.close(k.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return E($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!x2(Y))return E($,G,"invalid");if(z.subs.has(G))return E($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return E($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),E($,G,"unknown_channel");let Q;for(let V=1;;V++){let H=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)<=H)break;if(V>=j2)return z.subs.delete(G),E($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),E($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(V){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,V),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);E($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;s($,{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"||!g3.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 "${$}".`),v3(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()*O2);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)v3(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 V=X[Q];if(G.subs.get(Y)!==K)return;if(V.ok===!0&&V.topic===Z)return;G.subs.delete(Y),this.leave($,Z),E($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)s($,{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($){s($,{op:"bye",code:k.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),v3($,k.Restart,"Server restarting.")}run($){return U3.run(this.application,$)}}function A2($,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 v3($,Z,z){$.data.closing=!0,$.close(Z,z)}function s($,Z){$.send(JSON.stringify(Z))}function E($,Z,z){s($,{op:"denied",id:Z,code:z})}function b($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function x2($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function C2($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function S2($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return z$(z)??z;try{return Z.requestIP($)?.address??null}catch{return null}}function Z$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class q2 extends P{register(){this.app.singleton(w,()=>new w(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(t,()=>new t(this.app.make(w),this.app))}boot(){let $=this.app.config.get("route.channels");if($)K$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(w).driver:void 0;T2(Z,process.env,z)}async shutdown(){if(this.app.resolved(t))this.app.make(t).shutdown();if(!this.app.resolved(w))return;await this.app.make(w).close()}}function T2($,Z=process.env,z){if(!($.driver==="redis"||z instanceof Y$)||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 k2 extends P{register(){this.app.singleton(m3,()=>new m3(this.app.config.get("cache",{}),{application:this.app}))}}class M2 extends P{register(){this.app.singleton(Z3,()=>new Z3(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(Z3))return;await this.app.make(Z3).close()}}class R2 extends P{register(){this.app.singleton(d3,()=>new d3(this.app.config.get("auth",{}))),this.app.singleton(u3,()=>{let $=this.app.config.get("auth",{});return new u3({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){Q$(this.app.config.get("auth",{}))}}var E2=100,b2=($)=>Math.min(E2,Math.floor($/10));class y2 extends P{register(){this.app.singleton(d,()=>new d(A(p3(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(d),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=A(p3(),Z);$.useJobs(await V$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let z=this.app;if(z.bound(u))$.useLocks(()=>z.make(u));$.start((G)=>U3.run(z,G))}async shutdown($){if(!this.app.resolved(d))return;let Z=this.app.make(d);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-b2(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 o extends H${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return U$(this.modelName)}async load(){if(!this.available)throw new c3(this.modelName);let $=i3(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new c3(this.modelName);let G=i3(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 m8($){return $}function J$(){return{features:void 0,enabled:!0,source:new o,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class f2 extends P{register(){this.app.singleton(J3,()=>{let $=this.app.config.get("features",{}),Z=A(J$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new o($.model);else if($?.model!==void 0&&$.source instanceof o&&$.source.modelName!==$.model)F3.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new J3(Z,(z)=>F3.warning(z))})}async boot(){let $=this.app.make(J3);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){F3.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class w2 extends P{register(){this.app.singleton(l3,()=>new l3(this.app.config.get("mail",{})))}}class v2 extends P{register(){this.app.singleton(N3,()=>new N3(this.app.config.get("encryption",{})))}boot(){if(this.app.make(N3).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new n3(`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=F$();if(G.length===0)return;throw new n3(`${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 h2=Symbol.for("gemi.broadcastEvent");function N$($){return typeof $==="object"&&$!==null&&$[h2]===!0}function g2($){return`listener:${$}`}function P$($,Z){m2($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends B${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,V]=u2(K),H=y(p).rehydrate(Q,V);await new $().handle(H)}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:g2($.name),writable:!0}),Y}function m2($){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 u2($){return typeof $[0]==="string"?$:$[0]}class p{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=A(B3(),$),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?P$(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=I$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=N$($);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{y(w).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{y(x).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 d2 extends P{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}=A(B3(),Z);$.useListeners(await L$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(x);for(let W of z)G.registerJob(W)}}class p2 extends P{register(){this.app.singleton(s3,()=>new s3(this.app.config.get("filesystem",{})))}}class c2 extends P{register(){this.app.singleton(t3,()=>new t3(this.app.config.get("image",{})))}}class i2 extends P{register(){this.app.instance(o3,new o3)}}function bZ($){return $}function _$(){let $=Bun.env.NODE_ENV==="development";return{maxFileSize:10485760,console:$,consoleFormat:$?"text":"json",onLogFileClosed:()=>{},onLogCreated:()=>{}}}class l2 extends P{register(){this.app.singleton(P3,()=>new P3(A(_$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(P3).boot()}}class n2 extends P{register(){this.app.singleton(n,()=>new n(A(D$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(n).assertGlobalMiddleware()}}function lZ($){return $}function j$(){return{driver:new O$,limit:1000,window:60}}class s2 extends P{register(){this.app.singleton(l,()=>new l(A(j$(),this.app.config.get("ratelimiter",{}))))}}function eZ($){return $}function A$(){return{url:process.env.REDIS_URL,options:void 0}}class t2 extends P{register(){this.app.singleton(z3,()=>new z3(A(A$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(z3))return;this.app.make(z3).close()}}function I3($,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 o2 extends P{register(){this.app.singleton(a,()=>new a(I3(this.app.config,"route.api"))),this.app.singleton(G3,()=>new G3(I3(this.app.config,"route.view"))),this.app.singleton(L3,()=>new L3({api:this.app.make(a),view:this.app.make(G3)},{api:I3(this.app.config,"route.api"),view:I3(this.app.config,"route.view"),domains:this.app.config.get("route.domains"),clientIpTrust:x$(process.env)})),this.app.singleton(i,()=>{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 i(new $.router,this.app.make(a),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton($3,()=>{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 $3(this.app.make(i),$.remote)})}boot(){if(this.app.make(a),this.app.make(G3),this.app.make(L3),this.app.config.get("route.mcp"))this.app.make(i);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make($3);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class a2 extends P{register(){this.app.singleton(a3,()=>new a3(this.app.config.get("runs",{}),{application:this.app}))}}
8
+ export{C$ as db,O as eb,v as fb,X6 as gb,i as hb,j3 as ib,n$ as jb,A3 as kb,M3 as lb,R3 as mb,$3 as nb,d as ob,F2 as pb,u6 as qb,$$ as rb,t as sb,q2 as tb,k2 as ub,M2 as vb,R2 as wb,y2 as xb,o as yb,m8 as zb,J$ as Ab,f2 as Bb,w2 as Cb,v2 as Db,h2 as Eb,N$ as Fb,p as Gb,d2 as Hb,p2 as Ib,c2 as Jb,i2 as Kb,bZ as Lb,_$ as Mb,l2 as Nb,n2 as Ob,lZ as Pb,j$ as Qb,s2 as Rb,eZ as Sb,A$ as Tb,t2 as Ub,o2 as Vb,a2 as Wb};
9
9
 
10
- //# debugId=CE5F072877DF3F2264756E2164756E21
10
+ //# debugId=F60D7FBF4F5D42F164756E2164756E21