gemi 0.241.0 → 0.242.1

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 (217) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/ai/testing/index.js +2 -2
  4. package/dist/ai/testing/index.js.map +1 -1
  5. package/dist/app/index.js +1 -1
  6. package/dist/bun/plugin.js +1 -1
  7. package/dist/bun/preload.js +1 -1
  8. package/dist/{chunk-8z16b2j2.js → chunk-093j5rh8.js} +3 -3
  9. package/dist/{chunk-8z16b2j2.js.map → chunk-093j5rh8.js.map} +2 -2
  10. package/dist/{chunk-bvgcv0jx.js → chunk-0jmh2271.js} +2 -2
  11. package/dist/{chunk-bvgcv0jx.js.map → chunk-0jmh2271.js.map} +1 -1
  12. package/dist/{chunk-etj63p4p.js → chunk-0tsnmrf9.js} +2 -2
  13. package/dist/{chunk-etj63p4p.js.map → chunk-0tsnmrf9.js.map} +1 -1
  14. package/dist/{chunk-0xmk4jyj.js → chunk-110ecy3e.js} +2 -2
  15. package/dist/{chunk-0xmk4jyj.js.map → chunk-110ecy3e.js.map} +1 -1
  16. package/dist/{chunk-samm4h7d.js → chunk-11hmhyk5.js} +2 -2
  17. package/dist/{chunk-samm4h7d.js.map → chunk-11hmhyk5.js.map} +1 -1
  18. package/dist/{chunk-8wvh099n.js → chunk-26pfh03x.js} +3 -3
  19. package/dist/{chunk-8wvh099n.js.map → chunk-26pfh03x.js.map} +1 -1
  20. package/dist/{chunk-51mz612v.js → chunk-27f9z8yk.js} +2 -2
  21. package/dist/{chunk-51mz612v.js.map → chunk-27f9z8yk.js.map} +1 -1
  22. package/dist/{chunk-3mq0wmq7.js → chunk-2g6cmkrn.js} +3 -3
  23. package/dist/{chunk-3mq0wmq7.js.map → chunk-2g6cmkrn.js.map} +1 -1
  24. package/dist/{chunk-4mysb5ej.js → chunk-2yvzc5tq.js} +2 -2
  25. package/dist/{chunk-4mysb5ej.js.map → chunk-2yvzc5tq.js.map} +1 -1
  26. package/dist/{chunk-vk1x3rsw.js → chunk-3tpj5t10.js} +2 -2
  27. package/dist/{chunk-vk1x3rsw.js.map → chunk-3tpj5t10.js.map} +1 -1
  28. package/dist/{chunk-vqmy8jfr.js → chunk-3ywtqcxt.js} +2 -2
  29. package/dist/{chunk-vqmy8jfr.js.map → chunk-3ywtqcxt.js.map} +1 -1
  30. package/dist/{chunk-3kgp6xka.js → chunk-4f8qpzsw.js} +1 -1
  31. package/dist/{chunk-qb8pjdez.js → chunk-4y0j6c56.js} +4 -4
  32. package/dist/{chunk-qb8pjdez.js.map → chunk-4y0j6c56.js.map} +1 -1
  33. package/dist/{chunk-e4adgvd6.js → chunk-54v3y7mg.js} +3 -3
  34. package/dist/{chunk-e4adgvd6.js.map → chunk-54v3y7mg.js.map} +1 -1
  35. package/dist/{chunk-fec4qnr3.js → chunk-57n0m9fv.js} +2 -2
  36. package/dist/{chunk-fec4qnr3.js.map → chunk-57n0m9fv.js.map} +1 -1
  37. package/dist/{chunk-vvq18rrr.js → chunk-5pfbqc1c.js} +2 -2
  38. package/dist/{chunk-vvq18rrr.js.map → chunk-5pfbqc1c.js.map} +1 -1
  39. package/dist/{chunk-2g1h9ktj.js → chunk-632nqkza.js} +2 -2
  40. package/dist/{chunk-2g1h9ktj.js.map → chunk-632nqkza.js.map} +1 -1
  41. package/dist/{chunk-kabkxq5q.js → chunk-646bqwp8.js} +2 -2
  42. package/dist/{chunk-kabkxq5q.js.map → chunk-646bqwp8.js.map} +1 -1
  43. package/dist/{chunk-3qmhe96e.js → chunk-65m459jb.js} +2 -2
  44. package/dist/{chunk-3qmhe96e.js.map → chunk-65m459jb.js.map} +1 -1
  45. package/dist/{chunk-bn2b57qq.js → chunk-79xrxgpj.js} +2 -2
  46. package/dist/{chunk-bn2b57qq.js.map → chunk-79xrxgpj.js.map} +1 -1
  47. package/dist/{chunk-3crknzwp.js → chunk-7c48nxqb.js} +3 -3
  48. package/dist/{chunk-3crknzwp.js.map → chunk-7c48nxqb.js.map} +1 -1
  49. package/dist/{chunk-feh44g4f.js → chunk-7mxwstm2.js} +2 -2
  50. package/dist/{chunk-feh44g4f.js.map → chunk-7mxwstm2.js.map} +1 -1
  51. package/dist/{chunk-gykwq8py.js → chunk-7qt9pxm6.js} +1 -1
  52. package/dist/{chunk-c7hbdsjv.js → chunk-7ztbpqed.js} +2 -2
  53. package/dist/{chunk-3ady4k66.js.map → chunk-7ztbpqed.js.map} +1 -1
  54. package/dist/chunk-8dga75cv.js +5 -0
  55. package/dist/{chunk-by0ydsqs.js.map → chunk-8dga75cv.js.map} +1 -1
  56. package/dist/{chunk-zsmwmg8x.js → chunk-9cxs1q57.js} +2 -2
  57. package/dist/{chunk-zsmwmg8x.js.map → chunk-9cxs1q57.js.map} +1 -1
  58. package/dist/{chunk-387fpg2k.js → chunk-9xm5z33t.js} +2 -2
  59. package/dist/{chunk-387fpg2k.js.map → chunk-9xm5z33t.js.map} +1 -1
  60. package/dist/{chunk-gpngw61t.js → chunk-ac135mmf.js} +2 -2
  61. package/dist/{chunk-gpngw61t.js.map → chunk-ac135mmf.js.map} +1 -1
  62. package/dist/{chunk-z0jf5kzx.js → chunk-bbhrs7s3.js} +2 -2
  63. package/dist/{chunk-z0jf5kzx.js.map → chunk-bbhrs7s3.js.map} +1 -1
  64. package/dist/{chunk-vq1q8mgm.js → chunk-bsmy8vqs.js} +2 -2
  65. package/dist/{chunk-vq1q8mgm.js.map → chunk-bsmy8vqs.js.map} +1 -1
  66. package/dist/{chunk-t495wyhh.js → chunk-c0hxmw3a.js} +2 -2
  67. package/dist/{chunk-t495wyhh.js.map → chunk-c0hxmw3a.js.map} +1 -1
  68. package/dist/{chunk-c3c37k46.js → chunk-d39h1mrz.js} +3 -3
  69. package/dist/{chunk-c3c37k46.js.map → chunk-d39h1mrz.js.map} +1 -1
  70. package/dist/{chunk-n30y9dc5.js → chunk-daw2xr2v.js} +4 -4
  71. package/dist/{chunk-n30y9dc5.js.map → chunk-daw2xr2v.js.map} +1 -1
  72. package/dist/{chunk-3rm4v7ht.js → chunk-dfat5nmk.js} +3 -3
  73. package/dist/{chunk-3rm4v7ht.js.map → chunk-dfat5nmk.js.map} +1 -1
  74. package/dist/{chunk-9a3wbbr6.js → chunk-e0e43wvq.js} +2 -2
  75. package/dist/{chunk-9a3wbbr6.js.map → chunk-e0e43wvq.js.map} +1 -1
  76. package/dist/{chunk-re13gf4s.js → chunk-e3m0anq1.js} +3 -3
  77. package/dist/{chunk-re13gf4s.js.map → chunk-e3m0anq1.js.map} +1 -1
  78. package/dist/{chunk-rpwvwsq9.js → chunk-e4a6smfv.js} +1 -1
  79. package/dist/{chunk-4wj4bwvc.js → chunk-eb4mx34p.js} +3 -3
  80. package/dist/{chunk-4wj4bwvc.js.map → chunk-eb4mx34p.js.map} +1 -1
  81. package/dist/{chunk-qkfd84hx.js → chunk-ed64ynex.js} +2 -2
  82. package/dist/{chunk-qkfd84hx.js.map → chunk-ed64ynex.js.map} +1 -1
  83. package/dist/chunk-evx7nxad.js +10 -0
  84. package/dist/{chunk-2f2t8j4j.js.map → chunk-evx7nxad.js.map} +4 -4
  85. package/dist/{chunk-z6gwn4xf.js → chunk-fb3qkmwh.js} +2 -2
  86. package/dist/{chunk-z6gwn4xf.js.map → chunk-fb3qkmwh.js.map} +1 -1
  87. package/dist/{chunk-9fgyanab.js → chunk-fjh3xaq7.js} +2 -2
  88. package/dist/{chunk-9fgyanab.js.map → chunk-fjh3xaq7.js.map} +1 -1
  89. package/dist/{chunk-kgbgj7v4.js → chunk-fs2cdxry.js} +2 -2
  90. package/dist/{chunk-kgbgj7v4.js.map → chunk-fs2cdxry.js.map} +1 -1
  91. package/dist/{chunk-bhycdjcv.js → chunk-fy4142fv.js} +2 -2
  92. package/dist/{chunk-bhycdjcv.js.map → chunk-fy4142fv.js.map} +1 -1
  93. package/dist/{chunk-342ydn4n.js → chunk-ge5m9qdt.js} +2 -2
  94. package/dist/{chunk-342ydn4n.js.map → chunk-ge5m9qdt.js.map} +1 -1
  95. package/dist/{chunk-7fh7cfjh.js → chunk-gqw25apr.js} +2 -2
  96. package/dist/{chunk-7fh7cfjh.js.map → chunk-gqw25apr.js.map} +1 -1
  97. package/dist/{chunk-wkw8afk0.js → chunk-h6dzn5j6.js} +2 -2
  98. package/dist/{chunk-wkw8afk0.js.map → chunk-h6dzn5j6.js.map} +1 -1
  99. package/dist/{chunk-x68jra5n.js → chunk-hhaxacwh.js} +2 -2
  100. package/dist/{chunk-x68jra5n.js.map → chunk-hhaxacwh.js.map} +1 -1
  101. package/dist/{chunk-a8q7ds6w.js → chunk-hvw25pe3.js} +1 -1
  102. package/dist/{chunk-6wv3k8ap.js → chunk-jr53em8y.js} +2 -2
  103. package/dist/{chunk-6wv3k8ap.js.map → chunk-jr53em8y.js.map} +1 -1
  104. package/dist/{chunk-gs8fvb6a.js → chunk-kejexfsg.js} +2 -2
  105. package/dist/{chunk-gs8fvb6a.js.map → chunk-kejexfsg.js.map} +1 -1
  106. package/dist/{chunk-rc86ewq1.js → chunk-kjz6jh54.js} +3 -3
  107. package/dist/{chunk-rc86ewq1.js.map → chunk-kjz6jh54.js.map} +1 -1
  108. package/dist/{chunk-7sxbq483.js → chunk-mjfnv2r9.js} +2 -2
  109. package/dist/{chunk-7sxbq483.js.map → chunk-mjfnv2r9.js.map} +1 -1
  110. package/dist/{chunk-7ycjs0xn.js → chunk-n537kc55.js} +2 -2
  111. package/dist/{chunk-7ycjs0xn.js.map → chunk-n537kc55.js.map} +1 -1
  112. package/dist/{chunk-8e14zcdc.js → chunk-n8cm2sw6.js} +2 -2
  113. package/dist/{chunk-8e14zcdc.js.map → chunk-n8cm2sw6.js.map} +1 -1
  114. package/dist/{chunk-n1phcznj.js → chunk-nse5sgzm.js} +2 -2
  115. package/dist/{chunk-n1phcznj.js.map → chunk-nse5sgzm.js.map} +1 -1
  116. package/dist/{chunk-cfpzhc8n.js → chunk-ny1c68ts.js} +2 -2
  117. package/dist/{chunk-cfpzhc8n.js.map → chunk-ny1c68ts.js.map} +2 -2
  118. package/dist/{chunk-13eq76tw.js → chunk-p03jdwc1.js} +2 -2
  119. package/dist/{chunk-13eq76tw.js.map → chunk-p03jdwc1.js.map} +1 -1
  120. package/dist/{chunk-aczp96k5.js → chunk-rffa9x3d.js} +2 -2
  121. package/dist/{chunk-aczp96k5.js.map → chunk-rffa9x3d.js.map} +1 -1
  122. package/dist/{chunk-1wfwqgm5.js → chunk-rwyn40p1.js} +2 -2
  123. package/dist/{chunk-1wfwqgm5.js.map → chunk-rwyn40p1.js.map} +1 -1
  124. package/dist/{chunk-gxre6wnc.js → chunk-s0azv6dd.js} +2 -2
  125. package/dist/{chunk-gxre6wnc.js.map → chunk-s0azv6dd.js.map} +1 -1
  126. package/dist/{chunk-1kjyhseb.js → chunk-sew755q5.js} +1 -1
  127. package/dist/{chunk-wgb26e02.js → chunk-sp79baph.js} +2 -2
  128. package/dist/{chunk-wgb26e02.js.map → chunk-sp79baph.js.map} +1 -1
  129. package/dist/{chunk-g9q39z7t.js → chunk-ss0gk90s.js} +2 -2
  130. package/dist/{chunk-g9q39z7t.js.map → chunk-ss0gk90s.js.map} +1 -1
  131. package/dist/{chunk-4sv5vkab.js → chunk-t4eeg7j1.js} +3 -3
  132. package/dist/{chunk-4sv5vkab.js.map → chunk-t4eeg7j1.js.map} +1 -1
  133. package/dist/{chunk-wjjxqw9b.js → chunk-t67dbfqs.js} +3 -3
  134. package/dist/{chunk-wjjxqw9b.js.map → chunk-t67dbfqs.js.map} +1 -1
  135. package/dist/{chunk-4j0h4q8v.js → chunk-t77xnb8k.js} +2 -2
  136. package/dist/{chunk-4j0h4q8v.js.map → chunk-t77xnb8k.js.map} +1 -1
  137. package/dist/{chunk-3ady4k66.js → chunk-tws22txn.js} +2 -2
  138. package/dist/{chunk-c7hbdsjv.js.map → chunk-tws22txn.js.map} +1 -1
  139. package/dist/{chunk-ccymw1ed.js → chunk-v3ddktnq.js} +3 -3
  140. package/dist/{chunk-ccymw1ed.js.map → chunk-v3ddktnq.js.map} +1 -1
  141. package/dist/chunk-vh6vc4h1.js +596 -0
  142. package/dist/{chunk-6gek696n.js.map → chunk-vh6vc4h1.js.map} +7 -6
  143. package/dist/{chunk-tvb68dqg.js → chunk-vqtzwnwr.js} +2 -2
  144. package/dist/{chunk-tvb68dqg.js.map → chunk-vqtzwnwr.js.map} +1 -1
  145. package/dist/{chunk-rreb2k19.js → chunk-wac3gv1t.js} +2 -2
  146. package/dist/{chunk-rreb2k19.js.map → chunk-wac3gv1t.js.map} +1 -1
  147. package/dist/{chunk-p0dgpm5r.js → chunk-xvnjahea.js} +2 -2
  148. package/dist/{chunk-p0dgpm5r.js.map → chunk-xvnjahea.js.map} +1 -1
  149. package/dist/{chunk-cjwjrk12.js → chunk-xy5evkaz.js} +1 -1
  150. package/dist/{chunk-vcmwp7pv.js → chunk-ye1kbxkx.js} +3 -3
  151. package/dist/{chunk-vcmwp7pv.js.map → chunk-ye1kbxkx.js.map} +1 -1
  152. package/dist/{chunk-ff8rtz9h.js → chunk-yqsnrp2b.js} +2 -2
  153. package/dist/{chunk-ff8rtz9h.js.map → chunk-yqsnrp2b.js.map} +1 -1
  154. package/dist/{chunk-0wa8ztk5.js → chunk-yrna0ajq.js} +3 -3
  155. package/dist/{chunk-0wa8ztk5.js.map → chunk-yrna0ajq.js.map} +1 -1
  156. package/dist/{chunk-768yza4f.js → chunk-zpnxr23b.js} +2 -2
  157. package/dist/{chunk-768yza4f.js.map → chunk-zpnxr23b.js.map} +1 -1
  158. package/dist/{chunk-agpty0p6.js → chunk-zrqqnfrs.js} +2 -2
  159. package/dist/{chunk-agpty0p6.js.map → chunk-zrqqnfrs.js.map} +1 -1
  160. package/dist/config/index.js +1 -1
  161. package/dist/console/run.js +2 -2
  162. package/dist/console/run.js.map +1 -1
  163. package/dist/container/index.js +2 -2
  164. package/dist/container/index.js.map +1 -1
  165. package/dist/database/index.js +2 -2
  166. package/dist/database/index.js.map +1 -1
  167. package/dist/email/index.js +2 -2
  168. package/dist/email/index.js.map +1 -1
  169. package/dist/facades/Storage.d.ts +2 -2
  170. package/dist/facades/Storage.d.ts.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/probe/index.js +2 -2
  186. package/dist/probe/index.js.map +1 -1
  187. package/dist/server/index.js +2 -2
  188. package/dist/server/index.js.map +1 -1
  189. package/dist/services/cron/ScheduleServiceProvider.d.ts.map +1 -1
  190. package/dist/services/image-optimization/drivers/SharpDriver.d.ts +1 -1
  191. package/dist/services/index.js +2 -2
  192. package/dist/services/index.js.map +1 -1
  193. package/dist/services/queue/Job.d.ts +10 -0
  194. package/dist/services/queue/Job.d.ts.map +1 -1
  195. package/dist/services/queue/QueueManager.d.ts +10 -37
  196. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  197. package/dist/services/queue/QueueServiceProvider.d.ts.map +1 -1
  198. package/dist/services/queue/WorkerPool.d.ts +123 -0
  199. package/dist/services/queue/WorkerPool.d.ts.map +1 -0
  200. package/dist/services/queue/config.d.ts +16 -0
  201. package/dist/services/queue/config.d.ts.map +1 -1
  202. package/dist/services/queue/work.js +2 -2
  203. package/dist/services/queue/work.js.map +1 -1
  204. package/dist/stats/route-table.js +1 -1
  205. package/dist/support/index.js +2 -2
  206. package/dist/support/index.js.map +1 -1
  207. package/dist/vitest/index.js +1 -1
  208. package/package.json +2 -2
  209. package/dist/chunk-2f2t8j4j.js +0 -10
  210. package/dist/chunk-6gek696n.js +0 -591
  211. package/dist/chunk-by0ydsqs.js +0 -5
  212. /package/dist/{chunk-3kgp6xka.js.map → chunk-4f8qpzsw.js.map} +0 -0
  213. /package/dist/{chunk-gykwq8py.js.map → chunk-7qt9pxm6.js.map} +0 -0
  214. /package/dist/{chunk-rpwvwsq9.js.map → chunk-e4a6smfv.js.map} +0 -0
  215. /package/dist/{chunk-a8q7ds6w.js.map → chunk-hvw25pe3.js.map} +0 -0
  216. /package/dist/{chunk-1kjyhseb.js.map → chunk-sew755q5.js.map} +0 -0
  217. /package/dist/{chunk-cjwjrk12.js.map → chunk-xy5evkaz.js.map} +0 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Whether this code runs in a `worker = true` job's thread (#1325).
