gemi 0.221.0 → 0.222.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/{chunk-8rbr4z14.js → chunk-073j13t7.js} +1 -1
  3. package/dist/{chunk-00d37bhc.js → chunk-140r27bn.js} +1 -1
  4. package/dist/{chunk-xjgfmefy.js → chunk-3b68kpz1.js} +6 -6
  5. package/dist/{chunk-xjgfmefy.js.map → chunk-3b68kpz1.js.map} +3 -3
  6. package/dist/{chunk-5neyjn6f.js → chunk-4xgjg08e.js} +1 -1
  7. package/dist/{chunk-n8m9vycp.js → chunk-7czgj8ae.js} +2 -2
  8. package/dist/{chunk-n8m9vycp.js.map → chunk-7czgj8ae.js.map} +1 -1
  9. package/dist/{chunk-t0ke72e9.js → chunk-tn8gkch4.js} +1 -1
  10. package/dist/chunk-wcj7rjfe.js +517 -0
  11. package/dist/chunk-wcj7rjfe.js.map +25 -0
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/console/run.js +1 -1
  14. package/dist/kernel/index.js +1 -1
  15. package/dist/server/index.js +1 -1
  16. package/dist/services/index.d.ts +1 -1
  17. package/dist/services/index.d.ts.map +1 -1
  18. package/dist/services/index.js +1 -1
  19. package/dist/services/queue/work.js +1 -1
  20. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts +4 -7
  21. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts.map +1 -1
  22. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +2 -7
  23. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -1
  24. package/dist/services/queue/workflow/Step.d.ts +94 -7
  25. package/dist/services/queue/workflow/Step.d.ts.map +1 -1
  26. package/dist/services/queue/workflow/Workflow.d.ts +11 -0
  27. package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
  28. package/dist/services/queue/workflow/WorkflowRuntime.d.ts +2 -0
  29. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
  30. package/dist/services/queue/workflow/WorkflowStore.d.ts +22 -6
  31. package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -1
  32. package/dist/services/queue/workflow/wire.d.ts +2 -1
  33. package/dist/services/queue/workflow/wire.d.ts.map +1 -1
  34. package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-169e9dg7.js +0 -517
  37. package/dist/chunk-169e9dg7.js.map +0 -25
  38. /package/dist/{chunk-8rbr4z14.js.map → chunk-073j13t7.js.map} +0 -0
  39. /package/dist/{chunk-00d37bhc.js.map → chunk-140r27bn.js.map} +0 -0
  40. /package/dist/{chunk-5neyjn6f.js.map → chunk-4xgjg08e.js.map} +0 -0
  41. /package/dist/{chunk-t0ke72e9.js.map → chunk-tn8gkch4.js.map} +0 -0
