gemi 0.138.0 → 0.139.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R as S,T as h,U as u}from"./chunk-vtc1khbm.js";import{ma as q,na as w}from"./chunk-kzdkpz04.js";import"./chunk-a22h5cby.js";import"./chunk-epvpmakp.js";import"./chunk-r3v2cnrj.js";import"./chunk-rqb52m93.js";import"./chunk-kk18xqgc.js";import"./chunk-bg0e39dk.js";import{Fi as N}from"./chunk-p2c7z2nr.js";import{Xk as y}from"./chunk-c83e4ghx.js";import{kl as C}from"./chunk-f9w78tbd.js";import"./chunk-038xtqpm.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function c(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{R as S,T as h,U as u}from"./chunk-6t38r0hf.js";import{ma as q,na as w}from"./chunk-kzdkpz04.js";import"./chunk-a22h5cby.js";import"./chunk-epvpmakp.js";import"./chunk-r3v2cnrj.js";import"./chunk-rqb52m93.js";import"./chunk-kk18xqgc.js";import"./chunk-bg0e39dk.js";import{Fi as N}from"./chunk-p2c7z2nr.js";import{Xk as y}from"./chunk-c83e4ghx.js";import{kl as C}from"./chunk-f9w78tbd.js";import"./chunk-038xtqpm.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function c(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
3
  `).split(`
4
4
  `).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
5
5
  `).trim()}function _(J){return`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ea as E}from"../chunk-8p4t8x9c.js";import{$a as p}from"../chunk-gqcmnyc8.js";import{ab as H}from"../chunk-fs4ntgdr.js";import{Bb as L,Cb as Q,Db as T,Hb as U,Ib as y,Jb as F,Kb as C,Nb as D,Ob as I,Rb as b,Ub as f,Vb as k,Wb as m,nb as g,ob as W,pb as _,qb as l,rb as P,sb as u,tb as $,ub as V,vb as q,wb as B,xb as K}from"../chunk-4wyhf6j2.js";import"../chunk-z88axcxg.js";import"../chunk-gq4fr0zn.js";import"../chunk-zvzvgrrn.js";import{Rd as h}from"../chunk-85k70cme.js";import"../chunk-46bwknb5.js";import"../chunk-skmdmqv7.js";import{Ke as n,Le as v,qg as w,re as a,se as d,ug as A,vg as R}from"../chunk-n1n7qb34.js";import"../chunk-n7576zsr.js";import"../chunk-5benn2ys.js";import"../chunk-md6wfc1h.js";import"../chunk-p2c7z2nr.js";import"../chunk-yhp70t40.js";import"../chunk-v4dp93qv.js";import{Yi as M}from"../chunk-y6gr3stt.js";import"../chunk-pv2mtg8n.js";import"../chunk-ant9ck0r.js";import"../chunk-7d26eqv1.js";import"../chunk-qfhcec6q.js";import"../chunk-ghbzre7k.js";import"../chunk-c6c7p43e.js";import"../chunk-e440f645.js";import"../chunk-80fjsb26.js";import"../chunk-z0jazehw.js";import{Pk as O,Rk as z}from"../chunk-xwmy6fby.js";import"../chunk-27xv8kty.js";import"../chunk-c83e4ghx.js";import"../chunk-z969a4nt.js";import"../chunk-aj2sr77y.js";import"../chunk-f9w78tbd.js";import"../chunk-038xtqpm.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new z;boot(){if(this.models.length>0)p(...this.models);else s();this.app.config.merge(this.config),z.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let G of this.services){let J=typeof G==="function"?new G:G,x=J.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,J),this.serviceInstances.push(J),this.serviceTokens.add(x.token)}}async waitForBoot(){await this.app.boot(),await this.bootServices(),l(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),z.getInstance()===this.app)z.setInstance(void 0);O.disable()}}function s(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
2
+ import{Ea as E}from"../chunk-8p4t8x9c.js";import{$a as p}from"../chunk-gqcmnyc8.js";import{ab as H}from"../chunk-fs4ntgdr.js";import{Bb as L,Cb as Q,Db as T,Hb as U,Ib as y,Jb as F,Kb as C,Nb as D,Ob as I,Rb as b,Ub as f,Vb as k,Wb as m,nb as g,ob as W,pb as _,qb as l,rb as P,sb as u,tb as $,ub as V,vb as q,wb as B,xb as K}from"../chunk-z76te7x6.js";import"../chunk-y4mnxgdt.js";import"../chunk-gq4fr0zn.js";import"../chunk-zvzvgrrn.js";import{Rd as h}from"../chunk-85k70cme.js";import"../chunk-46bwknb5.js";import"../chunk-skmdmqv7.js";import{Ke as n,Le as v,qg as w,re as a,se as d,ug as A,vg as R}from"../chunk-n1n7qb34.js";import"../chunk-n7576zsr.js";import"../chunk-5benn2ys.js";import"../chunk-md6wfc1h.js";import"../chunk-p2c7z2nr.js";import"../chunk-yhp70t40.js";import"../chunk-v4dp93qv.js";import{Yi as M}from"../chunk-y6gr3stt.js";import"../chunk-pv2mtg8n.js";import"../chunk-ant9ck0r.js";import"../chunk-7d26eqv1.js";import"../chunk-qfhcec6q.js";import"../chunk-ghbzre7k.js";import"../chunk-c6c7p43e.js";import"../chunk-e440f645.js";import"../chunk-80fjsb26.js";import"../chunk-z0jazehw.js";import{Pk as O,Rk as z}from"../chunk-xwmy6fby.js";import"../chunk-27xv8kty.js";import"../chunk-c83e4ghx.js";import"../chunk-z969a4nt.js";import"../chunk-aj2sr77y.js";import"../chunk-f9w78tbd.js";import"../chunk-038xtqpm.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new z;boot(){if(this.models.length>0)p(...this.models);else s();this.app.config.merge(this.config),z.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let G of this.services){let J=typeof G==="function"?new G:G,x=J.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,J),this.serviceInstances.push(J),this.serviceTokens.add(x.token)}}async waitForBoot(){await this.app.boot(),await this.bootServices(),l(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),z.getInstance()===this.app)z.setInstance(void 0);O.disable()}}function s(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
3
3
  Nested relation reads resolve a model by name, so a policy on a subclass that does not own its
4
4
  `+" name is skipped inside every include \u2014 scoped at the root, "+`unscoped in an include, with nothing
5
5
  to notice it. Declaring the modules registers each class under its own name and audits the set:
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Ca as f}from"../chunk-kk18xqgc.js";import{Da as S}from"../chunk-bg0e39dk.js";import{$k as Q,bl as Z,cl as P,dl as y,el as U,fl as A}from"../chunk-z969a4nt.js";import{jl as H}from"../chunk-aj2sr77y.js";import"../chunk-f9w78tbd.js";import{ql as F}from"../chunk-038xtqpm.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new S({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=U(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)A(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-es3mah07.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-1y6hxv30.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{W as liveness,Q as isShuttingDown,k as Server};
2
+ import{Ca as f}from"../chunk-kk18xqgc.js";import{Da as S}from"../chunk-bg0e39dk.js";import{$k as Q,bl as Z,cl as P,dl as y,el as U,fl as A}from"../chunk-z969a4nt.js";import{jl as H}from"../chunk-aj2sr77y.js";import"../chunk-f9w78tbd.js";import{ql as F}from"../chunk-038xtqpm.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new S({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=U(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)A(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-63m8s40k.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-zbdgwgfv.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{W as liveness,Q as isShuttingDown,k as Server};
3
3
 
4
4
  //# debugId=CE0255FF8AD929BD64756E2164756E21
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{cb as w8}from"../chunk-fcqx2t0p.js";import{Ab as j8,Bb as M8,Cb as L8,Db as N8,Eb as S4,Fb as Z6,Gb as k,Hb as x8,Ib as D8,Jb as F8,Kb as H8,Lb as U8,Mb as O8,Nb as S8,Ob as R8,Pb as _8,Qb as f8,Rb as k8,Sb as C8,Tb as b8,Ub as T8,Vb as I8,Wb as P8,db as PZ,eb as wZ,fb as VZ,gb as vZ,hb as qZ,ib as H4,jb as yZ,kb as N4,lb as x4,mb as V1,nb as AZ,ob as hZ,pb as Z8,tb as $8,ub as J8,vb as Q8,wb as Y8,xb as z8,yb as X8,zb as B8}from"../chunk-4wyhf6j2.js";import"../chunk-z88axcxg.js";import{Ad as W8,ld as gZ,md as EZ,nd as mZ,od as cZ,pd as uZ,qd as dZ,rd as lZ,sd as nZ,td as iZ,ud as oZ,vd as sZ,wd as aZ,xd as tZ,yd as rZ,zd as eZ}from"../chunk-gq4fr0zn.js";import{Bd as pZ}from"../chunk-zvzvgrrn.js";import{Cd as LZ,Dd as NZ,Ed as xZ,Fd as DZ,Gd as FZ,Hd as HZ,Id as UZ,Jd as OZ,Kd as SZ,Ld as RZ,Md as _Z,Nd as fZ,Od as kZ,Pd as CZ,Qd as bZ,Rd as TZ,Wd as IZ}from"../chunk-85k70cme.js";import{Xd as K8,Yd as G8}from"../chunk-46bwknb5.js";import"../chunk-skmdmqv7.js";import{$e as Z5,$f as o5,Ae as gW,Af as P5,Be as EW,Ce as mW,De as b0,Df as w5,Ee as cW,Ef as V5,Fe as uW,Ff as v5,Ge as pW,Gf as q5,He as dW,Hg as KZ,Ie as lW,If as y5,Ig as GZ,Jf as A5,Kf as h5,Lf as g5,Mf as E5,Nf as m5,Of as c5,Pf as u5,Qf as p5,Rf as d5,Wf as C,Xf as i,Yf as l5,Ze as eW,Zf as n5,_e as W5,_f as i5,af as $5,ag as s5,bf as J5,cf as Q5,cg as a5,dg as t5,ee as o0,eg as r5,fe as bW,fg as e5,ge as TW,gg as WZ,he as IW,if as D5,je as PW,jf as F5,jg as ZZ,kf as H5,kg as $Z,lf as U5,lg as JZ,me as s0,mf as O5,ne as v0,nf as S5,oe as q0,of as R5,pe as G4,pf as _5,qe as wW,qf as f5,qg as QZ,sf as k5,tf as W6,ue as VW,uf as C5,ug as YZ,ve as vW,we as qW,wg as v1,xe as yW,ye as AW,yf as b5,ze as hW,zf as T5}from"../chunk-n1n7qb34.js";import"../chunk-n7576zsr.js";import"../chunk-5benn2ys.js";import{$h as nW,Ah as K4,Bh as J4,Ch as M1,Ph as L4,Sh as t,Uh as d,Yh as Q4,Zh as L1,_h as T1,ai as iW,bi as oW,ci as sW,ri as aW,si as tW,ui as rW,wi as I1}from"../chunk-md6wfc1h.js";import"../chunk-p2c7z2nr.js";import{Gi as r}from"../chunk-yhp70t40.js";import{Oi as j5,Pi as M5,Qi as b1,Ri as L5,Si as k0,Ti as N5,Ui as x5}from"../chunk-v4dp93qv.js";import{$i as X5,_i as z5,aj as B5}from"../chunk-y6gr3stt.js";import"../chunk-pv2mtg8n.js";import{Jj as I5}from"../chunk-ant9ck0r.js";import{Lj as Y5,Mj as K5,Nj as G5}from"../chunk-7d26eqv1.js";import"../chunk-qfhcec6q.js";import"../chunk-ghbzre7k.js";import"../chunk-c6c7p43e.js";import"../chunk-e440f645.js";import{Dk as zZ,Ek as XZ,Fk as BZ,Gk as jZ,Ik as MZ}from"../chunk-80fjsb26.js";import"../chunk-z0jazehw.js";import{Sk as q}from"../chunk-xwmy6fby.js";import"../chunk-27xv8kty.js";import"../chunk-c83e4ghx.js";import"../chunk-z969a4nt.js";import"../chunk-aj2sr77y.js";import"../chunk-f9w78tbd.js";import{ql as I0}from"../chunk-038xtqpm.js";import{Buffer as T0}from"buffer";class P0 extends L1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-qk6vmvr2.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof T0?$:$ instanceof Blob||$ instanceof File?T0.from(await $.arrayBuffer()):"",{sdk:G,client:z}=await this.connect();return Z?.throwIfAborted(),await z.send(new G.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((G)=>({name:G.Key,size:G.Size??0,lastModified:G.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){Q4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let z=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(z.length>0){let X=z[0];throw Error(`S3 could not delete ${z.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Y+=K.length}return Y}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),G=T1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(G,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),G;try{G=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?J4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new t(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new d(J);throw j}let z=M1(G.ContentRange),X=Boolean(z)&&G.$metadata?.httpStatusCode===206,B=z?.total??G.ContentLength??0;return{body:G.Body.transformToWebStream(),start:z?.start??0,end:z?.end??B-1,total:B,partial:X,type:G.ContentType??"application/octet-stream",etag:G.ETag||void 0,lastModified:G.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new d(Z);throw Y}}}import{Buffer as w0}from"buffer";import{Readable as m6}from"stream";function Y4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function c6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class V0 extends L1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof w0?$:w0.from(await $.arrayBuffer()),G=await this.blob(Q,Y);return Z?.throwIfAborted(),await G.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,G,z=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&z){let H=await this.size({name:$,bucket:J}),p=K4(Q,H);if(!p)throw new t(H);K=p.start,G=p.length}else if(Q?.kind==="offset")K=Q.start,G=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(K,G,Z?{abortSignal:Z}:void 0)}catch(H){if(c6(H))throw new t(await this.size({name:$,bucket:J}));if(Y4(H))throw new d($);throw H}let B=M1(X.contentRange),j=Boolean(B),x=B?.total??X.contentLength??0,O=await u6(X);if(O instanceof ReadableStream)O=T1(O,Z);return Z?.throwIfAborted(),{body:O,start:B?.start??0,end:B?.end??x-1,total:x,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(Y4(Q))throw new d(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(Y4(Q))return;throw Q}}}async function u6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return m6.toWeb(W.readableStreamBody);return null}function p6(W){return W}var d6=`
2
+ import{cb as w8}from"../chunk-fcqx2t0p.js";import{Ab as j8,Bb as M8,Cb as L8,Db as N8,Eb as S4,Fb as Z6,Gb as k,Hb as x8,Ib as D8,Jb as F8,Kb as H8,Lb as U8,Mb as O8,Nb as S8,Ob as R8,Pb as _8,Qb as f8,Rb as k8,Sb as C8,Tb as b8,Ub as T8,Vb as I8,Wb as P8,db as PZ,eb as wZ,fb as VZ,gb as vZ,hb as qZ,ib as H4,jb as yZ,kb as N4,lb as x4,mb as V1,nb as AZ,ob as hZ,pb as Z8,tb as $8,ub as J8,vb as Q8,wb as Y8,xb as z8,yb as X8,zb as B8}from"../chunk-z76te7x6.js";import"../chunk-y4mnxgdt.js";import{Ad as W8,ld as gZ,md as EZ,nd as mZ,od as cZ,pd as uZ,qd as dZ,rd as lZ,sd as nZ,td as iZ,ud as oZ,vd as sZ,wd as aZ,xd as tZ,yd as rZ,zd as eZ}from"../chunk-gq4fr0zn.js";import{Bd as pZ}from"../chunk-zvzvgrrn.js";import{Cd as LZ,Dd as NZ,Ed as xZ,Fd as DZ,Gd as FZ,Hd as HZ,Id as UZ,Jd as OZ,Kd as SZ,Ld as RZ,Md as _Z,Nd as fZ,Od as kZ,Pd as CZ,Qd as bZ,Rd as TZ,Wd as IZ}from"../chunk-85k70cme.js";import{Xd as K8,Yd as G8}from"../chunk-46bwknb5.js";import"../chunk-skmdmqv7.js";import{$e as Z5,$f as o5,Ae as gW,Af as P5,Be as EW,Ce as mW,De as b0,Df as w5,Ee as cW,Ef as V5,Fe as uW,Ff as v5,Ge as pW,Gf as q5,He as dW,Hg as KZ,Ie as lW,If as y5,Ig as GZ,Jf as A5,Kf as h5,Lf as g5,Mf as E5,Nf as m5,Of as c5,Pf as u5,Qf as p5,Rf as d5,Wf as C,Xf as i,Yf as l5,Ze as eW,Zf as n5,_e as W5,_f as i5,af as $5,ag as s5,bf as J5,cf as Q5,cg as a5,dg as t5,ee as o0,eg as r5,fe as bW,fg as e5,ge as TW,gg as WZ,he as IW,if as D5,je as PW,jf as F5,jg as ZZ,kf as H5,kg as $Z,lf as U5,lg as JZ,me as s0,mf as O5,ne as v0,nf as S5,oe as q0,of as R5,pe as G4,pf as _5,qe as wW,qf as f5,qg as QZ,sf as k5,tf as W6,ue as VW,uf as C5,ug as YZ,ve as vW,we as qW,wg as v1,xe as yW,ye as AW,yf as b5,ze as hW,zf as T5}from"../chunk-n1n7qb34.js";import"../chunk-n7576zsr.js";import"../chunk-5benn2ys.js";import{$h as nW,Ah as K4,Bh as J4,Ch as M1,Ph as L4,Sh as t,Uh as d,Yh as Q4,Zh as L1,_h as T1,ai as iW,bi as oW,ci as sW,ri as aW,si as tW,ui as rW,wi as I1}from"../chunk-md6wfc1h.js";import"../chunk-p2c7z2nr.js";import{Gi as r}from"../chunk-yhp70t40.js";import{Oi as j5,Pi as M5,Qi as b1,Ri as L5,Si as k0,Ti as N5,Ui as x5}from"../chunk-v4dp93qv.js";import{$i as X5,_i as z5,aj as B5}from"../chunk-y6gr3stt.js";import"../chunk-pv2mtg8n.js";import{Jj as I5}from"../chunk-ant9ck0r.js";import{Lj as Y5,Mj as K5,Nj as G5}from"../chunk-7d26eqv1.js";import"../chunk-qfhcec6q.js";import"../chunk-ghbzre7k.js";import"../chunk-c6c7p43e.js";import"../chunk-e440f645.js";import{Dk as zZ,Ek as XZ,Fk as BZ,Gk as jZ,Ik as MZ}from"../chunk-80fjsb26.js";import"../chunk-z0jazehw.js";import{Sk as q}from"../chunk-xwmy6fby.js";import"../chunk-27xv8kty.js";import"../chunk-c83e4ghx.js";import"../chunk-z969a4nt.js";import"../chunk-aj2sr77y.js";import"../chunk-f9w78tbd.js";import{ql as I0}from"../chunk-038xtqpm.js";import{Buffer as T0}from"buffer";class P0 extends L1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-qk6vmvr2.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof T0?$:$ instanceof Blob||$ instanceof File?T0.from(await $.arrayBuffer()):"",{sdk:G,client:z}=await this.connect();return Z?.throwIfAborted(),await z.send(new G.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((G)=>({name:G.Key,size:G.Size??0,lastModified:G.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){Q4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let z=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(z.length>0){let X=z[0];throw Error(`S3 could not delete ${z.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Y+=K.length}return Y}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),G=T1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(G,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),G;try{G=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?J4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new t(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new d(J);throw j}let z=M1(G.ContentRange),X=Boolean(z)&&G.$metadata?.httpStatusCode===206,B=z?.total??G.ContentLength??0;return{body:G.Body.transformToWebStream(),start:z?.start??0,end:z?.end??B-1,total:B,partial:X,type:G.ContentType??"application/octet-stream",etag:G.ETag||void 0,lastModified:G.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new d(Z);throw Y}}}import{Buffer as w0}from"buffer";import{Readable as m6}from"stream";function Y4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function c6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class V0 extends L1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof w0?$:w0.from(await $.arrayBuffer()),G=await this.blob(Q,Y);return Z?.throwIfAborted(),await G.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,G,z=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&z){let H=await this.size({name:$,bucket:J}),p=K4(Q,H);if(!p)throw new t(H);K=p.start,G=p.length}else if(Q?.kind==="offset")K=Q.start,G=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(K,G,Z?{abortSignal:Z}:void 0)}catch(H){if(c6(H))throw new t(await this.size({name:$,bucket:J}));if(Y4(H))throw new d($);throw H}let B=M1(X.contentRange),j=Boolean(B),x=B?.total??X.contentLength??0,O=await u6(X);if(O instanceof ReadableStream)O=T1(O,Z);return Z?.throwIfAborted(),{body:O,start:B?.start??0,end:B?.end??x-1,total:x,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(Y4(Q))throw new d(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(Y4(Q))return;throw Q}}}async function u6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return m6.toWeb(W.readableStreamBody);return null}function p6(W){return W}var d6=`
3
3
  local currentKey = KEYS[1]
4
4
  local previousKey = KEYS[2]
5
5
  local limit = tonumber(ARGV[1])
@@ -1,4 +1,4 @@
1
- import type { AnyAgentTool, ToolContext } from "../../ai/Agent";
1
+ import type { AnyAgentTool, ToolApproval, ToolContext } from "../../ai/Agent";
2
2
  import type { User } from "../../auth/types";
3
3
  import type { ProgressSink } from "../../http/modelOriginated";
4
4
  import { type SafeFetchOptions } from "../../http/safeFetch";
@@ -402,6 +402,30 @@ export declare class McpRegistry<R extends McpRouter<any> = McpRouter<any>> {
402
402
  * rather than on the first call.
403
403
  */
404
404
  private planNative;
405
+ /**
406
+ * Whether a remote caller's call of `name` with `args` must ask the user
407
+ * first (#944): the descriptor's `requiresApproval`, unless the tool is a
408
+ * native one whose `requiresApproval` is a function, which is then asked
409
+ * with the call's parsed input and a context built by the meta's
410
+ * `remote.context`, as `execute` would build it. Fails closed: invalid
411
+ * arguments, a context that cannot be built and a function that throws all
412
+ * answer `true`.
413
+ *
414
+ * The transport asks this before eliciting, and `execute` asks the function
415
+ * again unless the call is `approved`, so a transport that skipped this
416
+ * cannot run a call the function would have asked about.
417
+ */
418
+ approvalRequired(caller: McpCaller, name: string, args: unknown, options?: {
419
+ signal?: AbortSignal;
420
+ }): Promise<boolean>;
421
+ /**
422
+ * The native tool `name`'s approval as an in-process agent sees it: the
423
+ * meta's `requiresApproval: true` asks always, else the tool's own,
424
+ * function form included (#944).
425
+ *
426
+ * @internal For `toAgentTools`.
427
+ */
428
+ nativeApproval(name: string): ToolApproval<any>;
405
429
  /**
406
430
  * The `AgentTool` registered as the native tool `name`.
407
431
  *
@@ -1 +1 @@
1
- {"version":3,"file":"McpRegistry.d.ts","sourceRoot":"","sources":["../../../services/mcp/McpRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAKhE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,4BAA4B,CAAC;AAC/E,OAAO,EAAa,KAAK,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAK,KAAK,SAAS,EAAmB,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAClF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAEV,SAAS,EAMT,SAAS,EAEV,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EACV,kBAAkB,EAElB,mBAAmB,EACpB,MAAM,8BAA8B,CAAC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,MAAM,SAAS,GACjB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;CAAE,GAC7C;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,GAAG,EAAE,WAAW,CAAC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,QAAQ,CAAC,SAAS,CAA8C;IACxE,mGAAmG;IACnG,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGpB;IACJ,yEAAyE;IACzE,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsC;gBAG5C,QAAQ,EAAE,WAAW,EACtC,MAAM,EAAE,mBAAmB,EAC3B,OAAO,GAAE;QAAE,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;KAAO;IAsD3E,gFAAgF;IAChF,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED;;;;;;;OAOG;IACG,MAAM,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IA4CpD,iEAAiE;IACjE,OAAO,CAAC,QAAQ;YAYF,IAAI;YA8DJ,QAAQ;YA8FR,MAAM;YAyBN,MAAM;IAapB,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,UAAU;IA6BlB;;;;;;;OAOG;IACH,OAAO,CAAC,OAAO;IAiBf,OAAO,CAAC,kBAAkB;YAkCZ,QAAQ;IAmEtB,OAAO,CAAC,UAAU;IAIlB;;;;;;;;;;;;OAYG;YACW,QAAQ;YAyFR,UAAU;IAaxB;;;;;OAKG;YACW,OAAO;IA4CrB,OAAO,CAAC,YAAY;IAapB;;;;OAIG;YACW,aAAa;YAMb,KAAK;CAKpB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gemi",
3
- "version": "0.138.0",
3
+ "version": "0.139.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "author": "Enes Tufekci <enes@gemijs.dev>",
@@ -1,10 +0,0 @@
1
- // @bun
2
- import{$b as S9,Ic as V9,Xb as C9,_b as Y3,cc as e,kd as H9,pc as K9,vc as Q9}from"./chunk-z88axcxg.js";import{Ad as F$,rd as d3,td as N3,wd as g9,xd as h9,yd as W$}from"./chunk-gq4fr0zn.js";import{Dd as E9,Id as b9,Kd as y9,Rd as A,Sd as f9,Td as w9,Vd as v9,Wd as H$}from"./chunk-85k70cme.js";import{Zd as N}from"./chunk-skmdmqv7.js";import{Af as Z$,Bf as r9,Bg as $$,Cf as e9,Cg as z$,De as X$,Ee as c3,Ef as w,Ie as U3,Ig as B$,Je as W3,Rf as o3,ag as t3,bf as h3,cg as n,gg as s3,hg as p9,ig as i9,je as l,me as j9,og as y3,pf as Z3,pg as l9,qe as P$,qg as G3,rg as t9,sg as s9,te as G$,tg as f3,ug as a,vf as V3,vg as I3,wf as g3,wg as u3,xf as q}from"./chunk-n1n7qb34.js";import{Nh as p,Ph as m,ci as n3,qi as Y9,ui as B3,vi as J3,wi as z3}from"./chunk-md6wfc1h.js";import{Ci as u9}from"./chunk-p2c7z2nr.js";import{Ni as v}from"./chunk-yhp70t40.js";import{Ti as m3}from"./chunk-v4dp93qv.js";import{$i as l3,Wi as Y$,Xi as p3,_i as F3,cj as Q$}from"./chunk-y6gr3stt.js";import{qj as d9,vj as c9}from"./chunk-pv2mtg8n.js";import{Lj as R9,Nj as u}from"./chunk-7d26eqv1.js";import{Oj as O}from"./chunk-qfhcec6q.js";import{Uj as J$}from"./chunk-ghbzre7k.js";import{Ik as i3}from"./chunk-80fjsb26.js";import{Pk as H3,Sk as y}from"./chunk-xwmy6fby.js";import{$k as v3}from"./chunk-z969a4nt.js";import{kl as n9}from"./chunk-f9w78tbd.js";var _$="mcp",x$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class x extends e{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var a3=/^[A-Za-z0-9_-]{1,64}$/,D$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,r3=4000,T=1e5,O$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,U9=new WeakMap;function $6($){return U9.get($)}class i{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=T$(z.files),this.featureOn=z.featureOn??W3;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,A$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(_3($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if($9(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($9(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={}){_3($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new x(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0)throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new x(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let V=Q.value,H={caller:$,req:$.req,tool:K,input:V,ctx:G},U=await this.fillPath(Y,H),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${U}`));if(F!==K.url)throw new x(`"${Z}" has nothing at ${U}.`,404);let D={};for(let I of Y.jsonKeys)if(V[I]!==void 0)D[I]=V[I];let _,P="";if(Y.fileFields.length>0)_=await this.formData(Y,D,H);else if(K.method==="GET")P=g$(D);else if(Y.jsonKeys.length>0)_=D;let k=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(H)):void 0,j={...k?{credentials:k}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},M;try{let I=P?`${U}?${P}`:U;M=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,I,_,j):await this.dispatcher.dispatchAs($.req,K.method,I,_)}catch(I){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,I),new x(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await X9(Z,M);return await this.project(Y,H,M)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!a3.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(D$)].map(([,J,C])=>({name:J,modifier:C})),Q=X.params??{};for(let J of K)if(!(J.name in Q))throw Error(`${z}: the path param "${J.name}" must be bound or declared "input".`);for(let[J,C]of Object.entries(Q)){if(!K.some((g)=>g.name===J))throw Error(`${z}: "${J}" in params is not a param of the url.`);if(z9(C))b$(z,`params.${J}`,C);else Z9(z,`params.${J}`,C)}let V=[],H;if(X.input){if(H=X.input.toJSONSchema(),H.type!=="object"||!H.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);V=Object.keys(H.properties)}let U=Object.entries(X.files??{}).map(([J,C])=>({name:J,binder:C}));for(let J of U)Z9(z,`files.${J.name}`,J.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=G9(z,G,X.annotations);if(U.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let D={},_=(J,C)=>{if(J in D)throw Error(`${z}: "${J}" is the input key of two params or files, and the model can only send one.`);D[J]=C},P=new Map,k=new Map;for(let J of K){let C=Q[J.name];if(C==="input"){let g=p.string().describe(`The ":${J.name}" segment of the url.`);_(J.name,J.modifier==="?"||J.modifier==="*"?g.optional():g)}else if(z9(C)){let g=C.as??J.name;_(g,C.input),k.set(J.name,{key:g,param:C})}else P.set(J.name,C)}let j={};for(let J of U)if(J.binder==="input")_(J.name,p.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[J.name]=this.remoteFileSchema();let M=[...Object.keys(D),...U.map((J)=>J.name)];for(let J of new Set(M))if(V.includes(J))throw Error(`${z}: "${J}" is both an input field and a param or file, and the model can only send one.`);let I=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:W9(X.input,H,p.object(D)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),r=!U.every((J)=>J.binder==="input")?null:U.length===0?I:Object.freeze({...I,inputSchema:W9(X.input,H,p.object(w$(D,Object.keys(j))),j)});return{kind:"route",descriptor:I,remote:r,params:K,paramBinders:P,modelParams:k,fileFields:U,jsonKeys:V,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let V of Object.keys(Y))if(!W.includes(V))K.push(`a file has no field "${V}"`);for(let V of W){let H=Y[V];if(H===void 0||H===null){if(V==="name"||V==="mimeType")K.push(`a file needs "${V}"`);continue}if(typeof H!=="string")K.push(`a file's "${V}" must be a string`);else Q[V]=H}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!a3.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:G9(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}}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(_3($),$.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 x(`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 U9.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 x(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(I,L3)=>{if(!W.progress)return;let r;try{r=$.meta.remote?.progress?$.meta.remote.progress(I,L3):C$(I,L3)}catch(J){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,J);return}if(r)W.progress(r)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await e3(this.runNative($,{...K,ctx:G},G),Q)}let V=$.meta.remote,H=await this.bind($,"the remote context",()=>V.context(K));if(typeof H!=="object"||H===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,H),new x(`"${X}" failed on the server.`,500);let U=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...U!==void 0?[AbortSignal.timeout(U)]:[]],D=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),_=S$($,H,D),P;try{P=await e3(this.runNative($,{...K,ctx:_},_),Q,D)}catch(I){if(D.aborted&&I===D.reason){if(W.signal?.aborted)throw new x(`"${X}" was cancelled.`,499);throw new x(`"${X}" did not finish within ${U} ms.`,504)}if(I instanceof x)throw I;if(I instanceof e||I instanceof h)throw new x(I.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,I),new x(`"${X}" failed on the server.`,500)}let k=(I)=>{return console.error(`[gemi/mcp] "${X}" ${I}`),new x(`"${X}" failed on the server.`,500)};if(K9(P))throw k("answered a job handle, and a remote call has no background jobs.");let j=P;if($.descriptor.outputSchema){let I=$.descriptor.outputSchema.safeParse(j);if(I.ok===!1)throw k(`answered what its output schema refuses: ${I.errors.join(", ")}`);j=I.value}if(j===void 0)return null;if(typeof j==="string")return j.length>T?`${j.slice(0,T)}\u2026 [cut at ${T} of ${j.length} characters]`:j;let M=JSON.stringify(j);if(M!==void 0&&M.length>T)return`${M.slice(0,T)}\u2026 [cut at ${T} of ${M.length} characters]`;return j}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new x(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let V=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new x(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${V}`,"");continue}W=W.replace(V,v$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,V]of Object.entries(Z))x3(K,Q,V);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))x3(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 x(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(H)=>new x(`"${Z}" of "${$}" ${H}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!k$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!M$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let H=W.data.replace(/\s+/g,"");if(Math.floor(H.length*3/4)-E$(H)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(H.length%4!==0||!R$.test(H))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(H,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let V;try{V=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(V.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let H=await Y9(V.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!H.ok)throw G(`could not be fetched: ${V.host} answered ${H.status}.`);let U=await H.arrayBuffer();return new File([U],W.name,{type:W.mimeType})}catch(H){if(H instanceof x)throw H;throw G(`could not be fetched from ${V.host}: ${H instanceof Error?H.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(_$,{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(!x$.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 X9(G,z);let X=(U,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${U}`);else console.error(`[gemi/mcp] "${G}" ${U}`,F);return new x(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let V=Q;if($.result)try{V=await $.result(Q,Z)}catch(U){throw X("failed in its result projection:",U)}if(W){let U=W.safeParse(V);if(U.ok===!1)throw X(`answered what its output schema refuses: ${U.errors.join(", ")}`);V=U.value}if(V===void 0)return null;let H=JSON.stringify(V);if(H!==void 0&&H.length>T)return`${H.slice(0,T)}\u2026 [cut at ${T} of ${H.length} characters]`;return V}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof e)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new x(`"${$.descriptor.name}" failed on the server.`,500)}}}function A$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function j$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function e3($,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(!j$($))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 S$($,Z,z){let G=$.descriptor.name,W=`mcp_${crypto.randomUUID()}`,X=`mcp_call_${crypto.randomUUID()}`,Y=(Q)=>async()=>{throw new e(`"${G}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},K={put:Y("attachment store"),get:Y("attachment store"),read:Y("attachment store"),file:Y("attachment store")};return{context:Z,body:{},runId:W,toolCallId:X,signal:z,step:1,depth:0,resumed:!1,attachments:K,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:Y("agent run to nest a sub-agent in"),generateImage:Y("attachment store to put an image in"),editImage:Y("attachment store to put an image in"),generate:(Q)=>H9({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:G,runId:W,toolCallId:X}}),jobs:Q9({jobs:void 0,threadId:void 0,runId:W,toolCallId:X,toolName:G,depth:0,async:$.tool.async,attachments:null}),memory:V9()}}function _3($){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 $9($,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 q$=10485760;function T$($){let Z=$?.maxBytes??q$;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 k$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var M$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,R$=/^[A-Za-z0-9+/]*={0,2}$/;function E$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function Z9($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function z9($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function b$($,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 y$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function f$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function G9($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?f$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!y$.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 W9($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,V])=>[Q,V.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let V=[],H={};if($){let F=$.safeParse(Q);if(F.ok===!1)V.push(...F.errors);else H={...F.value}}let U=z.safeParse(Q);if(U.ok===!1)V.push(...U.errors);else H={...H,...U.value};for(let[F,D]of Object.entries(G)){let _=Q[F];if(_===void 0){V.push(`"${F}" is required`);continue}let P=D.safeParse(_);if(P.ok===!1)V.push(...P.errors.map((k)=>`${F}: ${k}`));else H[F]=P.value}return V.length>0?{ok:!1,errors:V}:{ok:!0,value:H}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let V=K(Q);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function w$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function v$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new x(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function x3($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)x3($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function g$($){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 X9($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!O$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>T)return`${W.slice(0,T)}\u2026 [cut at ${T} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>r3?`${z.slice(0,r3)}\u2026`:z;throw new x(`"${$}" 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 x(`"${$}" failed on the server.`,Z.status)}import{createHash as h$,randomBytes as m$,timingSafeEqual as u$}from"crypto";function D3($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class d${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`${$}${m$(32).toString("base64url")}`}static hash($){return h$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&u$(z,G)}async resolve($){let Z=D3($);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 q9,randomBytes as B9}from"crypto";async function O3($,Z){let z=c$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function c$(){try{let $=y();return $.bound(l)?$.make(l):null}catch{return null}}var A3=["2026-07-28"],X3=["2025-11-25","2025-06-18","2025-03-26"],j3=[...A3,...X3],C3="io.modelcontextprotocol/protocolVersion",S3="io.modelcontextprotocol/clientCapabilities";var q3="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class B extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function R($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function J9($){if(Array.isArray($))throw new B(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new B(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 B(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new B(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 B(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function T3($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function S($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function F9($){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 p$,timingSafeEqual as i$}from"crypto";function k3($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${N9($,Z,G).toString("base64url")}`}function M3($,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=N9($,Z,X);if(K.length!==Q.length||!i$(K,Q))return null;let V;try{V=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof V!=="object"||V===null)return null;if(typeof V.exp!=="number"||V.exp<=G)return null;return V}function N9($,Z,z){return p$("sha256",Y3($)).update(`${Z}.${z}`).digest()}var R3="gemi.mcp.request-state.v1",P9="gemi.mcp.session.v1",l$=86400000,I9=600000,L9="gemi_approval",E3=2000,n$={limit:600,window:60},t$={limit:30,window:60};class $3{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=a$(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");if(this.resolvers=G,Y3(R3),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??n$,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 C9,this.approvalTimeoutMs=Z.approvalTimeoutMs??I9,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??W3;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(Z.host!==this.endpoint.host)return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return f(R(null,new B(L.InvalidRequest,"Origin not allowed.")),403);let G=z?o$(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 _9(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return _9(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(D3($)!==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 s$($,this.maxBodyBytes))}catch(Y){if(Y instanceof Q3)return f(R(null,new B(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return f(R(null,new B(L.ParseError,"Parse error.")),400)}let X=new m($,{},"api",this.endpoint.pathname);return await v.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof B){let K=S(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return f(R(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),f(R(null,new B(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=J9(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let _=this.session($,z),P=this.pending.get(String(W.message.id));if(P&&P.session===_.id)this.pending.delete(String(W.message.id)),P.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=S(K._meta)?K._meta:{};if(typeof Q[C3]==="string"){if(this.checkModernHeaders($,Y,Q[C3]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(_,P)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:_,signal:P}),D9(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new B(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let V=this.session($,z),H=$.headers.get("mcp-protocol-version");if(H!==null&&H!==V.state.v)throw new B(L.InvalidRequest,`MCP-Protocol-Version ${H} is not the session's ${V.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let _=K.requestId;this.inflight.get(`${V.id}:${String(_)}`)?.abort()}return new Response(null,{status:202})}let U=`${V.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(U,F);let D=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(_,P)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:V.state,sessionId:V.id},stream:_,signal:P}),D9(K)||e$(this.registry,Y,V.state),D,()=>this.inflight.delete(U))}catch(_){throw this.inflight.delete(U),_}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:j3,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)=>T3(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new B(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)=>T3(Z,!1))};case"tools/call":return await this.callTool($);default:throw new B(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[q3]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=X3.includes(G)?G:X3[0],X=S(Z.capabilities)?Z.capabilities:{},Y={v:W,e:x9(X.elicitation),p:K3(z),exp:Date.now()+l$},K=k3(P9,"gms1",Y);return f({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new B(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=M3(P9,"gms1",z);if(!G||G.p!==K3(Z))throw new B(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A3.includes(z))throw new B(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:j3,requested:z},400);let G=(Y)=>new B(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||F9(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let{params:Z,caller:z,principal:G}=$,W=Z.name;if(typeof W!=="string")throw new B(L.InvalidParams,"tools/call needs a tool name.");let X=Z.arguments??{},Y=(await this.registry.available(z,{names:[W]}))[0];if(!Y)throw new B(L.InvalidParams,`Unknown tool: ${W}`);let K=!1;if(Y.requiresApproval){let F=Y.inputSchema.safeParse(X);if(F.ok===!1)return this.toolResult($,{content:[{type:"text",text:`Invalid arguments for "${W}": ${F.errors.join(", ")}`}],isError:!0});let D=await this.approval($,Y,X);if(D.kind==="answer")return D.result;K=!0}let Q=$2($),V;try{V=await this.registry.execute(z,W,X,void 0,{approved:K,signal:$.signal,...Q?{progress:Q}:{}})}catch(F){if(F instanceof x)return this.toolResult($,{content:[{type:"text",text:F.message}],isError:!0});if(F instanceof h)throw new B(L.InvalidParams,F.reason==="unknown-tool"?`Unknown tool: ${W}`:F.message);return console.error(`[gemi/mcp] "${W}" failed for ${G.via}:${G.id}:`,F),this.toolResult($,{content:[{type:"text",text:`"${W}" failed on the server.`}],isError:!0})}let H=typeof V==="string"?V:JSON.stringify(V??null),U=Y.outputSchema&&($.era.modern||S(V))?{structuredContent:V}:{};return this.toolResult($,{content:[{type:"text",text:H}],...U,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z){let G=Z2(Z,z),W=(V)=>({kind:"answer",result:this.toolResult($,{content:[{type:"text",text:V}],isError:!0})});if($.era.modern){let V=S($.params._meta)?$.params._meta:{},H=S(V[S3])?V[S3]:{},U=S($.params.inputResponses)?$.params.inputResponses:null,F=$.params.requestState,D=r$(z);if(U&&F!==void 0){let P=M3(R3,"grs1",F);if(!P||P.p!==K3($.principal)||P.t!==Z.name||P.a!==D)throw new B(L.InvalidParams,"requestState is not valid for this call.");if(!await this.spendNonce(P.n,P.exp))throw new B(L.InvalidParams,"requestState has already been used.");return O9(U[L9])?{kind:"approved"}:W(`The user did not approve "${Z.name}", and it did not run.`)}if(!x9(H.elicitation))throw new B(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400);let _={p:K3($.principal),t:Z.name,a:D,n:B9(16).toString("base64url"),exp:Date.now()+I9};return{kind:"answer",result:{resultType:"input_required",inputRequests:{[L9]:{method:"elicitation/create",params:{mode:"form",...G}}},requestState:k3(R3,"grs1",_),_meta:{[q3]:this.serverInfo}}}}let X=$.era;if(!X.session.e||!$.stream)return W(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`);let Y=`gemi-approval-${B9(12).toString("base64url")}`,K=X.sessionId,Q=await new Promise((V)=>{let H=setTimeout(()=>{this.pending.delete(Y),V(null)},this.approvalTimeoutMs),U=(F)=>{clearTimeout(H),V(F)};this.pending.set(Y,{session:K,resolve:U}),$.signal.addEventListener("abort",()=>{this.pending.delete(Y),U(null)}),$.stream.send({jsonrpc:"2.0",id:Y,method:"elicitation/create",params:X.session.v==="2025-11-25"?{mode:"form",...G}:G})});return Q&&!Q.error&&O9(Q.result)?{kind:"approved"}:W(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return f({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new T9(()=>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 B)K.send(R($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(R($.id,new B(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 f(R(null,new B(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=j9(new m($,{},"api",this.endpoint.pathname)),z=await O3(`mcp-auth-failed:${Z}`,t$);return z===null?null:A9(z)}async spend($){if(!this.rateLimit)return null;let Z=await O3(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:A9(Z)}}class T9{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 Q3 extends Error{}async function s$($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new Q3;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 Q3;W.push(K)}return Buffer.concat(W).toString("utf8")}function f($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function _9($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function o$($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function a$($){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 K3($){return q9("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function r$($){return q9("sha256").update(S9($??{})).digest("base64url")}function x9($){if(!S($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function D9($){let Z=S($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function e$($,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 $2($){let z=(S($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function Z2($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>E3?`${z.slice(0,E3)}\u2026 (${z.length-E3} 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 O9($){return S($)&&$.action==="accept"&&S($.content)&&$.content.approve===!0}function A9($){return f(R(null,new B(L.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function z2($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=G2($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await b3($);return}let G;try{if(G=Z.locks?.()??W2(),$.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 b3($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>b3($,W))}catch(W){if(W instanceof R9)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 k9=300000;function G2($){if(!$)return;if($===!0)return k9;return $.expiresAfter??k9}var M9;function W2(){return M9??=new u(new E9),M9}async function b3($,Z){try{await $.onTick.call($)}catch(z){console.error(`Error executing cron job ${$.name}:`,z)}try{await $.callback.call($,Z)}catch(z){console.error(`Error in cron job ${$.name}:`,z)}try{await $.onComplete.call($)}catch(z){console.error(`Error completing cron job ${$.name}:`,z)}}class d{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor($){this.resolved=$.jobs}get jobs(){return[...this.resolved]}useJobs($){this.resolved=$}useLocks($){this.locks=$}start($=(Z)=>Z()){if(this.stopped=!1,this.resolved.length===0)return;let Z=globalThis.__gemiCronJobs??=new Map,z=new Map;for(let G of this.resolved){let W=new G;if(!W.name){console.error(`Cron job must have a name \u2014 ${G.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let X=z.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${G.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}z.set(W.name,G.name||"an anonymous class"),Z.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(W.name,()=>$(()=>z2(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 X2}from"worker_threads";var Y2=100,K2=($)=>Math.min(Y2,Math.floor($/10));class Q2 extends N{register(){this.app.singleton(A,()=>new A(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(u,()=>this.app.make(A).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=O(b9(),$);if($.jobs===void 0)this.app.make(A).useJobs(await g9(Z));if($.workflows===void 0){let G=await h9(z);if(G.length>0)this.app.make(A).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(A))return;let Z=this.app.make(A);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-K2(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 w6($){if(H2($),Bun.env.NODE_ENV!=="production")return U2($);if(m9($))return;if(!f9())return;if(!$.bound(A))return;$.make(A).start()}function m9($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof y9}function V2($){if(m9($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(A))return!1;try{return!$.make(A).durable}catch{return!1}}function H2($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||v9())return;if(process.env.ROOT_DIR===void 0||!X2)return;if(w9()){if(!V2($))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 U2($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(A))$.make(A).start()}function J2($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var F2=new Set,N2={refusal:null,apply:($)=>$,carried:null};async function o9($){let Z=y(n);if(Z.config.global.length===0)return N2;let{pathname:z}=new URL($.url),G=n9(z),W=new m($,{},G?"api":"view","");return await v.run(W,async()=>{let X=v.getStore(),{headers:Y,cookies:K}=X,Q=(V)=>{if(!J2(V))return f3(V,Y,K);let H=new Headers(Y);return H.delete("Set-Cookie"),f3(V,H,F2)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(V){let H=!G&&z.endsWith(".json");if(V?.kind===u9){let U=G?s9(V.payload.api):H?l9(V.payload.viewData??V.payload.api):y3(V.payload.view);return{refusal:Q(U),apply:Q,carried:null}}if(d9(V)&&(G||H))return{refusal:Q(t9()),apply:Q,carried:null};if(c9(V)){console.error(V);let U=G||H?p9():y3(i9());return{refusal:Q(U),apply:Q,carried:null}}throw V}finally{X.destroy()}})}var B2=120,P2=2000,I2=3;class s{manager;application;static token="broadcast.sockets";server=null;sockets=new Set;byTopic=new Map;topicReady=new Map;perIp=new Map;perUser=new Map;connections=0;revocationSeq=0;revokedAt=new Map;closing=!1;closed=null;onAllClosed=null;startPromise=null;constructor($,Z){this.manager=$;this.application=Z}get config(){return this.manager.config}matches($){try{return new URL($.url).pathname===this.config.path}catch{return!1}}get size(){return this.sockets.size}start($){return this.server=$,this.startPromise??=this.manager.start((Z,z)=>this.deliver(Z,z),{onGap:()=>this.onGap(),onRevoke:(Z)=>this.applyRevocation(Z)}).catch((Z)=>{this.startPromise=null,console.error("[gemi] The broadcast driver could not start; events reach no socket.",Z)}),this.startPromise}upgrade($,Z){return this.run(()=>this.tryUpgrade($,Z))}async tryUpgrade($,Z){if(this.closing||v3())return b(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return b(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(V3))return b(400,`Open the socket with the "${V3}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return b(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return b(503,"Too many connections.",{"Retry-After":"10"});let W=D2($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return b(429,"Too many connections from this address.",{"Retry-After":"30"});let X=this.reserve(W),Y=!1;try{let K=await this.authenticate($,Z,X);return Y=K===void 0,K}finally{if(!Y)this.release(X)}}async authenticate($,Z,z){let G=await o9($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||v3())return b(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let H=new m($,{},"api",this.config.path);X=await v.run(H,async()=>{let U=v.getStore();try{return await $$(H)}finally{U.destroy()}},W)}catch(H){return console.error("[gemi] Resolving the session of a socket upgrade failed.",H),b(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=x2(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return b(429,"Too many connections for this user.",{"Retry-After":"30"});if(Y)z.userId=Y,this.perUser.set(Y,(this.perUser.get(Y)??0)+1);let K=e9(),Q={gemiSocket:!0,hub:this,socketId:K,tag:r9(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":V3},data:Q}))return b(400,"The WebSocket upgrade failed.");return}checkOrigin($){let Z=$.headers.get("origin"),z=Boolean($.headers.get("cookie"));if(!Z)return z?"A socket that carries cookies must send an Origin header.":!0;return this.originAllowed(Z,$)?!0:"This origin may not open a socket."}originAllowed($,Z){let z;try{z=new URL($)}catch{return!1}if(z.protocol!=="https:"&&z.protocol!=="http:")return!1;let G=Z.headers.get("host");if(G&&z.host.toLowerCase()===G.toLowerCase())return!0;for(let W of[process.env.APP_URL,process.env.HOST_NAME,...this.config.allowedOrigins])if(W&&L2(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--,a9(this.perIp,$.ip),a9(this.perUser,$.userId)}get websocket(){return{open:($)=>$.data.hub.onOpen($),message:($,Z)=>$.data.hub.onMessage($,Z),close:($)=>$.data.hub.onClose($),...this.socketOptions()}}socketOptions(){return{maxPayloadLength:this.config.maxInboundMessageBytes,idleTimeout:this.config.idleTimeout,backpressureLimit:this.config.backpressureLimit*2,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1}}onOpen($){let Z=$.data;if(this.closing){this.sayBye($);return}this.sockets.add($),t($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(q.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(q.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(q.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))t($,{op:"pong"});return;case"sub":this.subscribe($,z).catch((G)=>{if(console.error("[gemi] A socket subscription failed.",G),typeof z.id==="string"&&$.data.subs.has(z.id)){let W=$.data.subs.get(z.id);if($.data.subs.delete(z.id),W.topic&&!$.data.closed)this.leave($,W.topic);if(!$.data.closed)E($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(q.UnsupportedData,"Unknown op.")}}onClose($){let Z=$.data;if(Z.closed)return;Z.closed=!0;for(let[,z]of Z.subs)if(z.topic)this.leave($,z.topic);if(Z.subs.clear(),this.sockets.delete($),Z.reservation)this.release(Z.reservation),Z.reservation=null;if(this.closing&&this.sockets.size===0)this.onAllClosed?.()}rateWindow($){let Z=$.data.rate,z=Date.now();if(z-Z.windowStart>=this.config.subscribeRate.windowMs)Z.windowStart=z,Z.subs=0,Z.pings=0;return Z}countSub($){let{limit:Z}=this.config.subscribeRate,z=this.rateWindow($);if(z.subs++,z.subs>Z*2)return console.warn("[gemi] Socket closed for sending too many subscribe frames (1008)."),$.close(q.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=B2)return!0;return $.close(q.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!g3.test(G)){$.close(q.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return E($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!_2(Y))return E($,G,"invalid");if(z.subs.has(G))return E($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return E($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),E($,G,"unknown_channel");let Q;for(let V=1;;V++){let H=this.revocationSeq;if(Q=await this.authorize($,K),z.closed||z.subs.get(G)!==K)return;if(Q.ok!==!0)break;if((this.revokedAt.get(Q.topic)??0)<=H)break;if(V>=I2)return z.subs.delete(G),E($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),E($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(V){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,V),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);E($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;t($,{op:"subscribed",id:G,t:Q.topic})}authorize($,Z){let z=$.data,G=this.manager.channels;if(!G)return Promise.resolve({ok:!1,code:"unknown_channel"});return this.run(()=>G.authorize(new Request(z.request.url,{headers:z.request.headers}),Z.pattern,Z.params,{carried:z.carried}))}unsubscribeFrame($,Z){let z=Z.id;if(typeof z!=="string"||!g3.test(z)){$.close(q.UnsupportedData,"An unsub needs an id.");return}let G=$.data.subs.get(z);if(!G)return;if($.data.subs.delete(z),G.topic)this.leave($,G.topic)}join($,Z){let z=$.data,G=z.topics.get(Z)??0;if(z.topics.set(Z,G+1),G===0){$.subscribe(Z);let W=this.byTopic.get(Z);if(!W){W=new Set,this.byTopic.set(Z,W);let X=Promise.resolve().then(()=>this.manager.topicAdded(Z));this.topicReady.set(Z,X),X.catch(()=>{if(this.topicReady.get(Z)===X)this.topicReady.delete(Z)})}W.add($)}return this.topicReady.get(Z)??Promise.resolve()}leave($,Z){let z=$.data,G=z.topics.get(Z)??0;if(G>1){z.topics.set(Z,G-1);return}if(z.topics.delete(Z),!z.closed)$.unsubscribe(Z);let W=this.byTopic.get(Z);if(!W)return;if(W.delete($),W.size>0)return;this.byTopic.delete(Z),this.topicReady.delete(Z),Promise.resolve().then(()=>this.manager.topicRemoved(Z)).catch((X)=>console.error(`[gemi] The broadcast driver could not unsubscribe from "${Z}".`,X))}deliver($,Z){let z=this.byTopic.get($);if(!z||!this.server)return;let G=this.config.backpressureLimit;for(let W of z)if(!W.data.closing&&W.getBufferedAmount()>G)console.warn(`[gemi] Socket closed for backpressure (1013) on "${$}".`),w3(W,q.TryAgainLater,"Too far behind; reconnect.");this.server.publish($,Z)}onGap(){this.sendAll({op:"gap"});for(let $ of this.byTopic.keys()){let Z=Math.floor(Math.random()*P2);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)w3(W,q.Revoked,"Revoked.");return}let Z=$.topic,z=++this.revocationSeq;this.revokedAt.set(Z,z);let G=this.byTopic.get(Z);if(!G)return;for(let W of G)this.reauthorize(W,Z,z)}async reauthorize($,Z,z){let G=$.data,W=[...G.subs].filter(([,Y])=>Y.topic===Z);if(W.length===0)return;$.unsubscribe(Z);let X=await Promise.all(W.map(([,Y])=>this.authorize($,Y).catch((K)=>{return console.error(`[gemi] Authorizing "${Z}" again after a revoke failed.`,K),{ok:!1,code:"revoked"}})));if(G.closed)return;if(this.revokedAt.get(Z)!==z)return;if(W.forEach(([Y,K],Q)=>{let V=X[Q];if(G.subs.get(Y)!==K)return;if(V.ok===!0&&V.topic===Z)return;G.subs.delete(Y),this.leave($,Z),E($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)t($,{op:"subscribed",id:Y,t:Z})}sendAll($){let Z=JSON.stringify($);for(let z of this.sockets)z.send(Z)}shutdown($={}){if(this.closed)return this.closed;this.closing=!0,this.closed=new Promise((G)=>{this.onAllClosed=G});let Z=[...this.sockets];if(Z.length===0)this.onAllClosed?.();if(Z.length>0)console.log(`[gemi] Closing ${Z.length} broadcast socket(s) (1012).`);for(let G of Z)this.sayBye(G);return setTimeout(()=>{for(let G of Z)try{G.terminate()}catch{}this.onAllClosed?.()},$.terminateAfterMs??2000).unref?.(),this.closed}get isClosing(){return this.closing}sayBye($){t($,{op:"bye",code:q.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),w3($,q.Restart,"Server restarting.")}run($){return H3.run(this.application,$)}}function L2($,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 w3($,Z,z){$.data.closing=!0,$.close(Z,z)}function t($,Z){$.send(JSON.stringify(Z))}function E($,Z,z){t($,{op:"denied",id:Z,code:z})}function b($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function _2($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function x2($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function D2($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return z;try{return Z.requestIP($)?.address??null}catch{return null}}function a9($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class O2 extends N{register(){this.app.singleton(w,()=>new w(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(s,()=>new s(this.app.make(w),this.app))}boot(){let $=this.app.config.get("route.channels");if($)z$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(w).driver:void 0;A2(Z,process.env,z)}async shutdown(){if(this.app.resolved(s))this.app.make(s).shutdown();if(!this.app.resolved(w))return;await this.app.make(w).close()}}function A2($,Z=process.env,z){if(!($.driver==="redis"||z instanceof Z$)||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 j2 extends N{register(){this.app.singleton(h3,()=>new h3(this.app.config.get("cache",{}),{application:this.app}))}}class C2 extends N{register(){this.app.singleton(Z3,()=>new Z3(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(Z3))return;await this.app.make(Z3).close()}}class S2 extends N{register(){this.app.singleton(u3,()=>new u3(this.app.config.get("auth",{}))),this.app.singleton(m3,()=>{let $=this.app.config.get("auth",{});return new m3({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){G$(this.app.config.get("auth",{}))}}var q2=100,T2=($)=>Math.min(q2,Math.floor($/10));class k2 extends N{register(){this.app.singleton(d,()=>new d(O(d3(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(d),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=O(d3(),Z);$.useJobs(await W$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let z=this.app;if(z.bound(u))$.useLocks(()=>z.make(u));$.start((G)=>H3.run(z,G))}async shutdown($){if(!this.app.resolved(d))return;let Z=this.app.make(d);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running cron tick(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-T2(z)));if(G.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+G.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class o extends X${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return Y$(this.modelName)}async load(){if(!this.available)throw new c3(this.modelName);let $=p3(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new c3(this.modelName);let G=p3(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 y8($){return $}function K$(){return{features:void 0,enabled:!0,source:new o,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class M2 extends N{register(){this.app.singleton(U3,()=>{let $=this.app.config.get("features",{}),Z=O(K$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new o($.model);else if($?.model!==void 0&&$.source instanceof o&&$.source.modelName!==$.model)J3.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new U3(Z,(z)=>J3.warning(z))})}async boot(){let $=this.app.make(U3);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){J3.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class R2 extends N{register(){this.app.singleton(i3,()=>new i3(this.app.config.get("mail",{})))}}class E2 extends N{register(){this.app.singleton(F3,()=>new F3(this.app.config.get("encryption",{})))}boot(){if(this.app.make(F3).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new l3(`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=Q$();if(G.length===0)return;throw new l3(`${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 b2=Symbol.for("gemi.broadcastEvent");function V$($){return typeof $==="object"&&$!==null&&$[b2]===!0}function y2($){return`listener:${$}`}function U$($,Z){f2($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends H${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,V]=w2(K),H=y(c).rehydrate(Q,V);await new $().handle(H)}onFail(K){console.error(`The listener ${$.name} threw while handling ${X} off the queue. The queue will retry it up to ${z} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${$.name} failed every one of its ${z} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,K)}};return Object.defineProperty(Y,"name",{value:y2($.name),writable:!0}),Y}function f2($){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 w2($){return typeof $[0]==="string"?$:$[0]}class c{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=O(N3(),$),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?U$(z,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:$})=>$?[$]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch($,Z){if(this.deferToCommit($,Z,!1))return;this.runListeners($,Z)}async dispatchAndWait($,Z){if(this.deferToCommit($,Z,!0))return;return this.runListeners($,Z)}deferToCommit($,Z,z){let{name:G,afterCommit:W}=$.constructor;if(!W)return!1;let X=J$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=V$($);if(G.length===0&&!W){this.warnNothingIsListening(z);return}for(let{listener:X,job:Y}of G){if(Y){this.enqueue(Y,X,z,Z);continue}try{await new X().handle($)}catch(K){console.error(`The listener ${X.name} threw while handling ${z}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",K)}}if(W)this.broadcast($,z)}broadcast($,Z){try{y(w).broadcastEvent($)}catch(z){console.error(`The event ${Z} could not be broadcast.`,z)}}rehydrate($,Z=[]){let z=this.events[$];if(!z)throw Error(`Cannot rebuild the event "${$}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${$}"\`.`);return new z(...Z)}enqueue($,Z,z,G){if(G===void 0){console.error(`The listener ${Z.name} is queued, but ${z} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${z}.dispatch(...) or ${z}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${Z.name} could not be queued for ${z}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{y(A).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 v2 extends N{register(){this.app.singleton(c,()=>new c(this.app.config.get("events",{})))}async boot(){let $=this.app.make(c),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=O(N3(),Z);$.useListeners(await F$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(A);for(let W of z)G.registerJob(W)}}class g2 extends N{register(){this.app.singleton(n3,()=>new n3(this.app.config.get("filesystem",{})))}}class h2 extends N{register(){this.app.singleton(t3,()=>new t3(this.app.config.get("image",{})))}}class m2 extends N{register(){this.app.instance(s3,new s3)}}function qZ($){return $}function N$(){let $=Bun.env.NODE_ENV==="development";return{maxFileSize:10485760,console:$,consoleFormat:$?"text":"json",onLogFileClosed:()=>{},onLogCreated:()=>{}}}class u2 extends N{register(){this.app.singleton(B3,()=>new B3(O(N$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(B3).boot()}}class d2 extends N{register(){this.app.singleton(n,()=>new n(O(B$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(n).assertGlobalMiddleware()}}function mZ($){return $}function I$(){return{driver:new P$,limit:1000,window:60}}class c2 extends N{register(){this.app.singleton(l,()=>new l(O(I$(),this.app.config.get("ratelimiter",{}))))}}function nZ($){return $}function L$(){return{url:process.env.REDIS_URL,options:void 0}}class p2 extends N{register(){this.app.singleton(z3,()=>new z3(O(L$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(z3))return;this.app.make(z3).close()}}function P3($,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 i2 extends N{register(){this.app.singleton(a,()=>new a(P3(this.app.config,"route.api"))),this.app.singleton(G3,()=>new G3(P3(this.app.config,"route.view"))),this.app.singleton(I3,()=>new I3({api:this.app.make(a),view:this.app.make(G3)},{api:P3(this.app.config,"route.api"),view:P3(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(i,()=>{let $=this.app.config.get("route.mcp");if(!$?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new i(new $.router,this.app.make(a),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton($3,()=>{let $=this.app.config.get("route.mcp");if(!$?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new $3(this.app.make(i),$.remote)})}boot(){if(this.app.make(a),this.app.make(G3),this.app.make(I3),this.app.config.get("route.mcp"))this.app.make(i);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make($3);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class l2 extends N{register(){this.app.singleton(o3,()=>new o3(this.app.config.get("runs",{}),{application:this.app}))}}
8
- export{_$ as db,x as eb,h as fb,$6 as gb,i as hb,D3 as ib,d$ as jb,O3 as kb,k3 as lb,M3 as mb,$3 as nb,d as ob,Q2 as pb,w6 as qb,o9 as rb,s as sb,O2 as tb,j2 as ub,C2 as vb,S2 as wb,k2 as xb,o as yb,y8 as zb,K$ as Ab,M2 as Bb,R2 as Cb,E2 as Db,b2 as Eb,V$ as Fb,c as Gb,v2 as Hb,g2 as Ib,h2 as Jb,m2 as Kb,qZ as Lb,N$ as Mb,u2 as Nb,d2 as Ob,mZ as Pb,I$ as Qb,c2 as Rb,nZ as Sb,L$ as Tb,p2 as Ub,i2 as Vb,l2 as Wb};
9
-
10
- //# debugId=AF30F122A4200CF064756E2164756E21