3
+ *
4
+ * The thread boots the whole application, every provider included, and a
5
+ * provider that starts something long-lived at boot would start a second copy
6
+ * of it there: the cron schedule firing every job twice, or a queue loop
7
+ * claiming jobs into a thread that exists to run one at a time. Those
8
+ * providers ask this. It reads `workerData`, which only the pool sets, rather
9
+ * than `isMainThread` alone, so an application booted in some other thread —
10
+ * a test runner's, say — is not mistaken for one.
11
+ */
12
+ export declare function isJobThread(): boolean;
13
+ /**
14
+ * Where a job thread finds the application (#1318).
15
+ *
16
+ * An app's own bootstrap is used when it exists: `app/bootstrap.ts` under
17
+ * development, `dist/server/bootstrap.mjs` (which `gemi build` emits from it)
18
+ * in production. Otherwise the thread does what `gemi queue:work` does:
19
+ * `new App({ kernel })` from `app/kernel/Kernel.ts`, with `App` resolved from
20
+ * the application's own gemi, the copy its kernel extends.
21
+ */
22
+ export declare function workerEntry(env?: Record<string, string | undefined>): {
23
+ bootstrap: string | undefined;
24
+ kernel: string;
25
+ app: string;
26
+ };
27
+ /** A job that did not finish within its `workerTimeout`. */
28
+ export declare class WorkerTimeoutError extends Error {
29
+ name: string;
30
+ }
31
+ /** How many job threads a pool keeps when the config does not say. */
32
+ export declare function defaultWorkerThreads(cores?: number): number;
33
+ export type WorkerPoolOptions = {
34
+ /** At most this many threads at once. */
35
+ size: number;
36
+ /** How long a thread may take to boot the application before its job fails. */
37
+ bootTimeoutMs: number;
38
+ /** The thread's source; the application's by default. For tests. */
39
+ source?: () => string;
40
+ };
41
+ /**
42
+ * The threads `worker = true` jobs run in (#1325).
43
+ *
44
+ * Booting the application is most of what a job thread costs: a production
45
+ * bundle is several megabytes, and loading it and booting every provider took
46
+ * seconds of CPU and a few hundred megabytes for a job whose own work was half
47
+ * a second. So a thread is kept once it has booted and runs the next job too.
48
+ *
49
+ * - **Lazy.** No thread exists until a worker job runs, and the pool grows one
50
+ * thread per job waiting for one, up to `size`. Jobs beyond that wait here
51
+ * for the first free thread.
52
+ * - **One job per thread at a time**, so a CPU-bound job has its core.
53
+ * - **A thread that fails is replaced.** One that crashes, errors outside a
54
+ * job, or exits fails the job it was running — only that one — and is
55
+ * dropped; the next waiting job starts a new thread. One that cannot boot
56
+ * fails the job it was started for, so an application that cannot load
57
+ * fails its jobs (which then retry and dead-letter) rather than spinning.
58
+ * - **A job past its timeout** has its thread terminated, since a thread
59
+ * cannot be interrupted in the middle of `run`, and fails with
60
+ * `WorkerTimeoutError`.
61
+ * - **Idle threads do not hold the process open**: they are unref'd until
62
+ * they are given a job.
63
+ */
64
+ export declare class WorkerPool {
65
+ private readonly options;
66
+ private readonly slots;
67
+ private readonly waiting;
68
+ private nextId;
69
+ private closed;
70
+ /**
71
+ * Set by `retireWhenIdle`: the pool that takes this one's waiting jobs, and
72
+ * its threads end as their jobs finish.
73
+ */
74
+ private successor;
75
+ constructor(options: WorkerPoolOptions);
76
+ /** The threads alive right now, booting ones included. */
77
+ get threads(): number;
78
+ run(jobName: string, args: string, timeoutMs: number): Promise<unknown>;
79
+ /**
80
+ * Ends every thread. Jobs still running or waiting fail; the queue's own
81
+ * `drain` is what waits for them first.
82
+ */
83
+ close(): void;
84
+ /**
85
+ * Hands this pool over to `successor`: jobs waiting here, and any run
86
+ * later, go to it; idle threads end now, and busy ones once their job is
87
+ * done, so a job already running finishes rather than failing. A thread
88
+ * still booting ends too, its job going to the successor. See `adoptPool`.
89
+ */
90
+ retireWhenIdle(successor: {
91
+ run: WorkerPool["run"];
92
+ }): void;
93
+ private forward;
94
+ private pump;
95
+ private spawn;
96
+ private assign;
97
+ private idle;
98
+ /**
99
+ * Drops a thread: fails the job it holds, if any, terminates it, and lets
100
+ * the next waiting job start a replacement. Safe to call twice; `terminate`
101
+ * itself fires `close`, which lands here again.
102
+ */
103
+ private retire;
104
+ }
105
+ /**
106
+ * Hands the process's pool over when a `bun --hot` reload builds a new one.
107
+ *
108
+ * A reload re-evaluates this module and boots a new application, whose queue
109
+ * makes a new pool; the previous pool's threads hold the application as it
110
+ * was before the save, a few hundred megabytes each. A pool from another
111
+ * evaluation of this module is retired when the new one is made: its idle
112
+ * threads end at once, and a job one is running finishes on its old code. A second pool
113
+ * from the same module (two applications in one process, as tests build) is
114
+ * left alone.
115
+ */
116
+ export declare function adoptPool(pool: WorkerPool): void;
117
+ /**
118
+ * Whether the process holds a pool from before a `bun --hot` reload. The dev
119
+ * boot asks, so the stale threads are let go as soon as the new application
120
+ * is up rather than at its first worker job.
121
+ */
122
+ export declare function hasStalePool(): boolean;
123
+ //# sourceMappingURL=WorkerPool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkerPool.d.ts","sourceRoot":"","sources":["../../../services/queue/WorkerPool.ts"],"names":[],"mappings":"AAUA;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,IAAI,OAAO,CAErC;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GAAG;IAClF,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb,CAoBA;AAmDD,4DAA4D;AAC5D,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,IAAI,SAAwB;CAC7B;AAED,sEAAsE;AACtE,wBAAgB,oBAAoB,CAAC,KAAK,SAAyB,UAElE;AAmBD,MAAM,MAAM,iBAAiB,GAAG;IAC9B,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,+EAA+E;IAC/E,aAAa,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CACvB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,UAAU;IAWT,OAAO,CAAC,QAAQ,CAAC,OAAO;IAVpC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAmB;IACzC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB;;;OAGG;IACH,OAAO,CAAC,SAAS,CAAyC;gBAE7B,OAAO,EAAE,iBAAiB;IAEvD,0DAA0D;IAC1D,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAWvE;;;OAGG;IACH,KAAK;IAUL;;;;;OAKG;IACH,cAAc,CAAC,SAAS,EAAE;QAAE,GAAG,EAAE,UAAU,CAAC,KAAK,CAAC,CAAA;KAAE;IAYpD,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,IAAI;IAiBZ,OAAO,CAAC,KAAK;IAmEb,OAAO,CAAC,MAAM;IAkBd,OAAO,CAAC,IAAI;IAKZ;;;;OAIG;IACH,OAAO,CAAC,MAAM;CASf;AAkBD;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,UAAU,QAIzC;AAED;;;;GAIG;AACH,wBAAgB,YAAY,YAG3B"}
@@ -115,6 +115,22 @@ export interface QueueConfig {
115
115
  * unknown name there is dead-lettered at once.
116
116
  */
117
117
  unknownJobGrace?: number;
118
+ /**
119
+ * How many threads `worker = true` jobs run in, at most, in this process.
120
+ * Each boots its own copy of the application once, the first time a worker
121
+ * job needs it, and then runs one job at a time for as long as the process
122
+ * lives; worker jobs beyond this many wait for a free one. Default: the
123
+ * number of cores less one, between 1 and 2. Each thread holds a booted
124
+ * application in memory, so raise it with that in mind.
125
+ */
126
+ workerThreads?: number;
127
+ /**
128
+ * How long, in milliseconds, a new job thread may take to boot the
129
+ * application before the job it was started for fails and the thread is
130
+ * ended. Default two minutes. A job's own time limit is `workerTimeout` on
131
+ * the job.
132
+ */
133
+ workerBootTimeout?: number;
118
134
  /**
119
135
  * Where locks are kept: the ones unique jobs, a cron job's
120
136
  * `withoutOverlapping` and `onOneServer`, and the `Lock` facade take.
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../services/queue/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACH,IAAI,CAAC,EAAE,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC;IAE5B;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;OAIG;IACH,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC;IAE5B,gFAAgF;IAChF,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;;;;;;;;;;;;;;OAmBG;IACH,MAAM,CAAC,EACH,QAAQ,GACR,UAAU,GACV,WAAW,GACX,CAAC,CAAC,WAAW,EAAE,WAAW,KAAK,WAAW,CAAC,CAAC;IAEhD;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;;;;;;;OAkBG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;;;;;;;OAUG;IACH,KAAK,CAAC,EACF,MAAM,GACN,QAAQ,GACR,UAAU,GACV,SAAS,GACT,CAAC,CAAC,WAAW,EAAE,WAAW,KAAK,SAAS,CAAC,CAAC;CAC/C;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,WAAW,GAAG,WAAW,CAElE;AAED,wBAAgB,mBAAmB,IAAI,QAAQ,CAAC,WAAW,CAAC,CAa3D"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../services/queue/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAIzD,MAAM,WAAW,WAAW;IAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACH,IAAI,CAAC,EAAE,KAAK,CAAC,UAAU,GAAG,CAAC,CAAC;IAE5B;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;OAIG;IACH,SAAS,CAAC,EAAE,aAAa,EAAE,CAAC;IAE5B,gFAAgF;IAChF,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;;;;;;;;;;;;;;OAmBG;IACH,MAAM,CAAC,EACH,QAAQ,GACR,UAAU,GACV,WAAW,GACX,CAAC,CAAC,WAAW,EAAE,WAAW,KAAK,WAAW,CAAC,CAAC;IAEhD;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;;;;;;;OAkBG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;;;;;;OAUG;IACH,KAAK,CAAC,EACF,MAAM,GACN,QAAQ,GACR,UAAU,GACV,SAAS,GACT,CAAC,CAAC,WAAW,EAAE,WAAW,KAAK,SAAS,CAAC,CAAC;CAC/C;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,WAAW,GAAG,WAAW,CAElE;AAED,wBAAgB,mBAAmB,IAAI,QAAQ,CAAC,WAAW,CAAC,CAe3D"}
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Qe as J,Te as A}from"../../chunk-6gek696n.js";import{Uk as V}from"../../chunk-9a3wbbr6.js";import"../../chunk-0wa8ztk5.js";import"../../chunk-6wv3k8ap.js";import"../../chunk-ccymw1ed.js";import"../../chunk-aczp96k5.js";import"../../chunk-3mq0wmq7.js";import"../../chunk-wgb26e02.js";import{Gm as Y,Jm as N,Km as Z,Lm as _,Pm as I}from"../../chunk-vqmy8jfr.js";import{Tm as x}from"../../chunk-zsmwmg8x.js";import"../../chunk-c7hbdsjv.js";import $ from"path";function X(z){if(!z.config.get("route.channels"))return null;let C=z.config.get("broadcast",{}).driver;if(!(C===void 0||C==="memory"||C instanceof V))return null;return'[gemi] Broadcasts from this worker reach no one: the broadcast driver is "memory", which delivers to the sockets of the process that emits, and a worker has none. Set `driver: "redis"` in app/config/broadcast.ts.'}class L extends Error{name="QueueWorkerRefused"}class O{kernel;stopping;keepAlive;settings;constructor(z,C={}){this.kernel=z;this.settings={..._(),...C}}async start(){if(await this.kernel.waitForBoot(),this.stopping)return;let z=this.kernel.app;if(!z.bound(J))throw new L("[gemi] `gemi queue:work` has no queue to claim from: this application does not register QueueServiceProvider.");let C=z.make(J);if(!C.durable)throw new L('[gemi] `gemi queue:work` refuses to start: the queue uses the memory driver, which keeps each job in the process that dispatched it, so a worker never sees one. Set `driver: "database"` (or another driver every process can reach) in app/config/queue.ts, or run jobs in the server and drop the worker.');C.start(),this.keepAlive=setInterval(()=>{},1073741824),console.log(`[gemi] Queue worker started: claiming up to ${C.config.concurrency} job(s) at a time.`);let E=X(z);if(E)console.warn(E)}stop(z={}){return this.stopping??=this.drain({...this.settings,...z}),this.stopping}async drain(z){let C=Date.now()+z.timeoutMs;Y();let E=this.kernel.app,F=E.resolved(J)?E.make(J):void 0;if(F)console.log(`[gemi] Shutting down: waiting for ${F.running} running job(s) (up to ${z.timeoutMs/1000}s).`),await F.drain(z.timeoutMs);let G=N()===0;if(!G){let U=C-Date.now();if(G=U>0&&await Promise.race([Z().then(()=>!0),new Promise((K)=>setTimeout(()=>K(!1),U))]),!G)console.error(`[gemi] Shutdown grace period elapsed with ${N()} held background task(s) still running; abandoning them.`)}let H=await this.kernel.shutdown({timeoutMs:z.providerTimeoutMs});clearInterval(this.keepAlive);let T=G&&(F?.running??0)===0&&H.failed.length===0&&H.timedOut.length===0;return console.log(`[gemi] Shutdown ${T?"complete":"finished with errors"}.`),T?0:1}}async function j(){let z=x();process.env.ROOT_DIR=z,process.env.APP_DIR=$.join(z,"app"),A();let C=$.join(z,"app/kernel/Kernel.ts"),{default:E}=await import(C);if(typeof E!=="function")return console.error(`[gemi] ${C} has no default export to boot the worker from.`),1;let F=new E;F.boot();let G=new O(F);I(()=>G.stop());try{await G.start()}catch(H){if(!(H instanceof L))throw H;return console.error(H.message),1}return}j().then((z)=>{if(z!==void 0)process.exit(z)},(z)=>{console.error("[gemi] The queue worker failed to start:",z),process.exit(1)});
2
+ import{Se as J,Ve as A}from"../../chunk-vh6vc4h1.js";import{Wk as V}from"../../chunk-e0e43wvq.js";import"../../chunk-yrna0ajq.js";import"../../chunk-jr53em8y.js";import"../../chunk-v3ddktnq.js";import"../../chunk-rffa9x3d.js";import"../../chunk-2g6cmkrn.js";import"../../chunk-sp79baph.js";import{Im as Y,Lm as N,Mm as Z,Nm as _,Rm as I}from"../../chunk-3ywtqcxt.js";import{Vm as x}from"../../chunk-9cxs1q57.js";import"../../chunk-7ztbpqed.js";import $ from"path";function X(z){if(!z.config.get("route.channels"))return null;let C=z.config.get("broadcast",{}).driver;if(!(C===void 0||C==="memory"||C instanceof V))return null;return'[gemi] Broadcasts from this worker reach no one: the broadcast driver is "memory", which delivers to the sockets of the process that emits, and a worker has none. Set `driver: "redis"` in app/config/broadcast.ts.'}class L extends Error{name="QueueWorkerRefused"}class O{kernel;stopping;keepAlive;settings;constructor(z,C={}){this.kernel=z;this.settings={..._(),...C}}async start(){if(await this.kernel.waitForBoot(),this.stopping)return;let z=this.kernel.app;if(!z.bound(J))throw new L("[gemi] `gemi queue:work` has no queue to claim from: this application does not register QueueServiceProvider.");let C=z.make(J);if(!C.durable)throw new L('[gemi] `gemi queue:work` refuses to start: the queue uses the memory driver, which keeps each job in the process that dispatched it, so a worker never sees one. Set `driver: "database"` (or another driver every process can reach) in app/config/queue.ts, or run jobs in the server and drop the worker.');C.start(),this.keepAlive=setInterval(()=>{},1073741824),console.log(`[gemi] Queue worker started: claiming up to ${C.config.concurrency} job(s) at a time.`);let E=X(z);if(E)console.warn(E)}stop(z={}){return this.stopping??=this.drain({...this.settings,...z}),this.stopping}async drain(z){let C=Date.now()+z.timeoutMs;Y();let E=this.kernel.app,F=E.resolved(J)?E.make(J):void 0;if(F)console.log(`[gemi] Shutting down: waiting for ${F.running} running job(s) (up to ${z.timeoutMs/1000}s).`),await F.drain(z.timeoutMs);let G=N()===0;if(!G){let U=C-Date.now();if(G=U>0&&await Promise.race([Z().then(()=>!0),new Promise((K)=>setTimeout(()=>K(!1),U))]),!G)console.error(`[gemi] Shutdown grace period elapsed with ${N()} held background task(s) still running; abandoning them.`)}let H=await this.kernel.shutdown({timeoutMs:z.providerTimeoutMs});clearInterval(this.keepAlive);let T=G&&(F?.running??0)===0&&H.failed.length===0&&H.timedOut.length===0;return console.log(`[gemi] Shutdown ${T?"complete":"finished with errors"}.`),T?0:1}}async function j(){let z=x();process.env.ROOT_DIR=z,process.env.APP_DIR=$.join(z,"app"),A();let C=$.join(z,"app/kernel/Kernel.ts"),{default:E}=await import(C);if(typeof E!=="function")return console.error(`[gemi] ${C} has no default export to boot the worker from.`),1;let F=new E;F.boot();let G=new O(F);I(()=>G.stop());try{await G.start()}catch(H){if(!(H instanceof L))throw H;return console.error(H.message),1}return}j().then((z)=>{if(z!==void 0)process.exit(z)},(z)=>{console.error("[gemi] The queue worker failed to start:",z),process.exit(1)});
3
3
 
4
- //# debugId=3ABCBF3D67B1F60A64756E2164756E21
4
+ //# debugId=AC66DA9E1BC1584D64756E2164756E21
@@ -7,6 +7,6 @@
7
7
  "import type { Application, ShutdownReport } from \"../../foundation/Application\";\nimport {\n heldWork,\n heldWorkSettled,\n markShuttingDown,\n shutdownSettings,\n type ShutdownSettings,\n} from \"../../server/shutdown\";\nimport { memoryBroadcastInWorker } from \"../broadcast/workerWarning\";\nimport { QueueManager } from \"./QueueManager\";\n\n/** The part of a `Kernel` a worker drives. */\nexport type WorkerKernel = {\n readonly app: Application;\n waitForBoot(): Promise<void>;\n shutdown(options?: { timeoutMs?: number }): Promise<ShutdownReport>;\n};\n\n/**\n * A worker that was told to start in an application it cannot claim for. The\n * message is written for the operator reading the deploy's logs.\n */\nexport class QueueWorkerRefused extends Error {\n name = \"QueueWorkerRefused\";\n}\n\n/**\n * The process `gemi queue:work` runs: the application booted as a server boots\n * it, claiming from the queue, and no `Bun.serve`. It exists so job capacity\n * can be scaled apart from request traffic, which needs a driver both kinds of\n * process can reach; see `start` for why the memory driver is refused.\n *\n * The caller marks the process as a worker (`markQueueWorker`) before the\n * kernel registers, so every claim rule that asks `claimsInThisProcess` sees a\n * process that claims, whatever `GEMI_QUEUE_CLAIM` says.\n */\nexport class QueueWorker {\n private stopping: Promise<number> | undefined;\n private keepAlive: ReturnType<typeof setInterval> | undefined;\n private readonly settings: ShutdownSettings;\n\n /**\n * `settings` default to the `GEMI_SHUTDOWN_*` variables, read here rather\n * than at the signal so a bad value is warned about while the deploy is\n * being watched, as `Server.start` does.\n */\n constructor(\n private readonly kernel: WorkerKernel,\n settings: Partial<ShutdownSettings> = {},\n ) {\n this.settings = { ...shutdownSettings(), ...settings };\n }\n\n /**\n * Boots the application and starts claiming. Rejects with\n * `QueueWorkerRefused` when the application has no queue, or its queue uses\n * the memory driver.\n *\n * Refused rather than warned about, because a memory worker can never do\n * anything: its jobs live in a `Map` in the process that dispatched them,\n * so a worker's is always empty. Left running, it looks like a healthy\n * deploy — a process up, no errors — that runs nothing, and scaling it out\n * adds no capacity. An exit the platform reports as a crash loop is a form\n * of the mistake someone will see.\n */\n async start(): Promise<void> {\n await this.kernel.waitForBoot();\n // A signal during the boot has already drained and cleared the handle\n // below. Going on would start the loop again and arm a handle nothing\n // clears, holding open a worker that has finished shutting down.\n if (this.stopping) return;\n\n const application = this.kernel.app;\n // `bound`, not `make` in a try: an application built without the queue\n // provider is a configuration to name, not an unbound-token stack trace.\n if (!application.bound(QueueManager)) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` has no queue to claim from: this application \" +\n \"does not register QueueServiceProvider.\",\n );\n }\n const queue = application.make(QueueManager);\n if (!queue.durable) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` refuses to start: the queue uses the memory \" +\n \"driver, which keeps each job in the process that dispatched it, so \" +\n 'a worker never sees one. Set `driver: \"database\"` (or another driver ' +\n \"every process can reach) in app/config/queue.ts, or run jobs in the \" +\n \"server and drop the worker.\",\n );\n }\n\n // Idempotent: a production boot with a durable driver has already started\n // it (`startClaimingIfServing`). Development has not, and a worker claims\n // in either.\n queue.start();\n // The queue's poll timer is unref'd, so that a script's queue does not\n // hold it open; here the queue is the process, and without a handle of its\n // own an idle worker would exit 0 as soon as it booted.\n this.keepAlive = setInterval(() => {}, 1 << 30);\n console.log(\n `[gemi] Queue worker started: claiming up to ${queue.config.concurrency} job(s) at a time.`,\n );\n const broadcastWarning = memoryBroadcastInWorker(application);\n if (broadcastWarning) console.warn(broadcastWarning);\n }\n\n /**\n * Stops claiming, waits for the running jobs, runs every provider's\n * `shutdown()`, and resolves with the exit code: 0 when no job was left\n * running and every provider finished in time, 1 otherwise. Idempotent.\n *\n * `gemi start`'s drain, with the jobs where the requests were:\n * `isShuttingDown()` turns true, which stops a durable queue claiming;\n * running jobs get `timeoutMs` (`GEMI_SHUTDOWN_TIMEOUT`), which a server\n * spends on requests; then `Application.shutdown` gets `providerTimeoutMs`,\n * and in it the queue provider waits for whatever is still running and\n * names it. The two budgets add up as they do for a server, so a worker\n * fits the same grace period. `delayMs` is not waited: it is for a load\n * balancer, and nothing routes to a worker.\n */\n stop(settings: Partial<ShutdownSettings> = {}): Promise<number> {\n this.stopping ??= this.drain({ ...this.settings, ...settings });\n return this.stopping;\n }\n\n private async drain(settings: ShutdownSettings): Promise<number> {\n const deadline = Date.now() + settings.timeoutMs;\n markShuttingDown();\n const application = this.kernel.app;\n // Resolving the manager now would build a driver only to stop it, which\n // is what a signal during the boot, before the provider resolved it, finds.\n const queue = application.resolved(QueueManager) ? application.make(QueueManager) : undefined;\n if (queue) {\n console.log(\n `[gemi] Shutting down: waiting for ${queue.running} running job(s) ` +\n `(up to ${settings.timeoutMs / 1000}s).`,\n );\n await queue.drain(settings.timeoutMs);\n }\n // Work held with `holdShutdown` (#1210) gets what is left of the same budget.\n let held = heldWork() === 0;\n if (!held) {\n const remaining = deadline - Date.now();\n held =\n remaining > 0 &&\n (await Promise.race([\n heldWorkSettled().then(() => true),\n new Promise<false>((resolve) => setTimeout(() => resolve(false), remaining)),\n ]));\n if (!held) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${heldWork()} held background task(s) still running; abandoning them.`,\n );\n }\n }\n\n const report = await this.kernel.shutdown({ timeoutMs: settings.providerTimeoutMs });\n clearInterval(this.keepAlive);\n const clean =\n held && (queue?.running ?? 0) === 0 && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n }\n}\n"
8
8
  ],
9
9
  "mappings": ";gdAYA,kBCDO,OAAS,DAAuB,DAAC,AAAyC,DAC/E,CAAI,DAAC,AAAY,KAAO,IAAI,gBAAgB,EAAG,OAAO,KACtD,IAAM,EAAS,EAAY,OAAO,IAAqB,YAAa,CAAC,CAAC,EAAE,OAGxE,GAAI,EADF,IAAW,QAAa,IAAW,UAAY,aAAkB,GACtD,OAAO,KACpB,MACE,uNCIG,MAAM,UAA2B,KAAM,CAC5C,KAAO,oBACT,CAYO,MAAM,CAAY,CAWJ,OAVX,SACA,UACS,SAOjB,WAAW,CACQ,EACjB,EAAsC,CAAC,EACvC,CAFiB,cAGjB,KAAK,SAAW,IAAK,EAAiB,KAAM,CAAS,OAejD,MAAK,EAAkB,CAK3B,GAJA,MAAM,KAAK,OAAO,YAAY,EAI1B,KAAK,SAAU,OAEnB,IAAM,EAAc,KAAK,OAAO,IAGhC,GAAI,CAAC,EAAY,MAAM,CAAY,EACjC,MAAM,IAAI,EACR,+GAEF,EAEF,IAAM,EAAQ,EAAY,KAAK,CAAY,EAC3C,GAAI,CAAC,EAAM,QACT,MAAM,IAAI,EACR,8SAKF,EAMF,EAAM,MAAM,EAIZ,KAAK,UAAY,YAAY,IAAM,GAAI,UAAO,EAC9C,QAAQ,IACN,+CAA+C,EAAM,OAAO,+BAC9D,EACA,IAAM,EAAmB,EAAwB,CAAW,EAC5D,GAAI,EAAkB,QAAQ,KAAK,CAAgB,EAiBrD,IAAI,CAAC,EAAsC,CAAC,EAAoB,CAE9D,OADA,KAAK,WAAa,KAAK,MAAM,IAAK,KAAK,YAAa,CAAS,CAAC,EACvD,KAAK,cAGA,MAAK,CAAC,EAA6C,CAC/D,IAAM,EAAW,KAAK,IAAI,EAAI,EAAS,UACvC,EAAiB,EACjB,IAAM,EAAc,KAAK,OAAO,IAG1B,EAAQ,EAAY,SAAS,CAAY,EAAI,EAAY,KAAK,CAAY,EAAI,OACpF,GAAI,EACF,QAAQ,IACN,qCAAqC,EAAM,iCAC/B,EAAS,UAAY,SACnC,EACA,MAAM,EAAM,MAAM,EAAS,SAAS,EAGtC,IAAI,EAAO,EAAS,IAAM,EAC1B,GAAI,CAAC,EAAM,CACT,IAAM,EAAY,EAAW,KAAK,IAAI,EAOtC,GANA,EACE,EAAY,GACX,MAAM,QAAQ,KAAK,CAClB,EAAgB,EAAE,KAAK,IAAM,EAAI,EACjC,IAAI,QAAe,CAAC,IAAY,WAAW,IAAM,EAAQ,EAAK,EAAG,CAAS,CAAC,CAC7E,CAAC,EACC,CAAC,EACH,QAAQ,MACN,6CAA6C,EAAS,2DACxD,EAIJ,IAAM,EAAS,MAAM,KAAK,OAAO,SAAS,CAAE,UAAW,EAAS,iBAAkB,CAAC,EACnF,cAAc,KAAK,SAAS,EAC5B,IAAM,EACJ,IAAS,GAAO,SAAW,KAAO,GAAK,EAAO,OAAO,SAAW,GAAK,EAAO,SAAS,SAAW,EAElG,OADA,QAAQ,IAAI,mBAAmB,EAAQ,WAAa,yBAAyB,EACtE,EAAQ,EAAI,EAEvB,CFjJA,eAAe,CAAI,EAAgC,CACjD,IAAM,EAAU,EAAY,EAI5B,QAAQ,IAAI,SAAW,EACvB,QAAQ,IAAI,QAAU,EAAK,KAAK,EAAS,KAAK,EAE9C,EAAgB,EAEhB,IAAM,EAAa,EAAK,KAAK,EAAS,sBAAsB,GACpD,QAAS,GAAY,MAAa,UAG1C,GAAI,OAAO,IAAW,WAEpB,OADA,QAAQ,MAAM,UAAU,kDAA2D,EAC5E,EAET,IAAM,EAAS,IAAI,EACnB,EAAO,KAAK,EAEZ,IAAM,EAAS,IAAI,EAAY,CAAM,EAKrC,EAAuB,IAAM,EAAO,KAAK,CAAC,EAE1C,GAAI,CACF,MAAM,EAAO,MAAM,EACnB,MAAO,EAAO,CACd,GAAI,EAAE,aAAiB,GAAqB,MAAM,EAElD,OADA,QAAQ,MAAM,EAAM,OAAO,EACpB,EAGT,OAGF,EAAK,EAAE,KACL,CAAC,IAAS,CACR,GAAI,IAAS,OAAW,QAAQ,KAAK,CAAI,GAE3C,CAAC,IAAU,CACT,QAAQ,MAAM,2CAA4C,CAAK,EAC/D,QAAQ,KAAK,CAAC,EAElB",
10
- "debugId": "3ABCBF3D67B1F60A64756E2164756E21",
10
+ "debugId": "AC66DA9E1BC1584D64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import"../chunk-c7hbdsjv.js";import M from"path";import{writeFileSync as Q}from"fs";var L=new Set(["FILE","REDIRECT"]);function H(j){return j.run(()=>{let x=[];for(let{group:z,view:D}of j.domains().viewGroups())for(let[G,B]of Object.entries(D.flatViewRoutes)){let C=D.routeManifest[G]??B.segments.map((K)=>K.viewPath);if(C.length===0||L.has(C.at(-1)))continue;x.push({path:G,group:z,views:C,...B.static?{static:{...B.static.layout?{layout:B.static.layout}:{},...B.static.navigation?{navigation:!0}:{}}}:{}})}return x})}var J=process.argv[2];async function U(){if(!J)throw Error("usage: route-table <out.json>");let j=M.resolve(process.cwd(),"app/kernel/Kernel.ts"),x=await import(j);if(typeof x.default!=="function")throw Error(`${j} has no default export (the Kernel subclass).`);let z=new x.default;z.boot();try{Q(J,JSON.stringify(H(z)))}finally{z.destroy()}}U().then(()=>process.exit(0),(j)=>{console.error(j?.stack??String(j)),process.exit(1)});
2
+ import"../chunk-7ztbpqed.js";import M from"path";import{writeFileSync as Q}from"fs";var L=new Set(["FILE","REDIRECT"]);function H(j){return j.run(()=>{let x=[];for(let{group:z,view:D}of j.domains().viewGroups())for(let[G,B]of Object.entries(D.flatViewRoutes)){let C=D.routeManifest[G]??B.segments.map((K)=>K.viewPath);if(C.length===0||L.has(C.at(-1)))continue;x.push({path:G,group:z,views:C,...B.static?{static:{...B.static.layout?{layout:B.static.layout}:{},...B.static.navigation?{navigation:!0}:{}}}:{}})}return x})}var J=process.argv[2];async function U(){if(!J)throw Error("usage: route-table <out.json>");let j=M.resolve(process.cwd(),"app/kernel/Kernel.ts"),x=await import(j);if(typeof x.default!=="function")throw Error(`${j} has no default export (the Kernel subclass).`);let z=new x.default;z.boot();try{Q(J,JSON.stringify(H(z)))}finally{z.destroy()}}U().then(()=>process.exit(0),(j)=>{console.error(j?.stack??String(j)),process.exit(1)});
3
3
 
4
4
  //# debugId=05EB0087C5A2060D64756E2164756E21
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Ye as Y}from"../chunk-bhycdjcv.js";import{kl as M}from"../chunk-6wv3k8ap.js";import{um as P,wm as R}from"../chunk-3mq0wmq7.js";import"../chunk-wgb26e02.js";import{Qm as Q,Rm as U,Sm as V,Tm as W}from"../chunk-zsmwmg8x.js";import"../chunk-c7hbdsjv.js";class S{static token;async boot(){}onShutdown(x){}static inject(){if(!this.token)throw Error(`Service [${this.name}] does not declare a \`static token\`, so the container has no key to resolve it by.`);try{return R(this)}catch(x){throw Error(`Could not inject [${this.name}]. Services are constructed when the kernel boots, so `+"inject() only works from code that runs after that \u2014 a constructor default or a method "+`body, never module top level. Check that [${this.name}] is listed in \`services\` on your Kernel.`,{cause:x})}}static with(x){let f=new this;for(let[C,g]of Object.entries(x))if(g!==void 0)f[C]=g;return f}}import{readdir as z}from"fs/promises";import{join as B,parse as j}from"path";var H=[".ts",".tsx",".js",".mjs",".jsx"];function J(x={}){let f={};for(let[C,g]of Object.entries(x))f[C]=q(g);return new P(f)}async function L(x,f=new P){let C=[];try{C=await z(x)}catch(D){return f}let g=C.filter((D)=>{let{ext:v,name:F}=j(D);return H.includes(v)&&!F.startsWith(".")}).sort();for(let D of g){let{name:v}=j(D),F=await import(B(x,D));f.set(v,q(F))}return f}function q(x){if(x&&typeof x==="object"&&"default"in x)return x.default;return x}export{M as withDefaults,Q as sourceFiles,W as projectRoot,L as loadConfigFrom,V as discoverClasses,J as createConfigRepository,Y as ServiceProvider,S as Service,P as Repository,U as DiscoveryError};
2
+ import{_e as Y}from"../chunk-fy4142fv.js";import{ml as M}from"../chunk-jr53em8y.js";import{wm as P,ym as R}from"../chunk-2g6cmkrn.js";import"../chunk-sp79baph.js";import{Sm as Q,Tm as U,Um as V,Vm as W}from"../chunk-9cxs1q57.js";import"../chunk-7ztbpqed.js";class S{static token;async boot(){}onShutdown(x){}static inject(){if(!this.token)throw Error(`Service [${this.name}] does not declare a \`static token\`, so the container has no key to resolve it by.`);try{return R(this)}catch(x){throw Error(`Could not inject [${this.name}]. Services are constructed when the kernel boots, so `+"inject() only works from code that runs after that \u2014 a constructor default or a method "+`body, never module top level. Check that [${this.name}] is listed in \`services\` on your Kernel.`,{cause:x})}}static with(x){let f=new this;for(let[C,g]of Object.entries(x))if(g!==void 0)f[C]=g;return f}}import{readdir as z}from"fs/promises";import{join as B,parse as j}from"path";var H=[".ts",".tsx",".js",".mjs",".jsx"];function J(x={}){let f={};for(let[C,g]of Object.entries(x))f[C]=q(g);return new P(f)}async function L(x,f=new P){let C=[];try{C=await z(x)}catch(D){return f}let g=C.filter((D)=>{let{ext:v,name:F}=j(D);return H.includes(v)&&!F.startsWith(".")}).sort();for(let D of g){let{name:v}=j(D),F=await import(B(x,D));f.set(v,q(F))}return f}function q(x){if(x&&typeof x==="object"&&"default"in x)return x.default;return x}export{M as withDefaults,Q as sourceFiles,W as projectRoot,L as loadConfigFrom,V as discoverClasses,J as createConfigRepository,Y as ServiceProvider,S as Service,P as Repository,U as DiscoveryError};
3
3
 