package/dist/ai/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,ka as A6,la as P$,ma as R6,na as E6,oa as k6,pa as T6}from"../chunk-9yascc81.js";import{$c as X6,Ac as CZ,Bc as YQ,Dc as VQ,Ec as FQ,Fc as HQ,Gc as PQ,Hc as NQ,Ic as OQ,Jc as UQ,Kc as CQ,Lc as LQ,Mc as _Q,Nc as BQ,Oc as SQ,Qc as c$,Rc as a9,Sc as t9,Tc as r9,Uc as e9,Vc as J6,Wc as $6,Xc as Q6,Yc as Z6,Zc as W6,_c as K6,ad as DJ,bd as G6,cd as eZ,dd as Y6,ed as J8,fd as V6,gd as z6,hd as D6,ic as h$,id as kJ,jc as lZ,jd as K$,kc as iZ,kd as H6,lc as g$,ld as P6,md as $8,nd as N6,od as F6,pc as gQ,pd as O6,qc as fQ,qd as U6,rc as GJ,rd as C6,sc as s9,sd as L6,tc as b,td as Z$,uc as KQ,vc as XQ,xc as GQ,yc as g,zc as UZ}from"../chunk-t0ke72e9.js";import{Gd as m,Hd as u$,Kd as dZ,Ld as nZ,Md as oZ,Nd as qJ,Od as sZ,Pd as mJ,Qd as vJ,Rd as w$,Sd as aZ,Td as tZ,Ud as pJ,Vd as rZ,_d as t,ae as a,xd as nQ,yd as A,zd as T}from"../chunk-kp7wcpx7.js";import{re as e$}from"../chunk-7xe5vd4w.js";import"../chunk-169e9dg7.js";import{Ni as I,li as qZ,oi as hZ,uj as gZ,zj as S$}from"../chunk-8gnbc9dg.js";import{Aj as vZ,Cj as uJ,Dj as cJ}from"../chunk-h1wmpa03.js";import{Mj as c}from"../chunk-t586p2g2.js";import{Oj as d9,Pj as n9,Qj as o9}from"../chunk-qs2xvc8g.js";import"../chunk-anc5v266.js";import{Xk as uZ,Yk as cZ,Zk as mZ,_k as pZ}from"../chunk-tac25cnj.js";import"../chunk-0k2r6bep.js";import{el as o,fl as s,ul as AJ}from"../chunk-0av1gyns.js";import"../chunk-zmt5kdpb.js";import"../chunk-yj7pbbnm.js";import{lm as GZ}from"../chunk-37209psn.js";import"../chunk-fqhkkpq3.js";import"../chunk-6r7956dh.js";import{Im as nJ}from"../chunk-5mrtgr7q.js";import"../chunk-3dkv4989.js";import{existsSync as z8,readdirSync as x6,readFileSync as a$}from"fs";import{isAbsolute as D8,join as CJ,relative as H8,sep as P8}from"path";var t$="prompts.json",N8=/\{\{>\s*([\w./-]+)\s*\}\}/g,n$=/\{\{(\w+)\}\}/g,F8=/^[\w-]+(\/[\w-]+)*$/,o$={dir:"app/agents",shared:"prompts"},_J={},iJ=new Map,LJ;function O8(){if(LJ===void 0){let J=CJ(nJ(),"dist","server",t$);LJ=z8(J)?JSON.parse(a$(J,"utf8")):null}return LJ??null}function U8(J){return J.replace(/\r?\n$/,"")}function s$(){return _J.cache??Bun.env.NODE_ENV==="production"}function C8(J,$){if(!F8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??_J.dir??o$.dir,Z=D8(Q)?Q:CJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:CJ($.shared??_J.shared??o$.shared,`${J}.md`);return CJ(Z,W)}function L8(J,$){let Q=C8(J,$),Z=s$()?iJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=O8()?.[H8(nJ(),Q).split(P8).join("/")];if(X!==void 0)return X}let K;try{K=U8(a$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${t$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(s$())iJ.set(Q,K);return K}function dJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return L8(J,Q).replace(N8,(Z,W)=>dJ(W,[...$,J],Q))}class r${static configure(J){_J={...J},iJ.clear(),LJ=void 0}static render(J,$={},Q={}){return dJ(J,[],Q).replace(n$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...dJ(J,[],$).matchAll(n$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class oJ extends e${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await g.sweep({limit:100})===100);}}var SJ=20,_8=300,B8=200;function $Q(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>!b(K.state)).sort(Q),...J.filter((K)=>b(K.state)).sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="waiting")X.push(`waiting for ${(K.after??[]).join(", ")} since ${BJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${BJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${BJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${JQ(K.error.message,B8)}`:"failed";X.push(`failed at ${BJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${JQ(JSON.stringify(K.summary),_8)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
2
+ import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,ka as A6,la as P$,ma as R6,na as E6,oa as k6,pa as T6}from"../chunk-9yascc81.js";import{$c as X6,Ac as CZ,Bc as YQ,Dc as VQ,Ec as FQ,Fc as HQ,Gc as PQ,Hc as NQ,Ic as OQ,Jc as UQ,Kc as CQ,Lc as LQ,Mc as _Q,Nc as BQ,Oc as SQ,Qc as c$,Rc as a9,Sc as t9,Tc as r9,Uc as e9,Vc as J6,Wc as $6,Xc as Q6,Yc as Z6,Zc as W6,_c as K6,ad as DJ,bd as G6,cd as eZ,dd as Y6,ed as J8,fd as V6,gd as z6,hd as D6,ic as h$,id as kJ,jc as lZ,jd as K$,kc as iZ,kd as H6,lc as g$,ld as P6,md as $8,nd as N6,od as F6,pc as gQ,pd as O6,qc as fQ,qd as U6,rc as GJ,rd as C6,sc as s9,sd as L6,tc as b,td as Z$,uc as KQ,vc as XQ,xc as GQ,yc as g,zc as UZ}from"../chunk-tn8gkch4.js";import{Gd as m,Hd as u$,Kd as dZ,Ld as nZ,Md as oZ,Nd as qJ,Od as sZ,Pd as mJ,Qd as vJ,Rd as w$,Sd as aZ,Td as tZ,Ud as pJ,Vd as rZ,_d as t,ae as a,xd as nQ,yd as A,zd as T}from"../chunk-kp7wcpx7.js";import{re as e$}from"../chunk-7xe5vd4w.js";import"../chunk-wcj7rjfe.js";import{Ni as I,li as qZ,oi as hZ,uj as gZ,zj as S$}from"../chunk-8gnbc9dg.js";import{Aj as vZ,Cj as uJ,Dj as cJ}from"../chunk-h1wmpa03.js";import{Mj as c}from"../chunk-t586p2g2.js";import{Oj as d9,Pj as n9,Qj as o9}from"../chunk-qs2xvc8g.js";import"../chunk-anc5v266.js";import{Xk as uZ,Yk as cZ,Zk as mZ,_k as pZ}from"../chunk-tac25cnj.js";import"../chunk-0k2r6bep.js";import{el as o,fl as s,ul as AJ}from"../chunk-0av1gyns.js";import"../chunk-zmt5kdpb.js";import"../chunk-yj7pbbnm.js";import{lm as GZ}from"../chunk-37209psn.js";import"../chunk-fqhkkpq3.js";import"../chunk-6r7956dh.js";import{Im as nJ}from"../chunk-5mrtgr7q.js";import"../chunk-3dkv4989.js";import{existsSync as z8,readdirSync as x6,readFileSync as a$}from"fs";import{isAbsolute as D8,join as CJ,relative as H8,sep as P8}from"path";var t$="prompts.json",N8=/\{\{>\s*([\w./-]+)\s*\}\}/g,n$=/\{\{(\w+)\}\}/g,F8=/^[\w-]+(\/[\w-]+)*$/,o$={dir:"app/agents",shared:"prompts"},_J={},iJ=new Map,LJ;function O8(){if(LJ===void 0){let J=CJ(nJ(),"dist","server",t$);LJ=z8(J)?JSON.parse(a$(J,"utf8")):null}return LJ??null}function U8(J){return J.replace(/\r?\n$/,"")}function s$(){return _J.cache??Bun.env.NODE_ENV==="production"}function C8(J,$){if(!F8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??_J.dir??o$.dir,Z=D8(Q)?Q:CJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:CJ($.shared??_J.shared??o$.shared,`${J}.md`);return CJ(Z,W)}function L8(J,$){let Q=C8(J,$),Z=s$()?iJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=O8()?.[H8(nJ(),Q).split(P8).join("/")];if(X!==void 0)return X}let K;try{K=U8(a$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${t$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(s$())iJ.set(Q,K);return K}function dJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return L8(J,Q).replace(N8,(Z,W)=>dJ(W,[...$,J],Q))}class r${static configure(J){_J={...J},iJ.clear(),LJ=void 0}static render(J,$={},Q={}){return dJ(J,[],Q).replace(n$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...dJ(J,[],$).matchAll(n$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class oJ extends e${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await g.sweep({limit:100})===100);}}var SJ=20,_8=300,B8=200;function $Q(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>!b(K.state)).sort(Q),...J.filter((K)=>b(K.state)).sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="waiting")X.push(`waiting for ${(K.after??[]).join(", ")} since ${BJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${BJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${BJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${JQ(K.error.message,B8)}`:"failed";X.push(`failed at ${BJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${JQ(JSON.stringify(K.summary),_8)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
3
3
  `)}function BJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function JQ(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var QQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],ZQ=20;class sJ{table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of S8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return AJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
4
4
  INSERT INTO ${this.name(Q)}
5
5
  (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as c,Z as P,aa as f,ba as l}from"./chunk-n8m9vycp.js";import{Ba as u,Ca as m}from"./chunk-fxa72ppw.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-h9nt7hm6.js";import"./chunk-ba1h9pm6.js";import"./chunk-8a3fqcf0.js";import{Ej as S}from"./chunk-h1wmpa03.js";import{qm as T}from"./chunk-swmf6w3z.js";import{Km as y}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{$ as c,Z as P,aa as f,ba as l}from"./chunk-7czgj8ae.js";import{Ba as u,Ca as m}from"./chunk-fxa72ppw.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-h9nt7hm6.js";import"./chunk-ba1h9pm6.js";import"./chunk-8a3fqcf0.js";import{Ej as S}from"./chunk-h1wmpa03.js";import{qm as T}from"./chunk-swmf6w3z.js";import{Km as y}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(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 N(J){return`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Cc as B3,Pc as P3,ic as E3,mc as H2,nc as b3,oc as N3,ud as I3,wc as F3}from"./chunk-t0ke72e9.js";import{Gd as l}from"./chunk-kp7wcpx7.js";import{he as i2,je as I2,me as i3,ne as l3,oe as F$,qe as A$}from"./chunk-xjgfmefy.js";import{Ae as u3,Ke as q,Le as d3,Me as c3,Oe as p3,Pe as D$,te as h3,ye as m3}from"./chunk-169e9dg7.js";import{Se as B}from"./chunk-qy0k2s5f.js";import{$g as g2,Af as B$,Bf as l2,Bh as C$,Dg as e2,Ff as F2,Gf as K2,Og as a2,Qg as s,Ug as r3,Vg as r2,Wg as e3,Xg as $$,Yf as d2,ah as f2,cf as t,df as Y$,eh as w2,fh as Z$,gf as R3,gh as X2,hg as J2,hh as z$,ig as u2,ih as G$,jg as k,jh as v2,kf as S$,kh as $2,mg as U$,nf as J$,ng as K$,nh as M$,og as Q$,oh as o,ph as p2,qf as N$,qg as g,uh as H$,vh as V$}from"./chunk-bs4p7dys.js";import{Ni as u,bj as o2,rj as J3,wj as x$,xj as L2,yj as B2,zj as W2}from"./chunk-8gnbc9dg.js";import{Bj as t3}from"./chunk-h1wmpa03.js";import{Mj as m}from"./chunk-t586p2g2.js";import{Pj as i}from"./chunk-qs2xvc8g.js";import{Wj as c2}from"./chunk-2y0nr525.js";import{Zj as P$,_j as n2,bk as P2,ck as s2,fk as L$}from"./chunk-p4v71qfx.js";import{tk as s3,yk as o3}from"./chunk-anc5v266.js";import{Ok as g3,Qk as d,al as G2}from"./chunk-tac25cnj.js";import{cl as S}from"./chunk-0k2r6bep.js";import{il as j$}from"./chunk-0av1gyns.js";import{bm as t2}from"./chunk-t8ygf6zj.js";import{im as N2,lm as E}from"./chunk-37209psn.js";import{um as m2}from"./chunk-6r7956dh.js";import{Km as a3}from"./chunk-55btq9c7.js";var k$="mcp",R$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class D extends l{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $3=/^[A-Za-z0-9_-]{1,64}$/,E$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z3=4000,R=1e5,b$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function J8($){return L3.get($)}class n{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=g$(z.files),this.featureOn=z.featureOn??K2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,y$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(Y3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){D2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new D(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!Y2(X))throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new D(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let H=Q.value,U={caller:$,req:$.req,tool:K,input:H,ctx:G},V=await this.fillPath(Y,U),{path:N}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(N!==K.url)throw new D(`"${Z}" has nothing at ${V}.`,404);let I={};for(let A of Y.jsonKeys)if(H[A]!==void 0)I[A]=H[A];let P,J="";if(Y.fileFields.length>0)P=await this.formData(Y,I,U);else if(K.method==="GET")J=t$(I);else if(Y.jsonKeys.length>0)P=I;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(U)):void 0,O={...j?{credentials:j}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let A=J?`${V}?${J}`:V;T=Object.keys(O).length>0?await this.dispatcher.dispatchAs($.req,K.method,A,P,O):await this.dispatcher.dispatchAs($.req,K.method,A,P)}catch(A){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,A),new D(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await V3(Z,T);return await this.project(Y,U,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(E$)].map(([,F,C])=>({name:F,modifier:C})),Q=X.params??{};for(let F of K)if(!(F.name in Q))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,C]of Object.entries(Q)){if(!K.some((w)=>w.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(Q3(C))c$(z,`params.${F}`,C);else K3(z,`params.${F}`,C)}let H=[],U;if(X.input){if(U=X.input.toJSONSchema(),U.type!=="object"||!U.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(U.properties)}let V=Object.entries(X.files??{}).map(([F,C])=>({name:F,binder:C}));for(let F of V)K3(z,`files.${F.name}`,F.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let N=H3(z,G,X.annotations);if(V.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let I={},P=(F,C)=>{if(F in I)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);I[F]=C},J=new Map,j=new Map;for(let F of K){let C=Q[F.name];if(C==="input"){let w=i.string().describe(`The ":${F.name}" segment of the url.`);P(F.name,F.modifier==="?"||F.modifier==="*"?w.optional():w)}else if(Q3(C)){let w=C.as??F.name;P(w,C.input),j.set(F.name,{key:w,param:C})}else J.set(F.name,C)}let O={};for(let F of V)if(F.binder==="input")P(F.name,i.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),O[F.name]=this.remoteFileSchema();let T=[...Object.keys(I),...V.map((F)=>F.name)];for(let F of new Set(T))if(H.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let A=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:U3(X.input,U,i.object(I)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:N,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),x=!V.every((F)=>F.binder==="input")?null:V.length===0?A:Object.freeze({...A,inputSchema:U3(X.input,U,i.object(l$(I,Object.keys(O))),O)});return{kind:"route",descriptor:A,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let H of Object.keys(Y))if(!W.includes(H))K.push(`a file has no field "${H}"`);for(let H of W){let U=Y[H];if(U===void 0||U===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof U!=="string")K.push(`a file's "${H}" must be a string`);else Q[H]=U}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:H3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!Y2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let H=G.signal??new AbortController().signal;return X3(X,Y.value,W3(G3(X,Q,H,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Y2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(D2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new D(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return L3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new D(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(x,F)=>{if(!W.progress)return;let C;try{C=$.meta.remote?.progress?$.meta.remote.progress(x,F):w$(x,F)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(C)W.progress(C)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z3(this.runNative($,{...K,ctx:G},G),Q)}let H=$.meta.remote,U=await this.bind($,"the remote context",()=>H.context(K));if(typeof U!=="object"||U===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,U),new D(`"${X}" failed on the server.`,500);let V=$.tool.timeoutMs,N=[...W.signal?[W.signal]:[],...V!==void 0?[AbortSignal.timeout(V)]:[]],I=N.length===0?new AbortController().signal:N.length===1?N[0]:AbortSignal.any(N),P=[],J=G3($,U,I,P);if(!W.approved&&Y2($)&&await X3($,K.input,W3(J)))throw new h(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await z3(this.runNative($,{...K,ctx:J},J),Q,I)}catch(x){if(I.aborted&&x===I.reason){if(W.signal?.aborted)throw new D(`"${X}" was cancelled.`,499);throw new D(`"${X}" did not finish within ${V} ms.`,504)}if(x instanceof D)throw x;if(x instanceof l||x instanceof h)throw new D(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new D(`"${X}" failed on the server.`,500)}let O=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new D(`"${X}" failed on the server.`,500)};if(F3(j))throw O("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(P)}catch(x){throw O(`could not read an image it showed: ${x}`)}let A=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(A);if(x.ok===!1)throw O(`answered what its output schema refuses: ${x.errors.join(", ")}`);A=x.value}for(let x of T)W.images?.(x);if(A===void 0)return null;if(typeof A==="string")return A.length>R?`${A.slice(0,R)}\u2026 [cut at ${R} of ${A.length} characters]`:A;let Z2=JSON.stringify(A);if(Z2!==void 0&&Z2.length>R)return`${Z2.slice(0,R)}\u2026 [cut at ${R} of ${Z2.length} characters]`;return A}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new D(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let H=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new D(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${H}`,"");continue}W=W.replace(H,n$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,H]of Object.entries(Z))O2(K,Q,H);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new D(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(U)=>new D(`"${Z}" of "${$}" ${U}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!h$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!m$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let U=W.data.replace(/\s+/g,"");if(Math.floor(U.length*3/4)-d$(U)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(U.length%4!==0||!u$.test(U))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(U,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(H.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let U=await J3(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!U.ok)throw G(`could not be fetched: ${H.host} answered ${U.status}.`);let V=await U.arrayBuffer();return new File([V],W.name,{type:W.mimeType})}catch(U){if(U instanceof D)throw U;throw G(`could not be fetched from ${H.host}: ${U instanceof Error?U.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(k$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!R$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await V3(G,z);let X=(V,N)=>{if(N===void 0)console.error(`[gemi/mcp] "${G}" ${V}`);else console.error(`[gemi/mcp] "${G}" ${V}`,N);return new D(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=Q;if($.result)try{H=await $.result(Q,Z)}catch(V){throw X("failed in its result projection:",V)}if(W){let V=W.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let U=JSON.stringify(H);if(U!==void 0&&U.length>R)return`${U.slice(0,R)}\u2026 [cut at ${R} of ${U.length} characters]`;return H}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof l)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new D(`"${$.descriptor.name}" failed on the server.`,500)}}}function y$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function f$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!f$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function w$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function G3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(U)=>async()=>{throw new l(`"${W}" was called by a remote MCP client, which has no ${U}.`,{retryable:!1})},H={put:async(U,V={})=>{if(!V.showModel)return K("attachment store")();let N=V.mimeType||U.type;if(!/^image\//i.test(N))throw new l(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${N?`"${N}"`:"a blob with no type"}.`,{retryable:!1});let I=U.arrayBuffer().then((P)=>({type:"image",data:Buffer.from(P).toString("base64"),mimeType:N}));return I.catch(()=>{}),G.push(I),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:V.name??(U instanceof File?U.name:"image"),mimeType:N,size:U.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:H,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(U)=>I3({...U,signal:U.signal?AbortSignal.any([z,U.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:B3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:N3().meter}}function Y2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function D2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Y3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var v$=10485760;function g$($){let Z=$?.maxBytes??v$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function h$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var m$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,u$=/^[A-Za-z0-9+/]*={0,2}$/;function d$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function c$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var p$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function i$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function H3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?i$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!p$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function U3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,H])=>[Q,H.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let H=[],U={};if($){let N=$.safeParse(Q);if(N.ok===!1)H.push(...N.errors);else U={...N.value}}let V=z.safeParse(Q);if(V.ok===!1)H.push(...V.errors);else U={...U,...V.value};for(let[N,I]of Object.entries(G)){let P=Q[N];if(P===void 0){H.push(`"${N}" is required`);continue}let J=I.safeParse(P);if(J.ok===!1)H.push(...J.errors.map((j)=>`${N}: ${j}`));else U[N]=J.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:U}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let H=K(Q);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function l$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function n$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new D(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function O2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function t$($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function V3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!b$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>R)return`${W.slice(0,R)}\u2026 [cut at ${R} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>Z3?`${z.slice(0,Z3)}\u2026`:z;throw new D(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new D(`"${$}" failed on the server.`,Z.status)}import{createHash as s$,randomBytes as o$,timingSafeEqual as a$}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class r${options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${o$(32).toString("base64url")}`}static hash($){return s$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&a$(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as y3,randomBytes as j3}from"crypto";async function A2($,Z){let z=e$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function e$(){try{let $=E();return $.bound(t)?$.make(t):null}catch{return null}}var x2=["2026-07-28"],Q2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...Q2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",_={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _3($){if(Array.isArray($))throw new L(_.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(_.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new L(_.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(_.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new L(_.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as $6,timingSafeEqual as Z6}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=O3($,Z,X);if(K.length!==Q.length||!Z6(K,Q))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=G)return null;return H}function O3($,Z,z){return $6("sha256",H2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",A3="gemi.mcp.session.v1",z6=86400000,x3=600000,C3="gemi_approval",b2=2000,G6={limit:600,window:60},W6={limit:30,window:60};class z2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=K6(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,H2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??G6,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new E3,this.approvalTimeoutMs=Z.approvalTimeoutMs??x3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??K2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new L(_.InvalidRequest,"Origin not allowed.")),403);let G=z?Y6(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return S3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await X6($,this.maxBodyBytes))}catch(Y){if(Y instanceof V2)return v(b(null,new L(_.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new L(_.ParseError,"Parse error.")),400)}let X=new u($,{},"api",this.endpoint.pathname);return await m.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new L(_.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let P=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===P.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:J}),T3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(_.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let H=this.session($,z),U=$.headers.get("mcp-protocol-version");if(U!==null&&U!==H.state.v)throw new L(_.InvalidRequest,`MCP-Protocol-Version ${U} is not the session's ${H.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,N=new AbortController;this.inflight.set(V,N);let I=AbortSignal.any([N.signal,$.signal]);try{return await this.respond(Y,async(P,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:J}),T3(K)||H6(this.registry,Y,H.state),I,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Q2.includes(G)?G:Q2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q3(X.elicitation),p:U2(z),exp:Date.now()+z6},K=k2(A3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(_.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(A3,"gms1",z);if(!G||G.p!==U2(Z))throw new L(_.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new L(_.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new L(_.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||D3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new L(_.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,j)=>{G.outcome="denied",G.reason=J,G.message=j},K=(J,j,O)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(O!==void 0)G.error=O},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(_.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let O=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(O),this.toolResult($,{content:[{type:"text",text:O}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let O=await this.approval($,Q,z,Y,G);if(O.kind==="answer")return O.result;G.approved=!0}}let H=U6($),U=[],V;try{V=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>U.push(J),...H?{progress:H}:{}})}catch(J){if(J instanceof D){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof h){let O=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,O),new L(_.InvalidParams,O)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let j=`"${Z}" failed on the server.`;return K(j,void 0,J),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}let N=typeof V==="string"?V:JSON.stringify(V??null),I=Q.outputSchema&&($.era.modern||M(V))?{structuredContent:V}:{},P=[...U.length>0&&V===null?[]:[{type:"text",text:N}],...U];return G.outcome="ok",this.toolResult($,{content:P,...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=V6(Z,z),Y=(N,I="approval-declined")=>{return G(I,N),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}},K=(N,I)=>{return G(N,I.message),I};if($.era.modern){let N=M($.params._meta)?$.params._meta:{},I=M(N[q2])?N[q2]:{},P=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=Q6(z);if(P&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==U2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new L(_.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new L(_.InvalidParams,"requestState has already been used."));return M3(P[C3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q3(I.elicitation))throw K("approval-unavailable",new L(_.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let O={p:U2($.principal),t:Z.name,a:j,n:j3(16).toString("base64url"),exp:Date.now()+x3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",O),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let H=`gemi-approval-${j3(12).toString("base64url")}`,U=Q.sessionId,V=await new Promise((N)=>{let I=setTimeout(()=>{this.pending.delete(H),N(null)},this.approvalTimeoutMs),P=(J)=>{clearTimeout(I),N(J)};this.pending.set(H,{session:U,resolve:P}),$.signal.addEventListener("abort",()=>{this.pending.delete(H),P(null)}),$.stream.send({jsonrpc:"2.0",id:H,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return V&&!V.error&&M3(V.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new L(_.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new L(_.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R3(new u($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,W6);return z===null?null:k3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:k3(Z)}}class f3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
2
+ import{Cc as B3,Pc as P3,ic as E3,mc as H2,nc as b3,oc as N3,ud as I3,wc as F3}from"./chunk-tn8gkch4.js";import{Gd as l}from"./chunk-kp7wcpx7.js";import{he as i2,je as I2,me as i3,ne as l3,oe as F$,qe as A$}from"./chunk-3b68kpz1.js";import{Ae as u3,Ke as q,Le as d3,Me as c3,Oe as p3,Pe as D$,te as h3,ye as m3}from"./chunk-wcj7rjfe.js";import{Se as B}from"./chunk-qy0k2s5f.js";import{$g as g2,Af as B$,Bf as l2,Bh as C$,Dg as e2,Ff as F2,Gf as K2,Og as a2,Qg as s,Ug as r3,Vg as r2,Wg as e3,Xg as $$,Yf as d2,ah as f2,cf as t,df as Y$,eh as w2,fh as Z$,gf as R3,gh as X2,hg as J2,hh as z$,ig as u2,ih as G$,jg as k,jh as v2,kf as S$,kh as $2,mg as U$,nf as J$,ng as K$,nh as M$,og as Q$,oh as o,ph as p2,qf as N$,qg as g,uh as H$,vh as V$}from"./chunk-bs4p7dys.js";import{Ni as u,bj as o2,rj as J3,wj as x$,xj as L2,yj as B2,zj as W2}from"./chunk-8gnbc9dg.js";import{Bj as t3}from"./chunk-h1wmpa03.js";import{Mj as m}from"./chunk-t586p2g2.js";import{Pj as i}from"./chunk-qs2xvc8g.js";import{Wj as c2}from"./chunk-2y0nr525.js";import{Zj as P$,_j as n2,bk as P2,ck as s2,fk as L$}from"./chunk-p4v71qfx.js";import{tk as s3,yk as o3}from"./chunk-anc5v266.js";import{Ok as g3,Qk as d,al as G2}from"./chunk-tac25cnj.js";import{cl as S}from"./chunk-0k2r6bep.js";import{il as j$}from"./chunk-0av1gyns.js";import{bm as t2}from"./chunk-t8ygf6zj.js";import{im as N2,lm as E}from"./chunk-37209psn.js";import{um as m2}from"./chunk-6r7956dh.js";import{Km as a3}from"./chunk-55btq9c7.js";var k$="mcp",R$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class D extends l{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $3=/^[A-Za-z0-9_-]{1,64}$/,E$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z3=4000,R=1e5,b$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function J8($){return L3.get($)}class n{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=g$(z.files),this.featureOn=z.featureOn??K2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,y$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(Y3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){D2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new D(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!Y2(X))throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new D(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let H=Q.value,U={caller:$,req:$.req,tool:K,input:H,ctx:G},V=await this.fillPath(Y,U),{path:N}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(N!==K.url)throw new D(`"${Z}" has nothing at ${V}.`,404);let I={};for(let A of Y.jsonKeys)if(H[A]!==void 0)I[A]=H[A];let P,J="";if(Y.fileFields.length>0)P=await this.formData(Y,I,U);else if(K.method==="GET")J=t$(I);else if(Y.jsonKeys.length>0)P=I;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(U)):void 0,O={...j?{credentials:j}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let A=J?`${V}?${J}`:V;T=Object.keys(O).length>0?await this.dispatcher.dispatchAs($.req,K.method,A,P,O):await this.dispatcher.dispatchAs($.req,K.method,A,P)}catch(A){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,A),new D(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await V3(Z,T);return await this.project(Y,U,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(E$)].map(([,F,C])=>({name:F,modifier:C})),Q=X.params??{};for(let F of K)if(!(F.name in Q))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,C]of Object.entries(Q)){if(!K.some((w)=>w.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(Q3(C))c$(z,`params.${F}`,C);else K3(z,`params.${F}`,C)}let H=[],U;if(X.input){if(U=X.input.toJSONSchema(),U.type!=="object"||!U.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(U.properties)}let V=Object.entries(X.files??{}).map(([F,C])=>({name:F,binder:C}));for(let F of V)K3(z,`files.${F.name}`,F.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let N=H3(z,G,X.annotations);if(V.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let I={},P=(F,C)=>{if(F in I)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);I[F]=C},J=new Map,j=new Map;for(let F of K){let C=Q[F.name];if(C==="input"){let w=i.string().describe(`The ":${F.name}" segment of the url.`);P(F.name,F.modifier==="?"||F.modifier==="*"?w.optional():w)}else if(Q3(C)){let w=C.as??F.name;P(w,C.input),j.set(F.name,{key:w,param:C})}else J.set(F.name,C)}let O={};for(let F of V)if(F.binder==="input")P(F.name,i.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),O[F.name]=this.remoteFileSchema();let T=[...Object.keys(I),...V.map((F)=>F.name)];for(let F of new Set(T))if(H.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let A=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:U3(X.input,U,i.object(I)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:N,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),x=!V.every((F)=>F.binder==="input")?null:V.length===0?A:Object.freeze({...A,inputSchema:U3(X.input,U,i.object(l$(I,Object.keys(O))),O)});return{kind:"route",descriptor:A,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let H of Object.keys(Y))if(!W.includes(H))K.push(`a file has no field "${H}"`);for(let H of W){let U=Y[H];if(U===void 0||U===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof U!=="string")K.push(`a file's "${H}" must be a string`);else Q[H]=U}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:H3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!Y2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let H=G.signal??new AbortController().signal;return X3(X,Y.value,W3(G3(X,Q,H,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Y2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(D2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new D(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return L3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new D(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(x,F)=>{if(!W.progress)return;let C;try{C=$.meta.remote?.progress?$.meta.remote.progress(x,F):w$(x,F)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(C)W.progress(C)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z3(this.runNative($,{...K,ctx:G},G),Q)}let H=$.meta.remote,U=await this.bind($,"the remote context",()=>H.context(K));if(typeof U!=="object"||U===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,U),new D(`"${X}" failed on the server.`,500);let V=$.tool.timeoutMs,N=[...W.signal?[W.signal]:[],...V!==void 0?[AbortSignal.timeout(V)]:[]],I=N.length===0?new AbortController().signal:N.length===1?N[0]:AbortSignal.any(N),P=[],J=G3($,U,I,P);if(!W.approved&&Y2($)&&await X3($,K.input,W3(J)))throw new h(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await z3(this.runNative($,{...K,ctx:J},J),Q,I)}catch(x){if(I.aborted&&x===I.reason){if(W.signal?.aborted)throw new D(`"${X}" was cancelled.`,499);throw new D(`"${X}" did not finish within ${V} ms.`,504)}if(x instanceof D)throw x;if(x instanceof l||x instanceof h)throw new D(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new D(`"${X}" failed on the server.`,500)}let O=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new D(`"${X}" failed on the server.`,500)};if(F3(j))throw O("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(P)}catch(x){throw O(`could not read an image it showed: ${x}`)}let A=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(A);if(x.ok===!1)throw O(`answered what its output schema refuses: ${x.errors.join(", ")}`);A=x.value}for(let x of T)W.images?.(x);if(A===void 0)return null;if(typeof A==="string")return A.length>R?`${A.slice(0,R)}\u2026 [cut at ${R} of ${A.length} characters]`:A;let Z2=JSON.stringify(A);if(Z2!==void 0&&Z2.length>R)return`${Z2.slice(0,R)}\u2026 [cut at ${R} of ${Z2.length} characters]`;return A}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new D(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let H=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new D(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${H}`,"");continue}W=W.replace(H,n$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,H]of Object.entries(Z))O2(K,Q,H);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new D(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(U)=>new D(`"${Z}" of "${$}" ${U}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!h$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!m$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let U=W.data.replace(/\s+/g,"");if(Math.floor(U.length*3/4)-d$(U)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(U.length%4!==0||!u$.test(U))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(U,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(H.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let U=await J3(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!U.ok)throw G(`could not be fetched: ${H.host} answered ${U.status}.`);let V=await U.arrayBuffer();return new File([V],W.name,{type:W.mimeType})}catch(U){if(U instanceof D)throw U;throw G(`could not be fetched from ${H.host}: ${U instanceof Error?U.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(k$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!R$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await V3(G,z);let X=(V,N)=>{if(N===void 0)console.error(`[gemi/mcp] "${G}" ${V}`);else console.error(`[gemi/mcp] "${G}" ${V}`,N);return new D(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=Q;if($.result)try{H=await $.result(Q,Z)}catch(V){throw X("failed in its result projection:",V)}if(W){let V=W.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let U=JSON.stringify(H);if(U!==void 0&&U.length>R)return`${U.slice(0,R)}\u2026 [cut at ${R} of ${U.length} characters]`;return H}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof l)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new D(`"${$.descriptor.name}" failed on the server.`,500)}}}function y$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function f$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!f$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function w$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function G3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(U)=>async()=>{throw new l(`"${W}" was called by a remote MCP client, which has no ${U}.`,{retryable:!1})},H={put:async(U,V={})=>{if(!V.showModel)return K("attachment store")();let N=V.mimeType||U.type;if(!/^image\//i.test(N))throw new l(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${N?`"${N}"`:"a blob with no type"}.`,{retryable:!1});let I=U.arrayBuffer().then((P)=>({type:"image",data:Buffer.from(P).toString("base64"),mimeType:N}));return I.catch(()=>{}),G.push(I),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:V.name??(U instanceof File?U.name:"image"),mimeType:N,size:U.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:H,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(U)=>I3({...U,signal:U.signal?AbortSignal.any([z,U.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:B3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:N3().meter}}function Y2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function D2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Y3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var v$=10485760;function g$($){let Z=$?.maxBytes??v$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function h$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var m$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,u$=/^[A-Za-z0-9+/]*={0,2}$/;function d$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function c$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var p$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function i$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function H3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?i$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!p$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function U3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,H])=>[Q,H.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let H=[],U={};if($){let N=$.safeParse(Q);if(N.ok===!1)H.push(...N.errors);else U={...N.value}}let V=z.safeParse(Q);if(V.ok===!1)H.push(...V.errors);else U={...U,...V.value};for(let[N,I]of Object.entries(G)){let P=Q[N];if(P===void 0){H.push(`"${N}" is required`);continue}let J=I.safeParse(P);if(J.ok===!1)H.push(...J.errors.map((j)=>`${N}: ${j}`));else U[N]=J.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:U}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let H=K(Q);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function l$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function n$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new D(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function O2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function t$($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function V3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!b$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>R)return`${W.slice(0,R)}\u2026 [cut at ${R} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>Z3?`${z.slice(0,Z3)}\u2026`:z;throw new D(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new D(`"${$}" failed on the server.`,Z.status)}import{createHash as s$,randomBytes as o$,timingSafeEqual as a$}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class r${options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${o$(32).toString("base64url")}`}static hash($){return s$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&a$(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as y3,randomBytes as j3}from"crypto";async function A2($,Z){let z=e$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function e$(){try{let $=E();return $.bound(t)?$.make(t):null}catch{return null}}var x2=["2026-07-28"],Q2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...Q2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",_={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _3($){if(Array.isArray($))throw new L(_.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(_.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new L(_.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(_.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new L(_.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as $6,timingSafeEqual as Z6}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=O3($,Z,X);if(K.length!==Q.length||!Z6(K,Q))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=G)return null;return H}function O3($,Z,z){return $6("sha256",H2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",A3="gemi.mcp.session.v1",z6=86400000,x3=600000,C3="gemi_approval",b2=2000,G6={limit:600,window:60},W6={limit:30,window:60};class z2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=K6(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,H2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??G6,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new E3,this.approvalTimeoutMs=Z.approvalTimeoutMs??x3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??K2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new L(_.InvalidRequest,"Origin not allowed.")),403);let G=z?Y6(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return S3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await X6($,this.maxBodyBytes))}catch(Y){if(Y instanceof V2)return v(b(null,new L(_.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new L(_.ParseError,"Parse error.")),400)}let X=new u($,{},"api",this.endpoint.pathname);return await m.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new L(_.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let P=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===P.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(P,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:P,signal:J}),T3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(_.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let H=this.session($,z),U=$.headers.get("mcp-protocol-version");if(U!==null&&U!==H.state.v)throw new L(_.InvalidRequest,`MCP-Protocol-Version ${U} is not the session's ${H.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let P=K.requestId;this.inflight.get(`${H.id}:${String(P)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,N=new AbortController;this.inflight.set(V,N);let I=AbortSignal.any([N.signal,$.signal]);try{return await this.respond(Y,async(P,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:P,signal:J}),T3(K)||H6(this.registry,Y,H.state),I,()=>this.inflight.delete(V))}catch(P){throw this.inflight.delete(V),P}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(_.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Q2.includes(G)?G:Q2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q3(X.elicitation),p:U2(z),exp:Date.now()+z6},K=k2(A3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(_.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(A3,"gms1",z);if(!G||G.p!==U2(Z))throw new L(_.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new L(_.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new L(_.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||D3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new L(_.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,j)=>{G.outcome="denied",G.reason=J,G.message=j},K=(J,j,O)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(O!==void 0)G.error=O},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(_.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let O=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(O),this.toolResult($,{content:[{type:"text",text:O}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let O=await this.approval($,Q,z,Y,G);if(O.kind==="answer")return O.result;G.approved=!0}}let H=U6($),U=[],V;try{V=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>U.push(J),...H?{progress:H}:{}})}catch(J){if(J instanceof D){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof h){let O=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,O),new L(_.InvalidParams,O)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let j=`"${Z}" failed on the server.`;return K(j,void 0,J),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}let N=typeof V==="string"?V:JSON.stringify(V??null),I=Q.outputSchema&&($.era.modern||M(V))?{structuredContent:V}:{},P=[...U.length>0&&V===null?[]:[{type:"text",text:N}],...U];return G.outcome="ok",this.toolResult($,{content:P,...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=V6(Z,z),Y=(N,I="approval-declined")=>{return G(I,N),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}},K=(N,I)=>{return G(N,I.message),I};if($.era.modern){let N=M($.params._meta)?$.params._meta:{},I=M(N[q2])?N[q2]:{},P=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=Q6(z);if(P&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==U2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new L(_.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new L(_.InvalidParams,"requestState has already been used."));return M3(P[C3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q3(I.elicitation))throw K("approval-unavailable",new L(_.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let O={p:U2($.principal),t:Z.name,a:j,n:j3(16).toString("base64url"),exp:Date.now()+x3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",O),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let H=`gemi-approval-${j3(12).toString("base64url")}`,U=Q.sessionId,V=await new Promise((N)=>{let I=setTimeout(()=>{this.pending.delete(H),N(null)},this.approvalTimeoutMs),P=(J)=>{clearTimeout(I),N(J)};this.pending.set(H,{session:U,resolve:P}),$.signal.addEventListener("abort",()=>{this.pending.delete(H),P(null)}),$.stream.send({jsonrpc:"2.0",id:H,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return V&&!V.error&&M3(V.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new L(_.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new L(_.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R3(new u($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,W6);return z===null?null:k3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:k3(Z)}}class f3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
3
3
  data: ${JSON.stringify($)}
4
4
 
5
5
  `))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class V2 extends Error{}async function X6($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new V2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function S3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function Y6($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function K6($){let Z;try{Z=new URL($)}catch{throw Error(`route.mcp.remote.url: "${$}" is not a URL.`)}let z=Z.hostname==="localhost"||Z.hostname==="127.0.0.1"||Z.hostname==="[::1]";if(Z.protocol!=="https:"&&!(Z.protocol==="http:"&&z))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if(Z.search||Z.hash||Z.username||Z.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if(Z.pathname==="/"||Z.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return Z}function U2($){return y3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function Q6($){return y3("sha256").update(b3($??{})).digest("base64url")}function q3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function T3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function H6($,Z,z){if(Z.method!=="tools/call"||!z.e)return!1;let G=Z.params?.name;return typeof G==="string"&&$.descriptors({names:[G]})[0]?.requiresApproval===!0}function U6($){let z=(M($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function V6($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
@@ -1,19 +1,19 @@
1
1
  // @bun
2
- import{re as M}from"./chunk-7xe5vd4w.js";import{Ke as V,Pe as Q,ye as C}from"./chunk-169e9dg7.js";import{lm as P}from"./chunk-37209psn.js";import{Gm as A,Hm as S,Im as R}from"./chunk-5mrtgr7q.js";class j extends Error{code;constructor(z,F=1){super(z);this.code=F;this.name="CommandFailed"}}class Z{static commandName="unset";static description="";static args=[];static options=[];run(z){}}function p(z){return z}function L(){return{commands:[],commandsDir:"app/commands"}}var I=Symbol.for("gemi.console.builder");function k(z){if(z.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(z)||/\s/.test(z))throw Error(`Invalid command name ${JSON.stringify(z)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
2
+ import{re as M}from"./chunk-7xe5vd4w.js";import{Ke as V,Pe as Q,ye as W}from"./chunk-wcj7rjfe.js";import{lm as P}from"./chunk-37209psn.js";import{Gm as U,Hm as S,Im as R}from"./chunk-5mrtgr7q.js";class j extends Error{code;constructor(z,F=1){super(z);this.code=F;this.name="CommandFailed"}}class Z{static commandName="unset";static description="";static args=[];static options=[];run(z){}}function h(z){return z}function L(){return{commands:[],commandsDir:"app/commands"}}var A=Symbol.for("gemi.console.builder");function k(z){if(z.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(z)||/\s/.test(z))throw Error(`Invalid command name ${JSON.stringify(z)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
3
3
 
4
4
  defineCommand("mail:send")
5
5
  .arg("user", { required: true })
6
6
  .option("queue", { type: "boolean" })
7
- .handle(async ({ args, options }) => { ... })`)}function c(z){k(z);let F=[],G=[],Y="",J={[I]:z,describe(H){return Y=H,J},arg(H,O={}){if(O.required&&O.default!==void 0)throw Error(`Argument "${H}" of command "${z}" is both required and has a default. An argument that is supplied when absent cannot also be `+"absent \u2014 drop one.");if(O.variadic&&O.default!==void 0)throw Error(`Argument "${H}" of command "${z}" is variadic and has a default. A variadic argument collects the remaining values and is an empty list when there are none, so the default could never `+"apply \u2014 drop it, or drop `variadic`.");let $=F.find((X)=>X.variadic);if($)throw Error(`Argument "${H}" of command "${z}" is declared after the variadic argument "${$.name}", which collects everything that follows, so "${H}" could never receive a value. A variadic argument must be declared last.`);if(F.some((X)=>X.name===H))throw Error(`Command "${z}" declares the argument "${H}" twice.`);return F.push({...O,name:H}),J},option(H,O){if(G.some((K)=>K.name===H))throw Error(`Command "${z}" declares the option "${H}" twice.`);let $="alias"in O?O.alias:void 0,X=$===void 0?void 0:G.find((K)=>("alias"in K)&&K.alias===$);if(X)throw Error(`Options "${X.name}" and "${H}" of command "${z}" both use the alias "-${$}".`);return G.push({...O,name:H}),J},handle(H){let O=z,$=Y,X=class extends Z{static commandName=O;static description=$;static args=[...F];static options=[...G];run(K){return H(K)}};return delete J[I],Object.defineProperty(X,"name",{value:O,configurable:!0}),X}};return J}function T(z){return typeof z==="object"&&z!==null&&typeof z[I]==="string"}function o(z){return z}function B(){return{jobs:[],jobsDir:"app/cron"}}function n(z){return z}function D(){return{listeners:[],listenersDir:"app/listeners"}}class U{static name="unset";static event;queued=!1;maxAttempts=3;backoff=0;worker=!1}class W{static name="unset";run(z,...F){throw Error(`The workflow ${this.constructor.name} has no run method.`)}onCancel(z,...F){return}static start(...z){return P(V).workflows.start(this,z)}static signal(z,F,G){return P(V).workflows.signal(z,F,G)}static items(z,F,G={}){return P(V).workflows.items(z,F,G)}static channel(z){return P(V).workflows.channel(z)}static stream(z,F,G={}){return P(V).workflows.stream(z,F,G)}static cursor(z){return P(V).workflows.cursor(z)}static subscribe(z,F={}){return P(V).workflows.subscribe(z,F)}static find(z){return P(V).workflows.find(z)}static cancel(z){return P(V).workflows.cancel(z)}}import{existsSync as E}from"fs";import{dirname as x,isAbsolute as N,join as y}from"path";function q(z){return N(z)?z:y(R(),z)}function _(z,F,G){if(E(z)||E(x(z)))return;console.warn(`No ${F} were discovered: neither ${z} nor the directory above it exists, so this process cannot see the application's source. If this is a deploy that ships only the build output, list the classes explicitly in app/config/${G}.ts so they travel with it.`)}async function Zz(z=C().jobsDir){let F=q(z);_(F,"queue jobs","queue");let G=await S(F,Q);return w(G),G}async function qz(z=C().workflowsDir){let F=q(z);_(F,"workflows","queue");let G=await S(F,W);for(let Y of G){if(Object.getOwnPropertyDescriptor(Y,"name")?.writable)continue;console.warn(`Workflow ${Y.name} does not declare \`static name\`. A workflow is stored under its name, and a production build renames the class. Add: static name = "${Y.name}";`)}return G}function w(z){for(let F of z){if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;console.warn(`Queued job ${F.name} does not declare \`static name\`, so it is registered under its class name. A production build minifies the class that dispatches it and renames it, while discovery reads this `+"file from source and does not \u2014 so the dispatch would be dropped in "+`production and nowhere else. Add: static name = "${F.name}";`)}}async function _z(z=B().jobsDir){let F=q(z);return _(F,"cron jobs","schedule"),await S(F,M)}async function Iz(z=L().commandsDir){let F=q(z);_(F,"commands","command");let G=[],Y=await S(F,Z,[],(J,H)=>{if(T(J))G.push(H)});return b(G),Y}function b(z){if(z.length===0)return;let F=z.length===1?`${z[0]} exports a command builder that never called \`.handle()\``:`${z.length} files export a command builder that never called \`.handle()\`:
7
+ .handle(async ({ args, options }) => { ... })`)}function m(z){k(z);let F=[],G=[],Y="",J={[A]:z,describe(H){return Y=H,J},arg(H,O={}){if(O.required&&O.default!==void 0)throw Error(`Argument "${H}" of command "${z}" is both required and has a default. An argument that is supplied when absent cannot also be `+"absent \u2014 drop one.");if(O.variadic&&O.default!==void 0)throw Error(`Argument "${H}" of command "${z}" is variadic and has a default. A variadic argument collects the remaining values and is an empty list when there are none, so the default could never `+"apply \u2014 drop it, or drop `variadic`.");let $=F.find((X)=>X.variadic);if($)throw Error(`Argument "${H}" of command "${z}" is declared after the variadic argument "${$.name}", which collects everything that follows, so "${H}" could never receive a value. A variadic argument must be declared last.`);if(F.some((X)=>X.name===H))throw Error(`Command "${z}" declares the argument "${H}" twice.`);return F.push({...O,name:H}),J},option(H,O){if(G.some((K)=>K.name===H))throw Error(`Command "${z}" declares the option "${H}" twice.`);let $="alias"in O?O.alias:void 0,X=$===void 0?void 0:G.find((K)=>("alias"in K)&&K.alias===$);if(X)throw Error(`Options "${X.name}" and "${H}" of command "${z}" both use the alias "-${$}".`);return G.push({...O,name:H}),J},handle(H){let O=z,$=Y,X=class extends Z{static commandName=O;static description=$;static args=[...F];static options=[...G];run(K){return H(K)}};return delete J[A],Object.defineProperty(X,"name",{value:O,configurable:!0}),X}};return J}function T(z){return typeof z==="object"&&z!==null&&typeof z[A]==="string"}function o(z){return z}function B(){return{jobs:[],jobsDir:"app/cron"}}function n(z){return z}function D(){return{listeners:[],listenersDir:"app/listeners"}}class C{static name="unset";static event;queued=!1;maxAttempts=3;backoff=0;worker=!1}class I{static name="unset";run(z,...F){throw Error(`The workflow ${this.constructor.name} has no run method.`)}onCancel(z,...F){return}static start(...z){return P(V).workflows.start(this,z)}static signal(z,F,G){return P(V).workflows.signal(z,F,G)}static items(z,F,G={}){return P(V).workflows.items(z,F,G)}static channel(z){return P(V).workflows.channel(z)}static stream(z,F,G={}){return P(V).workflows.stream(z,F,G)}static cursor(z){return P(V).workflows.cursor(z)}static subscribe(z,F={}){return P(V).workflows.subscribe(z,F)}static find(z){return P(V).workflows.find(z)}static cancel(z){return P(V).workflows.cancel(z)}static pause(z){return P(V).workflows.pause(z)}static resume(z){return P(V).workflows.resume(z)}}import{existsSync as E}from"fs";import{dirname as x,isAbsolute as N,join as y}from"path";function q(z){return N(z)?z:y(R(),z)}function _(z,F,G){if(E(z)||E(x(z)))return;console.warn(`No ${F} were discovered: neither ${z} nor the directory above it exists, so this process cannot see the application's source. If this is a deploy that ships only the build output, list the classes explicitly in app/config/${G}.ts so they travel with it.`)}async function Zz(z=W().jobsDir){let F=q(z);_(F,"queue jobs","queue");let G=await S(F,Q);return w(G),G}async function qz(z=W().workflowsDir){let F=q(z);_(F,"workflows","queue");let G=await S(F,I);for(let Y of G){if(Object.getOwnPropertyDescriptor(Y,"name")?.writable)continue;console.warn(`Workflow ${Y.name} does not declare \`static name\`. A workflow is stored under its name, and a production build renames the class. Add: static name = "${Y.name}";`)}return G}function w(z){for(let F of z){if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;console.warn(`Queued job ${F.name} does not declare \`static name\`, so it is registered under its class name. A production build minifies the class that dispatches it and renames it, while discovery reads this `+"file from source and does not \u2014 so the dispatch would be dropped in "+`production and nowhere else. Add: static name = "${F.name}";`)}}async function _z(z=B().jobsDir){let F=q(z);return _(F,"cron jobs","schedule"),await S(F,M)}async function Az(z=L().commandsDir){let F=q(z);_(F,"commands","command");let G=[],Y=await S(F,Z,[],(J,H)=>{if(T(J))G.push(H)});return b(G),Y}function b(z){if(z.length===0)return;let F=z.length===1?`${z[0]} exports a command builder that never called \`.handle()\``:`${z.length} files export a command builder that never called \`.handle()\`:
8
8
  ${z.join(`
9
- `)}`;throw new A(`${F}, so there is no command to run. \`.handle()\` is what turns `+`the chain into a command \u2014 finish it:
9
+ `)}`;throw new U(`${F}, so there is no command to run. \`.handle()\` is what turns `+`the chain into a command \u2014 finish it:
10
10
 
11
11
  `+` export default defineCommand("my-command")
12
- .handle(async ({ line }) => { line("hello") })`)}async function Uz(z=D().listenersDir){let F=q(z);_(F,"event listeners","events");let G=await S(F,U);return f(G),v(G),g(G),G}function f(z){let F=z.filter((G)=>!G.event);if(F.length===0)return;throw new A(`${F.map((G)=>G.name).join(", ")} declare no \`static event\`, so there is no event name to register them under and their \`handle\` would never run. Every listener binds to exactly one event:
12
+ .handle(async ({ line }) => { line("hello") })`)}async function Cz(z=D().listenersDir){let F=q(z);_(F,"event listeners","events");let G=await S(F,C);return f(G),v(G),g(G),G}function f(z){let F=z.filter((G)=>!G.event);if(F.length===0)return;throw new U(`${F.map((G)=>G.name).join(", ")} declare no \`static event\`, so there is no event name to register them under and their \`handle\` would never run. Every listener binds to exactly one event:
13
13
 
14
14
  static event = UserRegistered;
15
15
 
16
16
  If this is an abstract base its subclasses extend, move it out of the `+"listeners directory \u2014 the walk excludes gemi's `Listener` and "+"nothing else, so a base sitting beside its subclasses is registered and run like one of them.")}function v(z){for(let F of z){if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;console.warn(`Event listener ${F.name} does not declare \`static name\`, so it is registered under its class name, which a production build renames. Nothing reads that name across a build boundary while the `+"listener is sync, which is why this is a warning \u2014 but adding "+`\`queued = true\` to it is refused at boot for the same reason, because the queue's key is that string. Add: static name = "${F.name}";`)}}function g(z){let F=new Set;for(let{event:G}of z){if(F.has(G))continue;if(Object.getOwnPropertyDescriptor(G,"name")?.writable)continue;F.add(G),console.warn(`Event ${G.name} does not declare \`static name\`, so it is dispatched under its class name. A production build minifies the code that dispatches it and renames the class, while discovery reads `+"the listener's copy from source and does not \u2014 so the dispatch would "+`reach no listener in production and nowhere else. Add: static name = "${G.name}";`)}}
17
- export{j as be,Z as ce,p as de,L as ee,c as fe,o as ge,B as he,n as ie,D as je,U as ke,W as le,Zz as me,qz as ne,_z as oe,Iz as pe,Uz as qe};
17
+ export{j as be,Z as ce,h as de,L as ee,m as fe,o as ge,B as he,n as ie,D as je,C as ke,I as le,Zz as me,qz as ne,_z as oe,Az as pe,Cz as qe};
18
18
 
19
- //# debugId=A125E94BD185BD7F64756E2164756E21
19
+ //# debugId=2392BA172967F18064756E2164756E21
@@ -8,10 +8,10 @@
8
8
  "import type { CronJob } from \"./CronJob\";\n\n// Config key: `schedule`. Consumed by `ScheduleServiceProvider`.\nexport interface ScheduleConfig {\n /**\n * The `CronJob` subclasses this application runs on a schedule, or nothing.\n *\n * ### Why \"or nothing\" is the point\n *\n * A cron job that is written and not listed here never fires, and unlike a\n * dropped dispatch there is no caller left waiting to notice: nothing is\n * downstream of a tick that did not happen. The report is simply not sent,\n * for as long as it takes somebody to ask why they stopped seeing it. That is\n * the whole failure — the file exists, the expression is right, and the class\n * was never in the module graph.\n *\n * Leaving this out spells the schedule once: the jobs are the classes under\n * `jobsDir`.\n *\n * ### The rule, exactly\n *\n * **Declared wins, and `[]` is declared.** A `jobs` that is present is used\n * verbatim and no directory is read — the escape hatch for an app whose jobs\n * live somewhere this cannot walk, for one that runs a deliberate subset, and\n * for a deploy that ships no source. An empty array means an app with nothing\n * scheduled and says so; it does not mean \"find some\".\n *\n * **Absent or `undefined` discovers.** `undefined` counts as absent for the\n * same reason `withDefaults` treats it that way everywhere else: a key spread\n * in from an optional value is an omission, not an instruction.\n *\n * Either way the set the scheduler ended up with is readable afterwards, as\n * `app(Scheduler).jobs` — an app that used to import this array to assert\n * something about its own schedule asks the scheduler instead.\n */\n jobs?: Array<new () => CronJob>;\n\n /**\n * Where to look when `jobs` was not declared. Relative to the project root,\n * or absolute.\n *\n * Every `.ts`/`.tsx` file underneath it is imported at boot and every exported\n * class extending `CronJob` is scheduled, so this wants to be a directory of\n * cron declarations rather than a directory that merely contains some. Moving\n * the jobs is what this field is for; pointing it at `app/` is not.\n */\n jobsDir?: string;\n}\n\nexport function defineScheduleConfig(config: ScheduleConfig): ScheduleConfig {\n return config;\n}\n\nexport function scheduleConfigDefaults(): Required<ScheduleConfig> {\n return {\n jobs: [],\n jobsDir: \"app/cron\",\n };\n}\n",
9
9
  "import type { ListenerClass } from \"./Listener\";\n\n// Config key: `events`. Derived from `EventServiceProvider`.\nexport interface EventConfig {\n /**\n * The `Listener` subclasses this application registers, or nothing.\n *\n * ### Why \"or nothing\" is the point\n *\n * A dispatch fans out to whatever the `EventManager` holds for the event's\n * name, and an event nothing is registered for is not an error — it is the\n * ordinary state of an application that has not written that listener yet.\n * So this list is a second spelling of `app/listeners`, kept in step by hand,\n * and what the two disagreeing costs is a side effect that stops happening,\n * with a development-only warning as the only trace. Nothing fails, nothing\n * is dropped from a log: the welcome email simply is not sent.\n *\n * Leaving this out spells it once: the listeners are the classes under\n * `listenersDir`.\n *\n * ### The rule, exactly\n *\n * **Declared wins, and `[]` is declared.** A `listeners` that is present is\n * used verbatim and no directory is read — that is the escape hatch for an\n * app whose listeners live somewhere this cannot walk, for one that\n * deliberately registers a subset, and for a deploy that ships no source. An\n * empty array means an app with no listeners and says so; it does not mean\n * \"find some\".\n *\n * **Absent or `undefined` discovers.** `undefined` counts as absent for the\n * same reason `withDefaults` treats it that way everywhere else: a key spread\n * in from an optional value is an omission, not an instruction.\n */\n listeners?: ListenerClass[];\n\n /**\n * Where to look when `listeners` was not declared. Relative to the project\n * root, or absolute.\n *\n * Every `.ts`/`.tsx` file underneath it is imported at boot and every\n * exported class extending `Listener` is registered, so this wants to be a\n * directory of listener declarations rather than a directory that merely\n * contains some. That includes an abstract base a few listeners share: the\n * walk excludes the framework's `Listener` and nothing else, so a base\n * sitting here is registered alongside its subclasses and its `handle` runs\n * on every dispatch of whatever event it declares. Keep shared bases outside\n * this directory.\n *\n * There is no `eventsDir` to go with it. Event classes are never discovered\n * — each is imported by the listener that binds to it and by the code that\n * dispatches it, so nothing needs to walk them and a walk that imported them\n * anyway would only be a boot cost.\n */\n listenersDir?: string;\n}\n\nexport function defineEventConfig(config: EventConfig): EventConfig {\n return config;\n}\n\nexport function eventConfigDefaults(): Required<EventConfig> {\n return {\n listeners: [],\n listenersDir: \"app/listeners\",\n };\n}\n",
10
10
  "import type { Event, EventClass } from \"./Event\";\n\n/**\n * One side effect of one event, in its own file.\n *\n * ```typescript\n * // app/listeners/SendWelcomeEmail.ts\n * export class SendWelcomeEmail extends Listener {\n * static name = \"SendWelcomeEmail\";\n * static event = UserRegistered;\n *\n * async handle(event: UserRegistered) {\n * await Mail.send(event.email, ...);\n * }\n * }\n * ```\n *\n * That is the whole of what the subsystem buys: adding a fourth side effect to\n * a registration is adding a file, rather than editing the controller that\n * already has three.\n *\n * ### Why the binding lives here and not on the event\n *\n * The listener is the thing with an opinion about what it cares about; an event\n * has no business knowing who is watching. An event listing its listeners would\n * also put the property back the way it was — adding a side effect would edit\n * an existing file.\n *\n * ### Why the binding is a value at all\n *\n * Laravel binds a listener to an event by reflecting on the type-hint of\n * `handle(UserRegistered $event)`. TypeScript erases types at runtime, so that\n * mechanism cannot exist here and the binding has to be carried as a value.\n * That constraint turns out to be a favourable one: it is also what makes the\n * payload types flow without a generated registry.\n *\n * ### The seam, written down rather than hidden\n *\n * **Nothing checks that `static event` and the annotation on `handle` agree.**\n * A static and an instance member cannot reference each other's types, so the\n * compiler sees `static event = UserRegistered` and `handle(event: OrderPaid)`\n * as two unrelated declarations. Copy a listener, change the static, forget the\n * annotation, and TypeScript is satisfied while the listener receives something\n * else.\n *\n * It is accepted because the failure is local and immediate — that one listener\n * reads a field that is not there, in its own stack — rather than the\n * misroute-shaped failures the rest of this subsystem is arranged against. The\n * `Listener.test-d.ts` beside this file pins the two halves the compiler *does*\n * enforce, so a later refactor reaching for convenience cannot widen them to\n * `any` unnoticed.\n */\nexport abstract class Listener {\n /**\n * The name this listener is reported and de-duplicated under. Required.\n *\n * Two listener classes claiming one name is refused at registration, and a\n * discovery walk makes that ordinary: `auth/NotifyAdmins.ts` beside\n * `billing/NotifyAdmins.ts` is a natural thing to write, and nothing forces\n * the import alias a hand-written list would have demanded.\n *\n * As on `Event`, the `\"unset\"` default is a floor and not the check — a class\n * declaration always shadows it with its own implicit binding, which is the\n * one a minifier renames. `discoverListeners` reads the property descriptor\n * to tell a declared name from an implicit one.\n *\n * For a **queued** listener it is more than a label: the queue is keyed by\n * name, the listener is registered under `listener:<name>`, and that string\n * is what a queued dispatch carries. So a queued listener whose name is the\n * implicit class binding is refused at registration rather than warned about\n * — the two ends of the queue can be two different module graphs, and a name\n * only one of them minified is a side effect that stops happening in\n * production and reports success.\n */\n static name = \"unset\";\n\n /**\n * The event class this listener handles. Exactly one, required.\n *\n * It holds the **class**, not its name. The name is read off it once, at\n * registration, inside `EventManager.useListeners` — and that read happens in\n * the module graph that declared the class, so the name it yields is the\n * source one. Nothing downstream keeps the class object, because a registry\n * keyed by class identity is wrong in production only.\n *\n * There is no `static events = [A, B]`, deliberately. A listener bound to two\n * events has to discriminate inside `handle`, and the natural way to write\n * that is `if (event instanceof UserRegistered)` — which is `true` in every\n * test and `false` in a production build, for the reason `Event`'s own doc\n * comment gives. Two events wanting the same side effect are two small\n * listeners calling one shared function.\n *\n * Declared as required, and still checked at runtime: every subclass inherits\n * this declaration whether or not it assigns to it, so the compiler cannot\n * see a listener that left it out. `EventManager` refuses one out loud.\n */\n static event: EventClass;\n\n /**\n * Where this listener runs. **A context boundary, not a performance dial.**\n *\n * Left `false`, the listener runs inline, inside the dispatcher's\n * `kernelContext` and `ormContext`: it has the request's `app()`, the\n * authenticated user through `currentActor()`, and it joins the ambient\n * transaction.\n *\n * **Unless the event declares `static afterCommit`.** That flag releases its\n * listeners after the commit and outside the transaction's scope, so a sync\n * listener bound to one runs with `currentTransaction()` undefined and\n * commits on its own. The listener kept sync *because* it writes a row that\n * has to roll back with the write it describes — an audit trail, a ledger\n * entry — starts committing separately the day someone sets that flag in the\n * event's file, and nothing on this side says so: no error, no warning, and\n * a `queued = false` that still reads as \"inside the transaction\".\n *\n * Set `true`, it is handed to the `QueueManager` instead and run from a\n * drain, on the queue's terms. What crosses is the event's name and its\n * constructor arguments as JSON, and nothing else — not the instance the sync\n * listeners share, and not a line of the request. With `worker = true` it is\n * a different thread with a cloned application.\n *\n * The part that catches people is that the context is not reliably *gone*\n * either: the queue is in-process, so a drain that happens to start from\n * `push` is still standing in the dispatcher's context and `app()` there\n * resolves the request's application. Nothing about that is promised. A\n * queued listener that reads the current actor, or writes expecting to join\n * the ambient transaction, works until the day the queue was already busy —\n * and then reads different rows, or commits separately, with no error either\n * way. So: a listener that needs the request's context has to stay sync, and\n * a listener that only needs the payload is free to queue.\n *\n * What it buys, in exchange, is the queue's whole retry path: `maxAttempts`,\n * `onFail`-style re-queueing and dead-lettering, none of which a sync\n * listener has. `dispatchAndWait` does **not** wait for it.\n */\n queued = false;\n\n /**\n * Attempts before the queue gives up, counting the first. `Job`'s field and\n * `Job`'s meaning, because it is forwarded to one.\n *\n * **Ignored unless `queued` is true.** A sync listener has no retry path at\n * all — its throw is logged and the next listener runs — so a `maxAttempts`\n * beside `queued = false` is a line that does nothing, which is why it is\n * said here rather than in a note somewhere else.\n */\n maxAttempts = 3;\n\n /**\n * Milliseconds to wait before each retry: a number for every retry, or an\n * array with one entry per retry, its last repeating. `Job`'s field and\n * `Job`'s meaning, because it is forwarded to one.\n *\n * **Ignored unless `queued` is true**, for the reason `maxAttempts` is.\n */\n backoff: number | number[] = 0;\n\n /**\n * Runs `handle` in a Worker thread with its own cloned application, for a\n * queued listener whose work is CPU-bound. `Job`'s field and `Job`'s\n * meaning, because it is forwarded to one.\n *\n * **Ignored unless `queued` is true.** A sync listener runs on the\n * dispatcher's stack by definition; there is no thread to move it to.\n */\n worker = false;\n\n /**\n * The side effect. Runs inside the dispatcher's context when `queued` is\n * false: a sync listener has the request's `app()`, its authenticated user,\n * and — unless the event declares `static afterCommit` — its ambient\n * transaction. A queued one can rely on none of them — see `queued`.\n *\n * Annotate the parameter with the event named in `static event` — narrowing\n * the base's `Event` here is legal because method parameters are bivariant,\n * which is what lets this class avoid a generic parameter. Nothing checks\n * that the two agree; see the note on the class.\n *\n * Abstract, so a listener that forgets it fails to compile rather than\n * silently handling nothing.\n *\n * A throw is caught, logged with both names, and the next listener still\n * runs. Listeners are independent side effects by construction, and their\n * order is a filesystem walk's — letting one cancel the rest would make that\n * order load-bearing, which is the exact coupling this subsystem exists to\n * remove.\n */\n abstract handle(event: Event): void | Promise<void>;\n}\n\n/**\n * A `Listener` subclass, as the registry and the `events` config slice hold\n * one.\n *\n * Zero-argument, because the manager constructs one per dispatch and has\n * nothing to pass it. The `event` member is typed as present even though\n * `EventManager` checks for it at runtime: an inherited declaration is\n * indistinguishable from an assignment to the type system, so this is the\n * shape, and the runtime check is what covers the difference.\n */\nexport type ListenerClass = (new () => Listener) & {\n name: string;\n event: EventClass;\n};\n",
11
- "import { app } from \"../../../foundation/app\";\nimport { QueueManager } from \"../QueueManager\";\nimport type { EachProblem, Step } from \"./Step\";\nimport type { ChangeFeedResponse, StreamOptions } from \"../../change-feed/stream\";\nimport type { WorkflowUpdate } from \"./wire\";\n\n/** The arguments `start` takes: `run`'s, after `step`. */\nexport type WorkflowArgs<T extends Workflow> = Parameters<T[\"run\"]> extends [\n any,\n ...infer Rest,\n]\n ? Rest\n : never;\n\n/** What `Workflow.find` resolves to: the workflow's update, with its arguments and result. */\nexport type WorkflowStatus = WorkflowUpdate & {\n /** The `run` arguments after `step`. */\n args: unknown[];\n /** What `run` returned, once completed. */\n result: unknown;\n};\n\nexport type { WorkflowStepStatus, WorkflowUpdate } from \"./wire\";\n\n/**\n * A durable workflow (#846): a `run` method made of steps, which survives\n * restarts and deploys, sleeps and waits without holding a process, and can\n * be cancelled.\n *\n * ```ts\n * export class ImportSiteWorkflow extends Workflow {\n * static name = \"ImportSiteWorkflow\";\n *\n * async run(step: Step, importId: string) {\n * const pages = await step.run(\"discover\", () => crawl(importId));\n * const chosen = await step.waitFor<string[]>(\"pages-chosen\", { timeout: \"7d\" });\n * await step.run(\"charge\", (ctx) => charge(importId, ctx.idempotencyKey), { attempts: 1 });\n * const builds = await step.batch(\"build\", BuildPageJob,\n * chosen.map((id) => [id, importId] as const), { allowFailures: true });\n * await step.sleep(\"settle\", \"30s\");\n * return step.run(\"report\", () => report(importId, builds.failedJobIds));\n * }\n *\n * async onCancel(step: Step, importId: string) {\n * await step.run(\"refund\", () => refundUnbuilt(importId));\n * }\n * }\n * ```\n *\n * ### How it runs\n *\n * Each pass calls `run` from the top, inside an internal queue job (a\n * *tick*), so leases, heartbeats and crash recovery are the queue's. A step\n * whose result is stored returns it without running; the first one without\n * one runs and its result is stored before the code goes on. A step that\n * cannot finish now (a sleep, a wait, a batch, a retry with a delay) ends the\n * pass, and a later tick picks it up. **Code outside the steps runs again on\n * every pass**, so it must be cheap and give the same answer each time: put\n * anything with a side effect, anything slow and anything random or\n * time-dependent inside `step.run`.\n *\n * Step keys are the identity of a step: unique within the workflow, and the\n * same on every pass. Adding or removing a step between deploys is safe; a\n * renamed step runs again.\n */\nexport class Workflow {\n static name = \"unset\";\n\n /**\n * The workflow's body. Its return value, as JSON, is the workflow's\n * `result`. A throw that escapes it fails the workflow.\n */\n run(_step: Step, ..._args: any[]): unknown {\n throw new Error(`The workflow ${(this.constructor as typeof Workflow).name} has no run method.`);\n }\n\n /**\n * Runs once after `Workflow.cancel`, in place of `run`, with the same\n * arguments: the place to undo what the steps did. Its steps are memoized\n * like `run`'s (use keys of their own), so it may sleep or retry too.\n */\n onCancel(_step: Step, ..._args: any[]): unknown {\n return undefined;\n }\n\n /**\n * Starts a workflow and resolves to its id. The workflow and its first tick\n * are recorded in one atomic write. Inside an ORM transaction it belongs to\n * the transaction, as a dispatch does: recorded with it, or held until it\n * commits and dropped if it rolls back.\n */\n static start<T extends Workflow>(\n this: new () => T,\n ...args: WorkflowArgs<T>\n ): Promise<string> {\n return app(QueueManager).workflows.start(this as unknown as WorkflowClass, args);\n }\n\n /**\n * Delivers `payload` to the workflow's `step.waitFor(key)`, and resolves to\n * whether it was taken: `false` for an unknown or ended workflow, and for a\n * key that was already signalled. A signal that arrives before the workflow\n * reaches its `waitFor` is kept until it does.\n */\n static signal(id: string, key: string, payload?: unknown): Promise<boolean> {\n return app(QueueManager).workflows.signal(id, key, payload);\n }\n\n /**\n * The items of the `step.each` under `key` that failed or were skipped\n * (or only those of `status`), by index, from just after the index\n * `after`, at most `limit` (default 100, at most 1000). Page through them\n * by passing the last index as `after`.\n */\n static items(\n id: string,\n key: string,\n options: { status?: \"failed\" | \"skipped\"; after?: number; limit?: number } = {},\n ): Promise<EachProblem[]> {\n return app(QueueManager).workflows.items(id, key, options);\n }\n\n /** The ChangeFeed channel a workflow's changes are published to: `gemi:workflow:<id>`. */\n static channel(id: string): string {\n return app(QueueManager).workflows.channel(id);\n }\n\n /**\n * An SSE response following workflow `id`, for `useWorkflow`. Each event's\n * `data` is a `WorkflowUpdate`: the status without `args` and `result`.\n * Authorise the read first, as for any route. Resumes from\n * `Last-Event-ID`, or `options.cursor` (`Workflow.cursor(id)`).\n */\n static stream(\n request: { rawRequest: Request } | Request,\n id: string,\n options: StreamOptions = {},\n ): ChangeFeedResponse<WorkflowUpdate> {\n return app(QueueManager).workflows.stream(request, id, options);\n }\n\n /** A cursor at the workflow's channel head, for a view that read it to hand its client. */\n static cursor(id: string): Promise<string> {\n return app(QueueManager).workflows.cursor(id);\n }\n\n /**\n * Follows workflow `id` on the server: yields it as it is now, then each\n * newer update, and ends after the one that ended it.\n */\n static subscribe(\n id: string,\n options: { signal?: AbortSignal } = {},\n ): AsyncGenerator<WorkflowUpdate, void, undefined> {\n return app(QueueManager).workflows.subscribe(id, options);\n }\n\n /** The workflow's status, or `null` for an unknown id. */\n static find(id: string): Promise<WorkflowStatus | null> {\n return app(QueueManager).workflows.find(id);\n }\n\n /**\n * Cancels a workflow that has not ended, and resolves to whether it did.\n * A running `step.batch` is cancelled with it, a running `step.run` is told\n * through `ctx.signal`, and `onCancel` then runs once.\n */\n static cancel(id: string): Promise<boolean> {\n return app(QueueManager).workflows.cancel(id);\n }\n}\n\nexport type WorkflowClass = (new () => Workflow) & { name: string };\n",
11
+ "import { app } from \"../../../foundation/app\";\nimport { QueueManager } from \"../QueueManager\";\nimport type { EachProblem, Step } from \"./Step\";\nimport type { ChangeFeedResponse, StreamOptions } from \"../../change-feed/stream\";\nimport type { WorkflowUpdate } from \"./wire\";\n\n/** The arguments `start` takes: `run`'s, after `step`. */\nexport type WorkflowArgs<T extends Workflow> = Parameters<T[\"run\"]> extends [\n any,\n ...infer Rest,\n]\n ? Rest\n : never;\n\n/** What `Workflow.find` resolves to: the workflow's update, with its arguments and result. */\nexport type WorkflowStatus = WorkflowUpdate & {\n /** The `run` arguments after `step`. */\n args: unknown[];\n /** What `run` returned, once completed. */\n result: unknown;\n};\n\nexport type { WorkflowStepStatus, WorkflowUpdate } from \"./wire\";\n\n/**\n * A durable workflow (#846): a `run` method made of steps, which survives\n * restarts and deploys, sleeps and waits without holding a process, and can\n * be cancelled.\n *\n * ```ts\n * export class ImportSiteWorkflow extends Workflow {\n * static name = \"ImportSiteWorkflow\";\n *\n * async run(step: Step, importId: string) {\n * const pages = await step.run(\"discover\", () => crawl(importId));\n * const chosen = await step.waitFor<string[]>(\"pages-chosen\", { timeout: \"7d\" });\n * await step.run(\"charge\", (ctx) => charge(importId, ctx.idempotencyKey), { attempts: 1 });\n * const builds = await step.batch(\"build\", BuildPageJob,\n * chosen.map((id) => [id, importId] as const), { allowFailures: true });\n * await step.sleep(\"settle\", \"30s\");\n * return step.run(\"report\", () => report(importId, builds.failedJobIds));\n * }\n *\n * async onCancel(step: Step, importId: string) {\n * await step.run(\"refund\", () => refundUnbuilt(importId));\n * }\n * }\n * ```\n *\n * ### How it runs\n *\n * Each pass calls `run` from the top, inside an internal queue job (a\n * *tick*), so leases, heartbeats and crash recovery are the queue's. A step\n * whose result is stored returns it without running; the first one without\n * one runs and its result is stored before the code goes on. A step that\n * cannot finish now (a sleep, a wait, a batch, a retry with a delay) ends the\n * pass, and a later tick picks it up. **Code outside the steps runs again on\n * every pass**, so it must be cheap and give the same answer each time: put\n * anything with a side effect, anything slow and anything random or\n * time-dependent inside `step.run`.\n *\n * Step keys are the identity of a step: unique within the workflow, and the\n * same on every pass. Adding or removing a step between deploys is safe; a\n * renamed step runs again.\n */\nexport class Workflow {\n static name = \"unset\";\n\n /**\n * The workflow's body. Its return value, as JSON, is the workflow's\n * `result`. A throw that escapes it fails the workflow.\n */\n run(_step: Step, ..._args: any[]): unknown {\n throw new Error(`The workflow ${(this.constructor as typeof Workflow).name} has no run method.`);\n }\n\n /**\n * Runs once after `Workflow.cancel`, in place of `run`, with the same\n * arguments: the place to undo what the steps did. Its steps are memoized\n * like `run`'s (use keys of their own), so it may sleep or retry too.\n */\n onCancel(_step: Step, ..._args: any[]): unknown {\n return undefined;\n }\n\n /**\n * Starts a workflow and resolves to its id. The workflow and its first tick\n * are recorded in one atomic write. Inside an ORM transaction it belongs to\n * the transaction, as a dispatch does: recorded with it, or held until it\n * commits and dropped if it rolls back.\n */\n static start<T extends Workflow>(\n this: new () => T,\n ...args: WorkflowArgs<T>\n ): Promise<string> {\n return app(QueueManager).workflows.start(this as unknown as WorkflowClass, args);\n }\n\n /**\n * Delivers `payload` to the workflow's `step.waitFor(key)`, and resolves to\n * whether it was taken: `false` for an unknown or ended workflow, and for a\n * key that was already signalled. A signal that arrives before the workflow\n * reaches its `waitFor` is kept until it does.\n */\n static signal(id: string, key: string, payload?: unknown): Promise<boolean> {\n return app(QueueManager).workflows.signal(id, key, payload);\n }\n\n /**\n * The items of the `step.each` under `key` that failed or were skipped\n * (or only those of `status`), by index, from just after the index\n * `after`, at most `limit` (default 100, at most 1000). Page through them\n * by passing the last index as `after`.\n */\n static items(\n id: string,\n key: string,\n options: { status?: \"failed\" | \"skipped\"; after?: number; limit?: number } = {},\n ): Promise<EachProblem[]> {\n return app(QueueManager).workflows.items(id, key, options);\n }\n\n /** The ChangeFeed channel a workflow's changes are published to: `gemi:workflow:<id>`. */\n static channel(id: string): string {\n return app(QueueManager).workflows.channel(id);\n }\n\n /**\n * An SSE response following workflow `id`, for `useWorkflow`. Each event's\n * `data` is a `WorkflowUpdate`: the status without `args` and `result`.\n * Authorise the read first, as for any route. Resumes from\n * `Last-Event-ID`, or `options.cursor` (`Workflow.cursor(id)`).\n */\n static stream(\n request: { rawRequest: Request } | Request,\n id: string,\n options: StreamOptions = {},\n ): ChangeFeedResponse<WorkflowUpdate> {\n return app(QueueManager).workflows.stream(request, id, options);\n }\n\n /** A cursor at the workflow's channel head, for a view that read it to hand its client. */\n static cursor(id: string): Promise<string> {\n return app(QueueManager).workflows.cursor(id);\n }\n\n /**\n * Follows workflow `id` on the server: yields it as it is now, then each\n * newer update, and ends after the one that ended it.\n */\n static subscribe(\n id: string,\n options: { signal?: AbortSignal } = {},\n ): AsyncGenerator<WorkflowUpdate, void, undefined> {\n return app(QueueManager).workflows.subscribe(id, options);\n }\n\n /** The workflow's status, or `null` for an unknown id. */\n static find(id: string): Promise<WorkflowStatus | null> {\n return app(QueueManager).workflows.find(id);\n }\n\n /**\n * Cancels a workflow that has not ended, and resolves to whether it did.\n * A running `step.batch` is cancelled with it, a running `step.run` is told\n * through `ctx.signal`, and `onCancel` then runs once.\n */\n static cancel(id: string): Promise<boolean> {\n return app(QueueManager).workflows.cancel(id);\n }\n\n /**\n * Pauses a workflow that has not ended, and resolves to whether it did. No\n * new step starts: a running `step.run` finishes and is recorded, a\n * `step.each` lets the items in flight finish and takes no more, and the\n * workflow then waits as `paused`, holding no queue slot, until `resume`.\n * Signals and batches that arrive meanwhile are kept. It can still be\n * cancelled.\n */\n static pause(id: string): Promise<boolean> {\n return app(QueueManager).workflows.pause(id);\n }\n\n /** Resumes a paused workflow where it stopped, and resolves to whether it was paused. */\n static resume(id: string): Promise<boolean> {\n return app(QueueManager).workflows.resume(id);\n }\n}\n\nexport type WorkflowClass = (new () => Workflow) & { name: string };\n",
12
12
  "import { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nimport {\n discoverClasses,\n DiscoveryError,\n projectRoot,\n} from \"../support/discover\";\nimport { Command, type CommandClass } from \"../console/Command\";\nimport { commandConfigDefaults } from \"../console/config\";\nimport { isUnfinishedBuilder } from \"../console/builder\";\nimport { CronJob } from \"./cron/CronJob\";\nimport { scheduleConfigDefaults } from \"./cron/config\";\nimport { eventConfigDefaults } from \"./events/config\";\nimport type { EventClass } from \"./events/Event\";\nimport { Listener, type ListenerClass } from \"./events/Listener\";\nimport { Job } from \"./queue/Job\";\nimport { queueConfigDefaults } from \"./queue/config\";\nimport { Workflow, type WorkflowClass } from \"./queue/workflow/Workflow\";\n\n/**\n * Reading an application's jobs off the filesystem, for the two subsystems that\n * were asking every app to write its job list twice.\n *\n * Both functions here are the same call to `discoverClasses` with a different\n * base class, which is deliberate: one walk, one set of skip rules, one answer\n * to \"what does this app have\". They are exported from `gemi/services` rather\n * than kept private to the providers because the list stopped being something\n * an app could import — a test that used to walk the exported `jobs` array\n * needs somewhere to ask the same question, and so does a script.\n *\n * What the providers add on top of these is the decision of *whether* to ask,\n * which is the config's to make and not this file's.\n */\n\n/**\n * A directory the app named, resolved the way the app meant it.\n *\n * Relative paths hang off the project root rather than `process.cwd()` at the\n * moment of the call, because a config slice saying `app/jobs` means the app's\n * `app/jobs` and not whatever directory somebody happened to launch a script\n * from. Absolute paths are taken as given, which is what makes these callable\n * from a test that has no project around it.\n */\nfunction resolveDir(dir: string): string {\n return isAbsolute(dir) ? dir : join(projectRoot(), dir);\n}\n\n/**\n * Says something when the directory is missing *and so is the tree it lives in*.\n *\n * A missing directory has two readings and they want opposite responses. An app\n * that has never written a cron job has no `app/cron`, and warning about that on\n * every boot for the rest of its life is noise — the answer \"you have no cron\n * jobs\" is correct and uninteresting. But a deploy that ships `dist/` and\n * `node_modules/` without the source has no `app/cron` *and no `app/`*, and\n * there discovery quietly returns nothing while the app very much does have\n * jobs: the exact silence #322 and #323 exist to remove, reintroduced one layer\n * down and in production only.\n *\n * The parent directory is what tells them apart. If neither the directory nor\n * the one above it is there, the tree this was pointed into is not there\n * either, and that is worth a sentence.\n */\nfunction warnIfSourceIsMissing(\n resolved: string,\n subject: string,\n slice: string,\n) {\n if (existsSync(resolved) || existsSync(dirname(resolved))) return;\n\n console.warn(\n `No ${subject} were discovered: neither ${resolved} nor the directory ` +\n `above it exists, so this process cannot see the application's source. ` +\n `If this is a deploy that ships only the build output, list the classes ` +\n `explicitly in app/config/${slice}.ts so they travel with it.`,\n );\n}\n\n/**\n * The `Job` subclasses under `dir`, defaulting to the config slice's `app/jobs`.\n *\n * This is what a `queue` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array:\n * every job this application would register, in the order it would register\n * them.\n *\n * Every file underneath is imported, so calling this runs the app's job modules\n * — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverJobs(\n dir: string = queueConfigDefaults().jobsDir,\n): Promise<Array<new () => Job>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"queue jobs\", \"queue\");\n const jobs = await discoverClasses(resolved, Job);\n warnIfNameWillNotSurviveTheBuild(jobs);\n return jobs;\n}\n\n/**\n * The `Workflow` subclasses under `dir`, defaulting to the queue slice's\n * `app/workflows`: what a `queue` slice with no `workflows` key resolves to.\n * A missing directory is no workflows, said nothing about unless the tree\n * above it is missing too.\n */\nexport async function discoverWorkflows(\n dir: string = queueConfigDefaults().workflowsDir,\n): Promise<WorkflowClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"workflows\", \"queue\");\n const workflows = (await discoverClasses(resolved, Workflow)) as WorkflowClass[];\n for (const workflow of workflows) {\n if (Object.getOwnPropertyDescriptor(workflow, \"name\")?.writable) continue;\n console.warn(\n `Workflow ${workflow.name} does not declare \\`static name\\`. A workflow ` +\n `is stored under its name, and a production build renames the class. ` +\n `Add: static name = \"${workflow.name}\";`,\n );\n }\n return workflows;\n}\n\n/**\n * Says something about a discovered job that never declared `static name`.\n *\n * This is the one hazard discovery introduces rather than removes, and it is\n * production-only. `gemi build` minifies the server entry, and app code\n * reachable from it — a controller, and every job class that controller\n * imports to dispatch — is bundled and minified with it. Minification renames\n * the class binding, and a class's implicit `.name` is that binding: a\n * `TestJob` in the bundle reports `\"D\"`. Discovery, meanwhile, imports\n * `app/jobs/TestJob.ts` from source at runtime, where it is still `\"TestJob\"`.\n * The queue is keyed by that name, so the two halves stop agreeing and the\n * dispatch is dropped — in production, and only there.\n *\n * A declared `static name = \"TestJob\"` is a string literal, which survives\n * minification intact, and the two halves agree again. `docs/jobs-and-queues.md`\n * has always called it required; before discovery an app could get away without\n * it, because the explicit `jobs` array was bundled too and both sides were\n * wrong in the same way.\n *\n * The check is exact rather than a guess: a `static name = \"...\"` class field\n * defines a *writable* own property, while the implicit class name is\n * non-writable. Cron is unaffected — `CronJob.name` is an instance field\n * holding a string literal, not the class binding.\n */\nfunction warnIfNameWillNotSurviveTheBuild(jobs: Array<new () => Job>) {\n for (const job of jobs) {\n if (Object.getOwnPropertyDescriptor(job, \"name\")?.writable) continue;\n\n console.warn(\n `Queued job ${job.name} does not declare \\`static name\\`, so it is ` +\n `registered under its class name. A production build minifies the ` +\n `class that dispatches it and renames it, while discovery reads this ` +\n `file from source and does not — so the dispatch would be dropped in ` +\n `production and nowhere else. Add: static name = \"${job.name}\";`,\n );\n }\n}\n\n/**\n * The `CronJob` subclasses under `dir`, defaulting to the config slice's\n * `app/cron`.\n *\n * This is what a `schedule` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array —\n * though after boot `app(Scheduler).jobs` is the better one, because it is what\n * the scheduler actually took rather than what this would find if asked again.\n *\n * Every file underneath is imported, so calling this runs the app's cron\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCronJobs(\n dir: string = scheduleConfigDefaults().jobsDir,\n): Promise<Array<new () => CronJob>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"cron jobs\", \"schedule\");\n return await discoverClasses(resolved, CronJob);\n}\n\n/**\n * The `Command` subclasses under `dir`, defaulting to the config slice's\n * `app/commands`.\n *\n * This is what a `commands`-less `command` slice resolves to, and what\n * `gemi run` lists. Unlike the two above it is not called during boot — a\n * command registry has one consumer, and importing every file under\n * `app/commands` into every server process would be a cost paid on every start\n * for code no request reaches.\n *\n * Every file underneath is imported, so calling this runs the app's command\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCommands(\n dir: string = commandConfigDefaults().commandsDir,\n): Promise<CommandClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"commands\", \"command\");\n\n const unfinished: string[] = [];\n\n const commands = await discoverClasses(\n resolved,\n Command,\n [],\n (value, file) => {\n if (isUnfinishedBuilder(value)) unfinished.push(file);\n },\n );\n\n refuseUnfinishedBuilders(unfinished);\n\n return commands as CommandClass[];\n}\n\n/**\n * Stops the walk for a builder chain that was never finished.\n *\n * This is the one silence the builder introduces, and it is the exact shape\n * #322 and #323 exist to remove. `defineCommand(...).arg(...)` without a\n * trailing `.handle(...)` is a plain object rather than a class, so\n * `discoverClasses` discards it along with every constant and helper a command\n * file happens to export — and the command disappears from `gemi run` with\n * nothing raised. The author sees a listing containing every command except the\n * one they just wrote.\n *\n * A throw rather than a warning, because there is no reading of an unfinished\n * builder under which the author meant it: the chain builds a description of a\n * command and then discards it.\n *\n * \"Unfinished\" is decided by `.handle()` clearing the brand, not by the export\n * still being a builder object. Those differ for the natural way to share\n * declarations —\n *\n * export const base = defineCommand(\"reindex\").option(\"verbose\", …);\n * export default base.handle(async () => {});\n *\n * — where `base` is a builder that *did* produce a command. Keying off the shape\n * alone made that file abort the whole of `gemi run`, taking every other command\n * in the project down with it, under a message that was untrue for it.\n */\nfunction refuseUnfinishedBuilders(files: string[]): void {\n if (files.length === 0) return;\n\n const subject =\n files.length === 1\n ? `${files[0]} exports a command builder that never called \\`.handle()\\``\n : `${files.length} files export a command builder that never called ` +\n `\\`.handle()\\`:\\n ${files.join(\"\\n \")}`;\n\n throw new DiscoveryError(\n `${subject}, so there is no command to run. \\`.handle()\\` is what turns ` +\n `the chain into a command — finish it:\\n\\n` +\n ` export default defineCommand(\"my-command\")\\n` +\n ` .handle(async ({ line }) => { line(\"hello\") })`,\n );\n}\n\n/**\n * The `Listener` subclasses under `dir`, defaulting to the config slice's\n * `app/listeners`.\n *\n * This is what an `events` config slice with no `listeners` key resolves to.\n * Call it directly to ask what an application would register: every listener,\n * in the order it would register them.\n *\n * Only listeners are walked. Event classes are never discovered — each is\n * imported by the listener that binds to it and by the code that dispatches it,\n * so there is nothing a walk over them would find that is not already in the\n * module graph.\n *\n * **Known residual, matching jobs and cron.** `discoverClasses` excludes the\n * `base` it is handed and not intermediates, so an abstract listener base\n * written in `listenersDir` and extended by its siblings is discovered and\n * registered alongside them — constructed, with its `handle` called, on every\n * dispatch of whatever event it declares. Keep shared bases outside the\n * directory.\n *\n * Every file underneath is imported, so calling this runs the app's listener\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n *\n * @throws DiscoveryError if a discovered listener declares no `static event`.\n */\nexport async function discoverListeners(\n dir: string = eventConfigDefaults().listenersDir,\n): Promise<ListenerClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"event listeners\", \"events\");\n\n const listeners = (await discoverClasses(\n resolved,\n Listener,\n )) as ListenerClass[];\n\n refuseListenersWithNoEvent(listeners);\n warnIfListenerNameWillNotSurviveTheBuild(listeners);\n warnIfEventNameWillNotSurviveTheBuild(listeners);\n\n return listeners;\n}\n\n/**\n * Stops the walk for a listener that binds to nothing.\n *\n * `static event` is declared as required on the base and the compiler still\n * cannot see it missing: every subclass inherits the declaration whether or not\n * it assigns to one, so `typeof SomeListener` type-checks either way. What the\n * author gets instead is a file that is imported, registered under no name, and\n * never called — the silence this whole module is arranged against.\n *\n * A throw rather than a warning, because there is no reading of a listener with\n * no event under which the author meant it. The usual cause is the residual\n * above: an abstract base sharing a gate between two listeners, sitting in\n * `listenersDir` where the walk finds it. Moving it out is the fix, and the\n * message says so — the alternative, excluding it by some guess about\n * abstractness, is how a discovery pass ends up quietly covering less than the\n * directory holds.\n */\nfunction refuseListenersWithNoEvent(listeners: ListenerClass[]): void {\n const orphans = listeners.filter((listener) => !listener.event);\n if (orphans.length === 0) return;\n\n throw new DiscoveryError(\n `${orphans\n .map((listener) => listener.name)\n .join(\", \")} declare no \\`static event\\`, so there is no event name to ` +\n `register them under and their \\`handle\\` would never run. Every ` +\n `listener binds to exactly one event:\\n\\n` +\n ` static event = UserRegistered;\\n\\n` +\n `If this is an abstract base its subclasses extend, move it out of the ` +\n `listeners directory — the walk excludes gemi's \\`Listener\\` and ` +\n `nothing else, so a base sitting beside its subclasses is registered ` +\n `and run like one of them.`,\n );\n}\n\n/**\n * Says something about a discovered listener that never declared `static name`.\n *\n * The hazard is `warnIfNameWillNotSurviveTheBuild`'s, one subsystem over: a\n * `static name = \"...\"` class field defines a *writable* own property while the\n * implicit class binding does not, and a minifier renames the binding while\n * leaving the string literal alone. The two spellings are indistinguishable by\n * value — both read `\"SendWelcomeEmail\"` in development — so the descriptor is\n * the only thing that tells them apart, and the difference only becomes visible\n * in a production build.\n *\n * A warning rather than a refusal, because a *sync* listener's name has no\n * second half to disagree with: every reader of it comes from this same\n * source-side walk, so a minified build and this walk cannot produce two\n * different strings for it. A **queued** listener does have one — the name is\n * the queue's key and it crosses a JSON boundary — and that case is refused\n * outright, by `jobForListener`, at the point the listener is registered with\n * the queue rather than here. This walk cannot tell the two apart without\n * constructing every listener it found; the registry constructs them anyway.\n */\nfunction warnIfListenerNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n for (const listener of listeners) {\n if (Object.getOwnPropertyDescriptor(listener, \"name\")?.writable) continue;\n\n console.warn(\n `Event listener ${listener.name} does not declare \\`static name\\`, so ` +\n `it is registered under its class name, which a production build ` +\n `renames. Nothing reads that name across a build boundary while the ` +\n `listener is sync, which is why this is a warning — but adding ` +\n `\\`queued = true\\` to it is refused at boot for the same reason, ` +\n `because the queue's key is that string. Add: static name = ` +\n `\"${listener.name}\";`,\n );\n }\n}\n\n/**\n * Says something about the *event* a discovered listener binds to, when that\n * event's name is the implicit class binding.\n *\n * This is the check that matters from the first dispatch, and it is the reason\n * `discoverListeners` reads `static event` at all. The registry is keyed by the\n * event's name; the dispatcher supplies that name from the class it constructs.\n * A production build minifies the server entry and the app code reachable from\n * it — the controller, and the event class it imports in order to dispatch —\n * while discovery imports `app/listeners/*.ts` from source, and those files\n * import `app/events/*.ts` from source too. Two module graphs, two class\n * objects, and an implicit `.name` that reads `\"UserRegistered\"` on one side\n * and `\"D\"` on the other. The dispatch then finds no listeners, which is legal,\n * normal, and completely silent.\n *\n * A declared `static name` is a string literal, which survives minification\n * intact, and the two halves agree again.\n *\n * Checked through the descriptor rather than the string, and not by comparing\n * `event.name` to anything: in development the two spellings produce the same\n * value, so a check on the string would be a tautology that passes forever.\n */\nfunction warnIfEventNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n const warned = new Set<EventClass>();\n\n for (const { event } of listeners) {\n if (warned.has(event)) continue;\n if (Object.getOwnPropertyDescriptor(event, \"name\")?.writable) continue;\n warned.add(event);\n\n console.warn(\n `Event ${event.name} does not declare \\`static name\\`, so it is ` +\n `dispatched under its class name. A production build minifies the ` +\n `code that dispatches it and renames the class, while discovery reads ` +\n `the listener's copy from source and does not — so the dispatch would ` +\n `reach no listener in production and nowhere else. Add: ` +\n `static name = \"${event.name}\";`,\n );\n }\n}\n"
13
13
  ],
14
- "mappings": "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",
15
- "debugId": "A125E94BD185BD7F64756E2164756E21",
14
+ "mappings": "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",
15
+ "debugId": "2392BA172967F18064756E2164756E21",
16
16
  "names": []
17
17
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-n8m9vycp.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{We as GJ,ch as IJ,dh as g,lh as AJ,mh as BJ,nh as RJ}from"./chunk-bs4p7dys.js";import"./chunk-j9abwrkv.js";import"./chunk-4v5nwqw6.js";import{si as jJ,ti as YJ,wi as WJ}from"./chunk-8gnbc9dg.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t586p2g2.js";import"./chunk-qs2xvc8g.js";import"./chunk-2y0nr525.js";import"./chunk-p4v71qfx.js";import"./chunk-anc5v266.js";import"./chunk-wy82t7mz.js";import"./chunk-tac25cnj.js";import"./chunk-0k2r6bep.js";import"./chunk-0av1gyns.js";import"./chunk-zmt5kdpb.js";import"./chunk-rat2827k.js";import"./chunk-yj7pbbnm.js";import"./chunk-37209psn.js";import"./chunk-fqhkkpq3.js";import{qm as KJ}from"./chunk-swmf6w3z.js";import"./chunk-6r7956dh.js";import{Im as PJ}from"./chunk-5mrtgr7q.js";import{Km as f}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
2
+ import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-7czgj8ae.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{We as GJ,ch as IJ,dh as g,lh as AJ,mh as BJ,nh as RJ}from"./chunk-bs4p7dys.js";import"./chunk-j9abwrkv.js";import"./chunk-4v5nwqw6.js";import{si as jJ,ti as YJ,wi as WJ}from"./chunk-8gnbc9dg.js";import{Ej as DJ}from"./chunk-h1wmpa03.js";import"./chunk-t586p2g2.js";import"./chunk-qs2xvc8g.js";import"./chunk-2y0nr525.js";import"./chunk-p4v71qfx.js";import"./chunk-anc5v266.js";import"./chunk-wy82t7mz.js";import"./chunk-tac25cnj.js";import"./chunk-0k2r6bep.js";import"./chunk-0av1gyns.js";import"./chunk-zmt5kdpb.js";import"./chunk-rat2827k.js";import"./chunk-yj7pbbnm.js";import"./chunk-37209psn.js";import"./chunk-fqhkkpq3.js";import{qm as KJ}from"./chunk-swmf6w3z.js";import"./chunk-6r7956dh.js";import{Im as PJ}from"./chunk-5mrtgr7q.js";import{Km as f}from"./chunk-55btq9c7.js";import"./chunk-3dkv4989.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as R2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:R(J,y,$)}}function R(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(R(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of R(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:R(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8" />