4
- //# debugId=0722504D2BFEB23564756E2164756E21
4
+ //# debugId=4B40758CA8452E1F64756E2164756E21
@@ -6,6 +6,6 @@
6
6
  "import { readdir } from \"node:fs/promises\";\nimport { join, parse } from \"node:path\";\n\nimport { Repository } from \"./Repository\";\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".mjs\", \".jsx\"];\n\n// Builds a Repository from an already-imported map of config modules. The map\n// key becomes the top-level config key, so `{ mail: mailModule }` is readable\n// as `config.get(\"mail.driver\")`. Each entry may be either the module namespace\n// (its `default` export is unwrapped) or the config object itself.\nexport function createConfigRepository(\n modules: Record<string, any> = {},\n): Repository {\n const items: Record<string, any> = {};\n\n for (const [key, mod] of Object.entries(modules)) {\n items[key] = unwrap(mod);\n }\n\n return new Repository(items);\n}\n\n// Reads every config module in an app's `app/config` directory into a\n// Repository. The file's basename is the top-level key: `app/config/mail.ts`\n// populates `mail.*`. A missing directory yields an empty Repository so apps\n// that declare no config still boot.\nexport async function loadConfigFrom(\n directory: string,\n repository = new Repository(),\n): Promise<Repository> {\n let entries: string[] = [];\n\n try {\n entries = await readdir(directory);\n } catch (err) {\n return repository;\n }\n\n const files = entries\n .filter((entry) => {\n const { ext, name } = parse(entry);\n return CONFIG_EXTENSIONS.includes(ext) && !name.startsWith(\".\");\n })\n .sort();\n\n for (const file of files) {\n const { name } = parse(file);\n const mod = await import(join(directory, file));\n repository.set(name, unwrap(mod));\n }\n\n return repository;\n}\n\nfunction unwrap(mod: any) {\n if (mod && typeof mod === \"object\" && \"default\" in mod) {\n return mod.default;\n }\n return mod;\n}\n"
7
7
  ],
8
8
  "mappings": ";2RAiCO,CAAe,JAAQ,EAOrB,OAMD,AAAI,EAAkB,EAmB5B,UAAU,CAAC,EAEkD,QAmBtD,OAAS,EAKX,CACH,GAAI,CAAC,KAAK,MACR,MAAU,MACR,YAAY,KAAK,0FACnB,EAGF,GAAI,CACF,OAAO,EAAI,IAAuB,EAClC,MAAO,EAAO,CACd,MAAU,MACR,qBAAqB,KAAK,6DACxB,+FACA,6CAA6C,KAAK,kDAEpD,CAAE,OAAM,CACV,SAoBG,KAAuB,CAAoB,EAA0B,CAC1E,IAAM,EAAW,IAAI,KACrB,QAAY,EAAK,KAAU,OAAO,QAAQ,CAAS,EACjD,GAAI,IAAU,OAAW,EAAS,GAAO,EAE3C,OAAO,EAEX,CCtIA,kBAAS,oBACT,eAAS,WAAM,aAIf,IAAM,EAAoB,CAAC,MAAO,OAAQ,MAAO,OAAQ,MAAM,EAMxD,SAAS,CAAsB,CACpC,EAA+B,CAAC,EACpB,CACZ,IAAM,EAA6B,CAAC,EAEpC,QAAY,EAAK,KAAQ,OAAO,QAAQ,CAAO,EAC7C,EAAM,GAAO,EAAO,CAAG,EAGzB,OAAO,IAAI,EAAW,CAAK,EAO7B,eAAsB,CAAc,CAClC,EACA,EAAa,IAAI,EACI,CACrB,IAAI,EAAoB,CAAC,EAEzB,GAAI,CACF,EAAU,MAAM,EAAQ,CAAS,EACjC,MAAO,EAAK,CACZ,OAAO,EAGT,IAAM,EAAQ,EACX,OAAO,CAAC,IAAU,CACjB,IAAQ,MAAK,QAAS,EAAM,CAAK,EACjC,OAAO,EAAkB,SAAS,CAAG,GAAK,CAAC,EAAK,WAAW,GAAG,EAC/D,EACA,KAAK,EAER,QAAW,KAAQ,EAAO,CACxB,IAAQ,QAAS,EAAM,CAAI,EACrB,EAAM,MAAa,SAAK,EAAW,CAAI,GAC7C,EAAW,IAAI,EAAM,EAAO,CAAG,CAAC,EAGlC,OAAO,EAGT,SAAS,CAAM,CAAC,EAAU,CACxB,GAAI,GAAO,OAAO,IAAQ,UAAY,YAAa,EACjD,OAAO,EAAI,QAEb,OAAO",
9
- "debugId": "0722504D2BFEB23564756E2164756E21",
9
+ "debugId": "4B40758CA8452E1F64756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ua as B,va as D}from"../chunk-3crknzwp.js";import"../chunk-342ydn4n.js";import"../chunk-fec4qnr3.js";import{Pa as J}from"../chunk-rreb2k19.js";import"../chunk-7fh7cfjh.js";import"../chunk-c7hbdsjv.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
2
+ import{ua as B,va as D}from"../chunk-7c48nxqb.js";import"../chunk-ge5m9qdt.js";import"../chunk-57n0m9fv.js";import{Pa as J}from"../chunk-wac3gv1t.js";import"../chunk-gqw25apr.js";import"../chunk-7ztbpqed.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
3
3
 
4
4
  //# debugId=54630B516034F10064756E2164756E21
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gemi",
3
- "version": "0.241.0",
3
+ "version": "0.242.1",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "author": "Enes Tufekci <enes@gemijs.dev>",
@@ -75,7 +75,7 @@
75
75
  "@azure/storage-blob": "^12.28.0",
76
76
  "react": ">=19",
77
77
  "react-dom": ">=19",
78
- "sharp": "^0.34.2",
78
+ "sharp": "^0.34.2 || ^0.35.5",
79
79
  "typescript": ">=5",
80
80
  "vite": "^8.0.0",
81
81
  "postgres": "^3.4.0"
@@ -1,10 +0,0 @@
1
- // @bun
2
- import{Ec as _3,Rc as L3,jc as f3,nc as V2,oc as w3,pc as I3,qd as O3,yc as P3}from"./chunk-4j0h4q8v.js";import{Ed as n}from"./chunk-samm4h7d.js";import{ne as l2,pe as P2,se as s3,te as t3,ue as _$,we as q$}from"./chunk-51mz612v.js";import{Ce as Z3,Ee as c3,Ge as p3,Qe as C,Re as i3,Se as l3,Ue as n3,Ve as A$,ye as E$,ze as d3}from"./chunk-6gek696n.js";import{Ye as B}from"./chunk-bhycdjcv.js";import{Ch as J$,Dh as N$,If as L$,Jf as n2,Jh as M$,Lg as z3,Nf as B2,Of as Q2,Wg as r2,Yg as o,ah as Z$,bh as e2,ch as z$,dh as G$,eg as c2,hh as g2,if as t,ih as f2,jf as U$,kf as m2,mh as w2,nh as W$,of as y3,oh as Y2,pg as F2,ph as X$,qg as d2,qh as Y$,rf as k$,rg as R,rh as v2,sf as b$,sh as Z2,ug as F$,vf as B$,vg as V$,vh as w$,wg as H$,wh as a,xh as i2,yf as I$,yg as g}from"./chunk-n30y9dc5.js";import{Cj as X2,Vi as d,ij as a2,yj as B3}from"./chunk-8z16b2j2.js";import{Ej as a3}from"./chunk-2g1h9ktj.js";import{Kj as l,Oj as T$,Pj as _2,Qj as h}from"./chunk-e4adgvd6.js";import{Yj as u}from"./chunk-0xmk4jyj.js";import{ck as p2}from"./chunk-8wvh099n.js";import{fk as O$,gk as s2,jk as I2,kk as o2,nk as D$}from"./chunk-4sv5vkab.js";import{Bk as r3,Gk as e3}from"./chunk-768yza4f.js";import{Wk as u3,Yk as c,il as W2}from"./chunk-0wa8ztk5.js";import{kl as q}from"./chunk-6wv3k8ap.js";import{ql as S$}from"./chunk-ccymw1ed.js";import{Yl as R$}from"./chunk-aczp96k5.js";import{mm as t2}from"./chunk-rc86ewq1.js";import{tm as N2,wm as k}from"./chunk-3mq0wmq7.js";import{Fm as u2}from"./chunk-vqmy8jfr.js";import{Vm as $$}from"./chunk-4mysb5ej.js";var v$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var G3=/^[A-Za-z0-9_-]{1,64}$/,h$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,W3=4000,E=1e5,m$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,j3=new WeakMap;function D9($){return j3.get($)}class s{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=i$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,u$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(U3(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(U3(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={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`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 m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new m(`"${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 U=Q.value,V={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,V),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${H}.`,404);let P={};for(let x of Y.jsonKeys)if(U[x]!==void 0)P[x]=U[x];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,V);else if(K.method==="GET")J=Z8(P);else if(Y.jsonKeys.length>0)I=P;let D=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(V)):void 0,j={...D?{credentials:D}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let x=J?`${H}?${J}`:H;T=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,x,I,j):await this.dispatcher.dispatchAs($.req,K.method,x,I)}catch(x){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,x),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await N3(Z,T);return await this.project(Y,V,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!G3.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(h$)].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((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(H3(S))o$(z,`params.${N}`,S);else V3(z,`params.${N}`,S)}let U=[],V;if(X.input){if(V=X.input.toJSONSchema(),V.type!=="object"||!V.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(V.properties)}let H=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of H)V3(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 F=J3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,D=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=l.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(H3(S)){let w=S.as??N.name;I(w,S.input),D.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let j={};for(let N of H)if(N.binder==="input")I(N.name,l.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 T=[...Object.keys(P),...H.map((N)=>N.name)];for(let N of new Set(T))if(U.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let x=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:F3(X.input,V,l.object(P)),...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}:{}}),A=!H.every((N)=>N.binder==="input")?null:H.length===0?x:Object.freeze({...x,inputSchema:F3(X.input,V,l.object(e$(P,Object.keys(j))),j)});return{kind:"route",descriptor:x,remote:A,params:K,paramBinders:J,modelParams:D,fileFields:H,jsonKeys:U,...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 U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let V=Y[U];if(V===void 0||V===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof V!=="string")K.push(`a file's "${U}" must be a string`);else Q[U]=V}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(!G3.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:J3(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(!K2(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 U=G.signal??new AbortController().signal;return Q3(X,Y.value,K3(Y3(X,Q,U,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(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(O2($),$.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 j3.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=(A,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(A,N):c$(A,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};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 X3(this.runNative($,{...K,ctx:G},G),Q)}let U=$.meta.remote,V=await this.bind($,"the remote context",()=>U.context(K));if(typeof V!=="object"||V===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,V),new O(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=Y3($,V,P,I);if(!W.approved&&K2($)&&await Q3($,K.input,K3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let D;try{D=await X3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(A){if(P.aborted&&A===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${H} ms.`,504)}if(A instanceof O)throw A;if(A instanceof n||A instanceof m)throw new O(A.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,A),new O(`"${X}" failed on the server.`,500)}let j=(A)=>{return console.error(`[gemi/mcp] "${X}" ${A}`),new O(`"${X}" failed on the server.`,500)};if(P3(D))throw j("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(A){throw j(`could not read an image it showed: ${A}`)}let x=D;if($.descriptor.outputSchema){let A=$.descriptor.outputSchema.safeParse(x);if(A.ok===!1)throw j(`answered what its output schema refuses: ${A.errors.join(", ")}`);x=A.value}for(let A of T)W.images?.(A);if(x===void 0)return null;if(typeof x==="string")return x.length>E?`${x.slice(0,E)}\u2026 [cut at ${E} of ${x.length} characters]`:x;let z2=JSON.stringify(x);if(z2!==void 0&&z2.length>E)return`${z2.slice(0,E)}\u2026 [cut at ${E} of ${z2.length} characters]`;return x}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 U=`:${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(`/${U}`,"");continue}W=W.replace(U,$8($.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,U]of Object.entries(Z))j2(K,Q,U);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))j2(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=(V)=>new O(`"${Z}" of "${$}" ${V}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!l$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!n$.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 V=W.data.replace(/\s+/g,"");if(Math.floor(V.length*3/4)-t$(V)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(V.length%4!==0||!s$.test(V))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(V,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let V=await B3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!V.ok)throw G(`could not be fetched: ${U.host} answered ${V.status}.`);let H=await V.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(V){if(V instanceof O)throw V;throw G(`could not be fetched from ${U.host}: ${V instanceof Error?V.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(v$,{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(!g$.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 N3(G,z);let X=(H,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,F);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 U=Q;if($.result)try{U=await $.result(Q,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let V=JSON.stringify(U);if(V!==void 0&&V.length>E)return`${V.slice(0,E)}\u2026 [cut at ${E} of ${V.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function u$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function d$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function X3($,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(!d$($))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 c$($,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 Y3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(V)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${V}.`,{retryable:!1})},U={put:async(V,H={})=>{if(!H.showModel)return K("attachment store")();let F=H.mimeType||V.type;if(!/^image\//i.test(F))throw new n(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=V.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(V instanceof File?V.name:"image"),mimeType:F,size:V.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(V)=>O3({...V,signal:V.signal?AbortSignal.any([z,V.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:_3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:L3(),meter:I3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function K3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Q3($,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 O2($){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 U3($,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 p$=10485760;function i$($){let Z=$?.maxBytes??p$;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 l$($){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 n$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function t$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function H3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function o$($,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 a$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function r$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function J3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?r$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!a$.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 F3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,U])=>[Q,U.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 U=[],V={};if($){let F=$.safeParse(Q);if(F.ok===!1)U.push(...F.errors);else V={...F.value}}let H=z.safeParse(Q);if(H.ok===!1)U.push(...H.errors);else V={...V,...H.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){U.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((D)=>`${F}: ${D}`));else V[F]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:V}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let U=K(Q);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function e$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function $8($,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 j2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)j2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function Z8($){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 N3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!m$.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>E)return`${W.slice(0,E)}\u2026 [cut at ${E} 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>W3?`${z.slice(0,W3)}\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 z8,randomBytes as G8,timingSafeEqual as W8}from"crypto";function D2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class X8{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`${$}${G8(32).toString("base64url")}`}static hash($){return z8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&W8(z,G)}async resolve($){let Z=D2($);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 v3,randomBytes as C3}from"crypto";async function x2($,Z){let z=Y8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function Y8(){try{let $=k();return $.bound(t)?$.make(t):null}catch{return null}}var A2=["2026-07-28"],U2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...A2,...U2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function x3($){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 K8,timingSafeEqual as Q8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!Q8(K,Q))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function A3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",S3="gemi.mcp.session.v1",U8=86400000,q3=600000,T3="gemi_approval",b2=2000,V8={limit:600,window:60},H8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=N8(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,V2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??V8,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 f3,this.approvalTimeoutMs=Z.approvalTimeoutMs??q3,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??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?F8(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 M3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return M3(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(D2($)!==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 J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),R3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),V=$.headers.get("mcp-protocol-version");if(V!==null&&V!==U.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${V} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(H,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),R3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=U2.includes(G)?G:U2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:k3(X.elicitation),p:H2(z),exp:Date.now()+U8},K=k2(S3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(S3,"gms1",z);if(!G||G.p!==H2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||x3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,D)=>{G.outcome="denied",G.reason=J,G.message=D},K=(J,D,j)=>{if(G.outcome="error",G.message=J,D!==void 0)G.status=D;if(j!==void 0)G.error=j},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let j=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(j),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let j=await this.approval($,Q,z,Y,G);if(j.kind==="answer")return j.result;G.approved=!0}}let U=P8($),V=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>V.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let j=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,j),new _(L.InvalidParams,j)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let D=`"${Z}" failed on the server.`;return K(D,void 0,J),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}let F=typeof H==="string"?H:JSON.stringify(H??null),P=Q.outputSchema&&($.era.modern||M(H))?{structuredContent:H}:{},I=[...V.length>0&&H===null?[]:[{type:"text",text:F}],...V];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,D=B8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==H2($.principal)||T.t!==Z.name||T.a!==D)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return E3(I[T3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!k3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:H2($.principal),t:Z.name,a:D,n:C3(16).toString("base64url"),exp:Date.now()+q3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[T3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",j),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${C3(12).toString("base64url")}`,V=Q.sessionId,H=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(U),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(U,{session:V,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&E3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new g3(()=>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 _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=y3(new d($,{},"api",this.endpoint.pathname)),z=await x2(`mcp-auth-failed:${Z}`,H8);return z===null?null:b3(z)}async spend($){if(!this.rateLimit)return null;let Z=await x2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:b3(Z)}}class g3{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
- data: ${JSON.stringify($)}
4
-
5
- `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class J2 extends Error{}async function J8($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new J2;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 J2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function M3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function F8($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function N8($){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 H2($){return v3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function B8($){return v3("sha256").update(w3($??{})).digest("base64url")}function k3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function R3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function I8($,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 P8($){let z=(M($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function _8($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
6
-
7
- Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function E3($){return M($)&&$.action==="accept"&&M($.content)&&$.content.approve===!0}function b3($){return v(b(null,new _(L.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function L8($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=O8($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y2($);return}let G;try{if(G=Z.locks?.()??j8(),$.onOneServer){let W=Math.floor((Z.now??Date.now())/60000);if(!await G.store.advance(`gemi:cron-tick:${$.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${$.name}; skipped it:`,W);return}if(z===void 0){await y2($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y2($,W))}catch(W){if(W instanceof u3)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 h3=300000;function O8($){if(!$)return;if($===!0)return h3;return $.expiresAfter??h3}var m3;function j8(){return m3??=new c(new d3),m3}async function y2($,Z){try{await $.onTick.call($)}catch(z){console.error(`Error executing cron job ${$.name}:`,z)}try{await $.callback.call($,Z)}catch(z){console.error(`Error in cron job ${$.name}:`,z)}try{await $.onComplete.call($)}catch(z){console.error(`Error completing cron job ${$.name}:`,z)}}class p{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,()=>$(()=>L8(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 D8}from"worker_threads";var x8=100,A8=($)=>Math.min(x8,Math.floor($/10));class C8 extends B{register(){this.app.singleton(C,()=>new C(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(c,()=>this.app.make(C).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=q(c3(),$);if($.jobs===void 0)this.app.make(C).useJobs(await s3(Z));if($.workflows===void 0){let G=await t3(z);if(G.length>0)this.app.make(C).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(C))return;let Z=this.app.make(C);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running queued job(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-A8(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 WZ($){if(q8($),Bun.env.NODE_ENV!=="production")return T8($);if(o3($))return;if(!i3())return;if(!$.bound(C))return;$.make(C).start()}function o3($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof p3}function S8($){if(o3($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(C))return!1;try{return!$.make(C).durable}catch{return!1}}function q8($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||n3())return;if(process.env.ROOT_DIR===void 0||!D8)return;if(l3()){if(!S8($))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 T8($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(C))$.make(C).start()}var M8=new Set,k8={refusal:null,apply:($)=>$,carried:null};async function K$($){let Z=k(o);if(Z.config.global.length===0)return k8;let{pathname:z}=new URL($.url),G=$$(z),W=new d($,{},G?"api":"view","");return await u.run(W,async()=>{let X=u.getStore(),{headers:Y,cookies:K}=X,Q=(U)=>{if(!g2(U)){let H=v2(U,Y,K);return G?H:E8(H,z)}let V=new Headers(Y);return V.delete("Set-Cookie"),v2(U,V,M8)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(U){let V=!G&&R8(z);if(U?.kind===a3){let H=G?Y$(U.payload.api):V?W$(U.payload.viewData??U.payload.api):w2(U.payload.view);return{refusal:Q(H),apply:Q,carried:null}}if(r3(U)&&(G||V))return{refusal:Q(X$()),apply:Q,carried:null};if(e3(U)){console.error(U);let H=G||V?z$():w2(G$());return{refusal:Q(H),apply:Q,carried:null}}throw U}finally{X.destroy()}})}function R8($){if(!$.endsWith(".json"))return!1;let Z=k().config;if(!Z.get("route.api")||!Z.get("route.view"))return!0;return k(a).viewDispatchers().every((z)=>Z$(z.flatViewRoutes,$))}function E8($,Z){if(!g2($)||$.headers.getSetCookie().length===0)return $;try{return f2($.headers,Z),$}catch{let z=new Headers($.headers);return f2(z,Z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}var b8=120,y8=2000,f8=3;class e{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||u2())return f(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return f(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(F2))return f(400,`Open the socket with the "${F2}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return f(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return f(503,"Too many connections.",{"Retry-After":"10"});let W=h8($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return f(429,"Too many connections from this address.",{"Retry-After":"30"});let X=this.reserve(W),Y=!1;try{let K=await this.authenticate($,Z,X);return Y=K===void 0,K}finally{if(!Y)this.release(X)}}async authenticate($,Z,z){let G=await K$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||u2())return f(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let V=new d($,{},"api",this.config.path);X=await u.run(V,async()=>{let H=u.getStore();try{return await J$(V)}finally{H.destroy()}},W)}catch(V){return console.error("[gemi] Resolving the session of a socket upgrade failed.",V),f(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=g8(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return f(429,"Too many connections for this user.",{"Retry-After":"30"});if(Y)z.userId=Y,this.perUser.set(Y,(this.perUser.get(Y)??0)+1);let K=H$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:V$(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":F2},data:Q}))return f(400,"The WebSocket upgrade failed.");return}checkOrigin($){let Z=$.headers.get("origin"),z=Boolean($.headers.get("cookie"));if(!Z)return z?"A socket that carries cookies must send an Origin header.":!0;return this.originAllowed(Z,$)?!0:"This origin may not open a socket."}originAllowed($,Z){let z;try{z=new URL($)}catch{return!1}if(z.protocol!=="https:"&&z.protocol!=="http:")return!1;let G=Z.headers.get("host");if(G&&z.host.toLowerCase()===G.toLowerCase())return!0;for(let W of[process.env.APP_URL,process.env.HOST_NAME,...this.config.allowedOrigins])if(W&&w8(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--,Q$(this.perIp,$.ip),Q$(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($),r($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(R.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(R.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(R.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))r($,{op:"pong"});return;case"sub":this.subscribe($,z).catch((G)=>{if(console.error("[gemi] A socket subscription failed.",G),typeof z.id==="string"&&$.data.subs.has(z.id)){let W=$.data.subs.get(z.id);if($.data.subs.delete(z.id),W.topic&&!$.data.closed)this.leave($,W.topic);if(!$.data.closed)y($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(R.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(R.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=b8)return!0;return $.close(R.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!d2.test(G)){$.close(R.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return y($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!v8(Y))return y($,G,"invalid");if(z.subs.has(G))return y($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return y($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),y($,G,"unknown_channel");let Q;for(let U=1;;U++){let V=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)<=V)break;if(U>=f8)return z.subs.delete(G),y($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),y($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(U){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,U),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);y($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;r($,{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"||!d2.test(z)){$.close(R.UnsupportedData,"An unsub needs an id.");return}let G=$.data.subs.get(z);if(!G)return;if($.data.subs.delete(z),G.topic)this.leave($,G.topic)}join($,Z){let z=$.data,G=z.topics.get(Z)??0;if(z.topics.set(Z,G+1),G===0){$.subscribe(Z);let W=this.byTopic.get(Z);if(!W){W=new Set,this.byTopic.set(Z,W);let X=Promise.resolve().then(()=>this.manager.topicAdded(Z));this.topicReady.set(Z,X),X.catch(()=>{if(this.topicReady.get(Z)===X)this.topicReady.delete(Z)})}W.add($)}return this.topicReady.get(Z)??Promise.resolve()}leave($,Z){let z=$.data,G=z.topics.get(Z)??0;if(G>1){z.topics.set(Z,G-1);return}if(z.topics.delete(Z),!z.closed)$.unsubscribe(Z);let W=this.byTopic.get(Z);if(!W)return;if(W.delete($),W.size>0)return;this.byTopic.delete(Z),this.topicReady.delete(Z),Promise.resolve().then(()=>this.manager.topicRemoved(Z)).catch((X)=>console.error(`[gemi] The broadcast driver could not unsubscribe from "${Z}".`,X))}deliver($,Z){let z=this.byTopic.get($);if(!z||!this.server)return;let G=this.config.backpressureLimit;for(let W of z)if(!W.data.closing&&W.getBufferedAmount()>G)console.warn(`[gemi] Socket closed for backpressure (1013) on "${$}".`),h2(W,R.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()*y8);setTimeout(()=>{if(!this.closing)this.applyRevocation({topic:$})},Z).unref?.()}}applyRevocation($){if("user"in $){for(let W of this.sockets)if(W.data.userId===$.user&&!W.data.closing)h2(W,R.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 U=X[Q];if(G.subs.get(Y)!==K)return;if(U.ok===!0&&U.topic===Z)return;G.subs.delete(Y),this.leave($,Z),y($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)r($,{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($){r($,{op:"bye",code:R.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),h2($,R.Restart,"Server restarting.")}run($){return N2.run(this.application,$)}}function w8($,Z){let z=/^(?:(https?):\/\/)?\*\.([^/:]+)(?::(\d+))?\/?$/i.exec($);if(z){let[,G,W,X]=z;if(G&&`${G.toLowerCase()}:`!==Z.protocol)return!1;if((X??"")!==Z.port)return!1;return Z.hostname.toLowerCase().endsWith(`.${W.toLowerCase().replace(/\.$/,"")}`)}if(/^https?:\/\//i.test($))try{return new URL($).origin===Z.origin}catch{return!1}return $.toLowerCase().replace(/\/$/,"")===Z.host.toLowerCase()}function h2($,Z,z){$.data.closing=!0,$.close(Z,z)}function r($,Z){$.send(JSON.stringify(Z))}function y($,Z,z){r($,{op:"denied",id:Z,code:z})}function f($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function v8($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function g8($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function h8($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return m2(U$(z)??z);try{let G=Z.requestIP($)?.address;return G?m2(G):null}catch{return null}}function Q$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class m8 extends B{register(){this.app.singleton(g,()=>new g(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(e,()=>new e(this.app.make(g),this.app))}boot(){let $=this.app.config.get("route.channels");if($)N$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(g).driver:void 0;u8(Z,process.env,z)}async shutdown(){if(this.app.resolved(e))this.app.make(e).shutdown();if(!this.app.resolved(g))return;await this.app.make(g).close()}}function u8($,Z=process.env,z){if(!($.driver==="redis"||z instanceof F$)||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 d8 extends B{register(){this.app.singleton(c2,()=>new c2(this.app.config.get("cache",{}),{application:this.app}))}}class c8 extends B{register(){this.app.singleton(W2,()=>new W2(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(W2))return;await this.app.make(W2).close()}}class p8 extends B{register(){this.app.singleton(i2,()=>new i2(this.app.config.get("auth",{}))),this.app.singleton(p2,()=>{let $=this.app.config.get("auth",{});return new p2({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){let $=this.app.config.get("auth",{});I$($),B$($?.emailCode??{},{warn:!0})}}var P$=!1,i8=100,l8=($)=>Math.min(i8,Math.floor($/10));class n8 extends B{register(){this.app.singleton(p,()=>new p(q(l2(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(p),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=q(l2(),Z);$.useJobs(await _$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;if(process.env.VITEST&&process.env.GEMI_SCHEDULE!=="1"){if($.jobs.length>0&&!P$)P$=!0,console.warn(`[gemi] Not starting the cron schedule (${$.jobs.length} job(s)) under vitest. Set GEMI_SCHEDULE=1 to run it.`);return}let z=this.app;if(z.bound(c))$.useLocks(()=>z.make(c));$.start((G)=>N2.run(z,G))}async shutdown($){if(!this.app.resolved(p))return;let Z=this.app.make(p);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-l8(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 $2 extends L${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return O$(this.modelName)}async load(){if(!this.available)throw new n2(this.modelName);let $=s2(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new n2(this.modelName);let G=s2(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 K5($){return $}function j$(){return{features:void 0,enabled:!0,source:new $2,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class s8 extends B{register(){this.app.singleton(B2,()=>{let $=this.app.config.get("features",{}),Z=q(j$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new $2($.model);else if($?.model!==void 0&&$.source instanceof $2&&$.source.modelName!==$.model)h.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new B2(Z,(z)=>h.warning(z))})}async boot(){let $=this.app.make(B2);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){h.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class t8 extends B{register(){this.app.singleton(t2,()=>new t2(this.app.config.get("mail",{})))}}class o8 extends B{register(){this.app.singleton(I2,()=>new I2(this.app.config.get("encryption",{})))}boot(){if(this.app.make(I2).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new o2(`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=D$();if(G.length===0)return;throw new o2(`${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 a8=Symbol.for("gemi.broadcastEvent");function x$($){return typeof $==="object"&&$!==null&&$[a8]===!0}function r8($){return`listener:${$}`}function C$($,Z){e8($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends A${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,U]=$9(K),V=k(i).rehydrate(Q,U);await new $().handle(V)}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:r8($.name),writable:!0}),Y}function e8($){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 $9($){return typeof $[0]==="string"?$:$[0]}class i{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=q(P2(),$),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?C$(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=S$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=x$($);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{k(g).broadcastEvent($)}catch(z){console.error(`The event ${Z} could not be broadcast.`,z)}}rehydrate($,Z=[]){let z=this.events[$];if(!z)throw Error(`Cannot rebuild the event "${$}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${$}"\`.`);return new z(...Z)}enqueue($,Z,z,G){if(G===void 0){console.error(`The listener ${Z.name} is queued, but ${z} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${z}.dispatch(...) or ${z}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${Z.name} could not be queued for ${z}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{k(C).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 Z9 extends B{register(){this.app.singleton(i,()=>new i(this.app.config.get("events",{})))}async boot(){let $=this.app.make(i),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=q(P2(),Z);$.useListeners(await q$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(C);for(let W of z)G.registerJob(W)}}class z9 extends B{register(){this.app.singleton(a2,()=>new a2(this.app.config.get("filesystem",{})))}}class G9 extends B{register(){this.app.singleton(r2,()=>new r2(this.app.config.get("image",{})))}}class W9 extends B{register(){this.app.instance(e2,new e2)}}class X9 extends B{register(){this.app.singleton(_2,()=>new _2(q(T$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(_2).boot()}}class Y9 extends B{register(){this.app.singleton(o,()=>new o(q(M$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(o).assertGlobalMiddleware()}}import{createHash as K9,createHmac as Q9}from"crypto";var U9=150;class $3 extends k${options;resolved;prefix;pruneEvery;pruneBatch;calls=0;pruning;constructor($={}){super();this.options=$;if(this.prefix=$.prefix??"ratelimit:",this.prefix==="")throw Error("DatabaseRateLimiter needs a prefix: its rows share the locks table.");if($.hashKeys==="")throw Error("DatabaseRateLimiter's `hashKeys` secret is empty. Pass a secret, `true` to use SECRET, or `false`.");this.pruneEvery=Math.max(0,Math.floor($.pruneEvery??1000)),this.pruneBatch=Math.max(1,Math.floor($.pruneBatch??1000))}async prune($=this.pruneBatch){let Z=this.store();return Z.pruneWindows?await Z.pruneWindows(this.prefix,$):0}async consume($){let{limit:Z,window:z}=$,G=Math.ceil($.cost??1),W=Date.now();if(G>Z)return{allowed:!1,limit:Z,remaining:0,resetAt:W+z,retryAfter:z};this.maybePrune();let X=await this.store().hit(this.nameOf($.key),Z,z,G),Y=W+X.resetInMs;if(!X.allowed)return{allowed:!1,limit:Z,remaining:0,resetAt:Y,retryAfter:Math.max(1,X.resetInMs)};let K=X.count??Z;return{allowed:!0,limit:Z,remaining:Math.max(0,Math.floor(Z-K)),resetAt:Y,retryAfter:0}}maybePrune(){if(this.pruneEvery===0||++this.calls%this.pruneEvery!==0||this.pruning)return;this.pruning=this.prune().catch(($)=>{let z={error:$ instanceof Error?$.message:String($)};try{h.error("DatabaseRateLimiter could not prune ended windows",z)}catch{console.error("[gemi] DatabaseRateLimiter could not prune ended windows",$)}}).finally(()=>{this.pruning=void 0})}store(){if(this.resolved)return this.resolved;let{store:$,table:Z}=this.options;return this.resolved=typeof $==="function"?$():$??new E$(k().make(R$),{table:Z}),this.resolved}secretProblem(){let{hashKeys:$=!0}=this.options;if($!==!0||process.env.SECRET)return;return"DatabaseRateLimiter stores its keys hashed with the app's SECRET, and SECRET is not set. Set it, pass `hashKeys: <secret>`, or `hashKeys: false` to store keys as given."}secret(){let{hashKeys:$=!0}=this.options;if($===!1)return;if(typeof $==="string")return $;let Z=this.secretProblem();if(Z)throw Error(Z);return process.env.SECRET}nameOf($){let Z=this.secret();if(Z!==void 0)return`${this.prefix}#${Q9("sha256",Z).update(`gemi:ratelimit:${$}`).digest("hex")}`;let z=`${this.prefix}${$}`;if(z.length<=U9)return z;return`${this.prefix}#${K9("sha256").update($).digest("hex")}`}}function _7($){return $}function y$(){return{driver:new b$,limit:1000,window:60}}class V9 extends B{register(){this.app.singleton(t,()=>new t(q(y$(),this.app.config.get("ratelimiter",{}))))}async boot(){if(this.checkSecret(),Bun.env.NODE_ENV!=="production")return;if(this.app.config.get("ratelimiter",{}).driver!==void 0)return;if(!this.durableQueue())return;h.warning("[gemi] The queue keeps its jobs in the database, but rate limits are counted in memory: every deploy resets them, and each instance counts on its own. Set `driver: new DatabaseRateLimiter()` (or `RedisRateLimiter`, or `InMemoryRateLimiter` to keep it) in app/config/ratelimiter.ts.")}checkSecret(){let $=this.app.config.get("ratelimiter",{}).driver;if(!($ instanceof $3))return;let Z=$.secretProblem();if(!Z)return;if(Bun.env.NODE_ENV==="production")throw Error(`[gemi] ${Z}`);h.warning(`[gemi] ${Z}`)}durableQueue(){let $=this.app.config.get("queue",{}).driver;if($==="database"||$ instanceof Z3)return!0;if(typeof $!=="function"||!this.app.bound(C))return!1;try{return this.app.make(C).driver instanceof Z3}catch{return!1}}}function M7($){return $}function f$(){return{url:process.env.REDIS_URL,options:void 0}}class H9 extends B{register(){this.app.singleton(X2,()=>new X2(q(f$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(X2))return;this.app.make(X2).close()}}function L2($,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 J9 extends B{register(){this.app.singleton(Z2,()=>new Z2(L2(this.app.config,"route.api"))),this.app.singleton(Y2,()=>new Y2(L2(this.app.config,"route.view"),this.app.config.get("auth",{}))),this.app.singleton(a,()=>new a({api:this.app.make(Z2),view:this.app.make(Y2)},{api:L2(this.app.config,"route.api"),view:L2(this.app.config,"route.view"),auth:this.app.config.get("auth",{}),domains:this.app.config.get("route.domains"),clientIpTrust:w$(process.env)})),this.app.singleton(s,()=>{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 s(new $.router,this.app.make(Z2),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton(G2,()=>{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 G2(this.app.make(s),$.remote)})}boot(){if(this.app.make(Z2),this.app.make(Y2),this.app.make(a),this.app.config.get("route.mcp"))this.app.make(s);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make(G2);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class F9 extends B{register(){this.app.singleton(z3,()=>new z3(this.app.config.get("runs",{}),{application:this.app}))}}
8
- export{v$ as sb,O as tb,m as ub,D9 as vb,s as wb,D2 as xb,X8 as yb,x2 as zb,k2 as Ab,R2 as Bb,G2 as Cb,p as Db,C8 as Eb,WZ as Fb,K$ as Gb,e as Hb,m8 as Ib,d8 as Jb,c8 as Kb,p8 as Lb,n8 as Mb,$2 as Nb,K5 as Ob,j$ as Pb,s8 as Qb,t8 as Rb,o8 as Sb,a8 as Tb,x$ as Ub,i as Vb,Z9 as Wb,z9 as Xb,G9 as Yb,W9 as Zb,X9 as _b,Y9 as $b,$3 as ac,_7 as bc,y$ as cc,V9 as dc,M7 as ec,f$ as fc,H9 as gc,J9 as hc,F9 as ic};
9
-
10
- //# debugId=CE800A552938CCC264756E2164756E21