gemi 0.246.0 → 0.246.2

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 (36) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/ai/providers/http.d.ts.map +1 -1
  3. package/dist/ai/providers/stream.d.ts +5 -1
  4. package/dist/ai/providers/stream.d.ts.map +1 -1
  5. package/dist/ai/testing/index.js +1 -1
  6. package/dist/{chunk-p8ypq16v.js → chunk-8adt2k7j.js} +1 -1
  7. package/dist/{chunk-t56z2zec.js → chunk-gv7eh0wd.js} +1 -1
  8. package/dist/{chunk-bcpxyv8m.js → chunk-hn2mm9r6.js} +4 -4
  9. package/dist/{chunk-bcpxyv8m.js.map → chunk-hn2mm9r6.js.map} +4 -4
  10. package/dist/{chunk-q0k1j5a4.js → chunk-n626761s.js} +1 -1
  11. package/dist/{chunk-dxtxvxcz.js → chunk-p9trv4kn.js} +2 -2
  12. package/dist/{chunk-dxtxvxcz.js.map → chunk-p9trv4kn.js.map} +1 -1
  13. package/dist/chunk-pvs5qjs7.js +5 -0
  14. package/dist/{chunk-dapd4vkd.js.map → chunk-pvs5qjs7.js.map} +3 -3
  15. package/dist/{chunk-ggh1hzdb.js → chunk-qqh6h36y.js} +1 -1
  16. package/dist/{chunk-11fc5nve.js → chunk-tm4kfnqh.js} +1 -1
  17. package/dist/client/describeCaughtError.d.ts +11 -0
  18. package/dist/client/describeCaughtError.d.ts.map +1 -0
  19. package/dist/client/index.js +1 -1
  20. package/dist/client/index.js.map +1 -1
  21. package/dist/client/init.d.ts.map +1 -1
  22. package/dist/facades/index.js +1 -1
  23. package/dist/http/index.js +1 -1
  24. package/dist/i18n/index.js +1 -1
  25. package/dist/kernel/index.js +1 -1
  26. package/dist/server/index.js +1 -1
  27. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +2 -3
  28. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
  29. package/dist/services/index.js +1 -1
  30. package/package.json +1 -1
  31. package/dist/chunk-dapd4vkd.js +0 -5
  32. /package/dist/{chunk-p8ypq16v.js.map → chunk-8adt2k7j.js.map} +0 -0
  33. /package/dist/{chunk-t56z2zec.js.map → chunk-gv7eh0wd.js.map} +0 -0
  34. /package/dist/{chunk-q0k1j5a4.js.map → chunk-n626761s.js.map} +0 -0
  35. /package/dist/{chunk-ggh1hzdb.js.map → chunk-qqh6h36y.js.map} +0 -0
  36. /package/dist/{chunk-11fc5nve.js.map → chunk-tm4kfnqh.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Dc as I3,Qc as P3,ic as y3,mc as V2,nc as f3,oc as F3,pd as _3,xc as B3}from"./chunk-11fc5nve.js";import{Dd as n}from"./chunk-hhka8j31.js";import{me as c2,oe as B2,re as t3,se as s3,te as L$,ve as T$}from"./chunk-wr7xq82n.js";import{Be as e2,Ce as _$,De as d3,Fe as c3,He as p3,Re as A,Se as i3,Te as l3,Ve as n3,We as C$,xe as b$,ye as u3}from"./chunk-nbdjbde4.js";import{Ze as B}from"./chunk-ptm1d4vp.js";import{Dh as J$,Eh as F$,Jf as O$,Jh as C2,Kf as p2,Kh as S2,Lh as k3,Mg as $3,Mh as q2,Nh as T2,Of as N2,Oh as R2,Pf as K2,Ph as S,Qh as O,Rh as b,Sh as E3,Th as M2,Uh as R,Vh as b3,Xg as s2,Zg as s,_h as M$,bh as Z$,ch as o2,dh as z$,eh as G$,fg as m2,ih as f2,jf as r2,jh as E2,kf as U$,lf as v2,nh as b2,oh as W$,pf as M3,ph as X2,qg as H2,qh as X$,rg as g2,rh as Y$,sf as k$,sg as M,sh as y2,tf as y$,th as $2,vg as N$,wf as B$,wg as Q$,wh as v$,xg as H$,xh as o,yh as d2,zf as I$,zg as h}from"./chunk-t56z2zec.js";import{Pj as N3,Tj as W2,kj as d,zj as t2}from"./chunk-dapd4vkd.js";import{Vj as a3}from"./chunk-2kt5kgaq.js";import{$j as l,dk as R$,ek as I2,fk as g}from"./chunk-gx5yhz2m.js";import{nk as u}from"./chunk-vq0gcvcy.js";import{tk as u2}from"./chunk-cyxsmd4q.js";import{Ak as F2,Bk as n2,Ek as A$,wk as j$,xk as i2}from"./chunk-qbm49b1t.js";import{Sk as r3,Xk as e3}from"./chunk-k5vt2kz6.js";import{ll as m3,nl as c,zl as G2}from"./chunk-z5wwhgsg.js";import{Bl as q}from"./chunk-mbfjxyq0.js";import{Hl as q$}from"./chunk-kss2kkmm.js";import{nm as E$}from"./chunk-n26d4z3t.js";import{Dm as l2}from"./chunk-gm14dthh.js";import{Km as J2,Nm as E}from"./chunk-xac2vwtq.js";import{Wm as h2}from"./chunk-w31afsrx.js";import{kn as $$}from"./chunk-jzg9zdtj.js";var h$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class _ extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var Z3=/^[A-Za-z0-9_-]{1,64}$/,m$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,z3=4000,k=1e5,u$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function D9($){return L3.get($)}class t{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=l$(z.files),this.featureOn=z.featureOn??K2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,d$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(_2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(K3(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(K3(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={}){_2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`There is no tool named "${Z}".`,"unknown-tool");throw new _(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!Y2(X))throw new m(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,V=K.inputSchema.safeParse(z);if(V.ok===!1)throw new _(`Invalid arguments for "${Z}": ${V.errors.join(", ")}`);let U=V.value,Q={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,Q),{path:N}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(N!==K.url)throw new _(`"${Z}" has nothing at ${H}.`,404);let P={};for(let D of Y.jsonKeys)if(U[D]!==void 0)P[D]=U[D];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,Q);else if(K.method==="GET")J=z8(P);else if(Y.jsonKeys.length>0)I=P;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,L={...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 D=J?`${H}?${J}`:H;T=Object.keys(L).length>0?await this.dispatcher.dispatchAs($.req,K.method,D,I,L):await this.dispatcher.dispatchAs($.req,K.method,D,I)}catch(D){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,D),new _(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await J3(Z,T);return await this.project(Y,Q,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!Z3.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(m$)].map(([,F,C])=>({name:F,modifier:C})),V=X.params??{};for(let F of K)if(!(F.name in V))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,C]of Object.entries(V)){if(!K.some((w)=>w.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(U3(C))a$(z,`params.${F}`,C);else V3(z,`params.${F}`,C)}let U=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(Q.properties)}let H=Object.entries(X.files??{}).map(([F,C])=>({name:F,binder:C}));for(let F of H)V3(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=Q3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(F,C)=>{if(F in P)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);P[F]=C},J=new Map,j=new Map;for(let F of K){let C=V[F.name];if(C==="input"){let w=l.string().describe(`The ":${F.name}" segment of the url.`);I(F.name,F.modifier==="?"||F.modifier==="*"?w.optional():w)}else if(U3(C)){let w=C.as??F.name;I(w,C.input),j.set(F.name,{key:w,param:C})}else J.set(F.name,C)}let L={};for(let F of H)if(F.binder==="input")I(F.name,l.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),L[F.name]=this.remoteFileSchema();let T=[...Object.keys(P),...H.map((F)=>F.name)];for(let F of new Set(T))if(U.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let D=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:H3(X.input,Q,l.object(P)),...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=!H.every((F)=>F.binder==="input")?null:H.length===0?D:Object.freeze({...D,inputSchema:H3(X.input,Q,l.object($8(P,Object.keys(L))),L)});return{kind:"route",descriptor:D,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:H,jsonKeys:U,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],V={};for(let U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let Q=Y[U];if(Q===void 0||Q===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof Q!=="string")K.push(`a file's "${U}" must be a string`);else V[U]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:V}};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(!Z3.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((V)=>typeof V!=="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:Q3(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},V;try{V=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof V!=="object"||V===null)return!0;let U=G.signal??new AbortController().signal;return Y3(X,Y.value,X3(W3(X,V,U,[])))}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(_2($),$.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 _(`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 _(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},V=(x,F)=>{if(!W.progress)return;let C;try{C=$.meta.remote?.progress?$.meta.remote.progress(x,F):p$(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 G3(this.runNative($,{...K,ctx:G},G),V)}let U=$.meta.remote,Q=await this.bind($,"the remote context",()=>U.context(K));if(typeof Q!=="object"||Q===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,Q),new _(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,N=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=N.length===0?new AbortController().signal:N.length===1?N[0]:AbortSignal.any(N),I=[],J=W3($,Q,P,I);if(!W.approved&&Y2($)&&await Y3($,K.input,X3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await G3(this.runNative($,{...K,ctx:J},J),V,P)}catch(x){if(P.aborted&&x===P.reason){if(W.signal?.aborted)throw new _(`"${X}" was cancelled.`,499);throw new _(`"${X}" did not finish within ${H} ms.`,504)}if(x instanceof _)throw x;if(x instanceof n||x instanceof m)throw new _(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new _(`"${X}" failed on the server.`,500)}let L=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new _(`"${X}" failed on the server.`,500)};if(B3(j))throw L("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(x){throw L(`could not read an image it showed: ${x}`)}let D=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(D);if(x.ok===!1)throw L(`answered what its output schema refuses: ${x.errors.join(", ")}`);D=x.value}for(let x of T)W.images?.(x);if(D===void 0)return null;if(typeof D==="string")return D.length>k?`${D.slice(0,k)}\u2026 [cut at ${k} of ${D.length} characters]`:D;let Z2=JSON.stringify(D);if(Z2!==void 0&&Z2.length>k)return`${Z2.slice(0,k)}\u2026 [cut at ${k} of ${Z2.length} characters]`;return D}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),V;if(Y||K){if(V=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)),V===void 0||V===null||V==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(V)}.`),new _(`"${$.descriptor.name}" failed on the server.`,500)}else V=z[X.name];let U=`:${X.name}${X.modifier}`;if(V===void 0||V===null||V===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new _(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${U}`,"");continue}W=W.replace(U,Z8($.descriptor.name,X,String(V)))}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[V,U]of Object.entries(Z))L2(K,V,U);for(let V of $.fileFields)K.append(V.name,await this.remoteFile(X,V.name,G[V.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,V]of Object.entries(Z))L2(Y,K,V);for(let K of $.fileFields){let V=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof V!=="string"||V==="")throw new _(`"${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(V))}return Y}async remoteFile($,Z,z){let G=(Q)=>new _(`"${Z}" of "${$}" ${Q}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!n$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!t$.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",V=typeof W.url==="string";if(K===V)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=W.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-o$(Q)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!s$.test(Q))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let Q=await N3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw G(`could not be fetched: ${U.host} answered ${Q.status}.`);let H=await Q.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(Q){if(Q instanceof _)throw Q;throw G(`could not be fetched from ${U.host}: ${Q instanceof Error?Q.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(h$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!g$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:V}]of this.plans)if(V.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 J3(G,z);let X=(H,N)=>{if(N===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,N);return new _(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),V=null;if(K!=="")try{V=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let U=V;if($.result)try{U=await $.result(V,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let Q=JSON.stringify(U);if(Q!==void 0&&Q.length>k)return`${Q.slice(0,k)}\u2026 [cut at ${k} of ${Q.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new _(`"${$.descriptor.name}" failed on the server.`,500)}}}function d$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function c$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function G3($,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(!c$($))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 p$($,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 W3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(Q)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},U={put:async(Q,H={})=>{if(!H.showModel)return K("attachment store")();let N=H.mimeType||Q.type;if(!/^image\//i.test(N))throw new n(`"${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 P=Q.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:N}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(Q instanceof File?Q.name:"image"),mimeType:N,size:Q.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(Q)=>_3({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:I3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:F3().meter}}function Y2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function X3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Y3($,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 _2($){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 K3($,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 i$=10485760;function l$($){let Z=$?.maxBytes??i$;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 n$($){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 t$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function o$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function U3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function a$($,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 r$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function e$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function Q3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?e$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!r$.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 H3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([V,U])=>[V,U.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(V)=>{if(typeof V!=="object"||V===null||Array.isArray(V))return{ok:!1,errors:["expected an object"]};let U=[],Q={};if($){let N=$.safeParse(V);if(N.ok===!1)U.push(...N.errors);else Q={...N.value}}let H=z.safeParse(V);if(H.ok===!1)U.push(...H.errors);else Q={...Q,...H.value};for(let[N,P]of Object.entries(G)){let I=V[N];if(I===void 0){U.push(`"${N}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((j)=>`${N}: ${j}`));else Q[N]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(V){let U=K(V);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function $8($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function Z8($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new _(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function L2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)L2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function z8($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function J3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!u$.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>k)return`${W.slice(0,k)}\u2026 [cut at ${k} 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 _(`"${$}" 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 _(`"${$}" failed on the server.`,Z.status)}import{createHash as G8,randomBytes as W8,timingSafeEqual as X8}from"crypto";function O2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class Y8{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`${$}${W8(32).toString("base64url")}`}static hash($){return G8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&X8(z,G)}async resolve($){let Z=O2($);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 w3,randomBytes as j3}from"crypto";import{createHmac as K8,timingSafeEqual as V8}from"crypto";function j2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function D2($,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"),V=O3($,Z,X);if(K.length!==V.length||!V8(K,V))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function O3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var A2="gemi.mcp.request-state.v1",D3="gemi.mcp.session.v1",U8=86400000,A3=600000,x3="gemi_approval",x2=2000,Q8={limit:600,window:60},H8={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=F8(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,V2(A2),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??Q8,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 y3,this.approvalTimeoutMs=Z.approvalTimeoutMs??A3,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 O(S.InvalidRequest,"Origin not allowed.")),403);let G=z?N8(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 C3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return C3(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(O2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof Q2)return v(b(null,new O(S.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new O(S.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof O){let K=R(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 O(S.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=E3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},V=R(K._meta)?K._meta:{};if(typeof V[q2]==="string"){if(b3($,Y,V[q2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),q3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new O(S.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),Q=$.headers.get("mcp-protocol-version");if(Q!==null&&Q!==U.state.v)throw new O(S.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,N=new AbortController;this.inflight.set(H,N);let P=AbortSignal.any([N.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),q3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:k3,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 O(S.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 O(S.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[R2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=S2.includes(G)?G:S2[0],X=R(Z.capabilities)?Z.capabilities:{},Y={v:W,e:S3(X.elicitation),p:U2(z),exp:Date.now()+U8},K=j2(D3,"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 O(S.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=D2(D3,"gms1",z);if(!G||G.p!==U2(Z))throw new O(S.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new O(S.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 O?X.message:"Internal error.",!(X instanceof O))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,L)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(L!==void 0)G.error=L},V=(await this.registry.available(W,{names:[Z]}))[0];if(!V)throw Y("unknown-tool",`Unknown tool: ${Z}`),new O(S.InvalidParams,`Unknown tool: ${Z}`);if(V.requiresApproval){let J=V.inputSchema.safeParse(z);if(J.ok===!1){let L=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(L),this.toolResult($,{content:[{type:"text",text:L}],isError:!0})}if($.era.modern&&R($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let L=await this.approval($,V,z,Y,G);if(L.kind==="answer")return L.result;G.approved=!0}}let U=P8($),Q=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>Q.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof _){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let L=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,L),new O(S.InvalidParams,L)}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 H==="string"?H:JSON.stringify(H??null),P=V.outputSchema&&($.era.modern||R(H))?{structuredContent:H}:{},I=[...Q.length>0&&H===null?[]:[{type:"text",text:N}],...Q];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(N,P="approval-declined")=>{return G(P,N),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}},K=(N,P)=>{return G(N,P.message),P};if($.era.modern){let N=R($.params._meta)?$.params._meta:{},P=R(N[T2])?N[T2]:{},I=R($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=B8(z);if(I&&J!==void 0){let T=D2(A2,"grs1",J);if(!T||T.p!==U2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new O(S.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new O(S.InvalidParams,"requestState has already been used."));return T3(I[x3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!S3(P.elicitation))throw K("approval-unavailable",new O(S.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let L={p:U2($.principal),t:Z.name,a:j,n:j3(16).toString("base64url"),exp:Date.now()+A3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[x3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:j2(A2,"grs1",L),_meta:{[R2]:this.serverInfo}}}}let V=$.era;if(!V.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${j3(12).toString("base64url")}`,Q=V.sessionId,H=await new Promise((N)=>{let P=setTimeout(()=>{this.pending.delete(U),N(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),N(J)};this.pending.set(U,{session:Q,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:V.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&T3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let V=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:V},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new v3(()=>X.abort());return(async()=>{try{let V=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:V})}catch(V){if(V instanceof O)K.send(b($.id,V));else console.error("[gemi/mcp] The MCP endpoint failed:",V),K.send(b($.id,new O(S.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 O(S.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=M3(new d($,{},"api",this.endpoint.pathname)),z=await C2(`mcp-auth-failed:${Z}`,H8);return z===null?null:R3(z)}async spend($){if(!this.rateLimit)return null;let Z=await C2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:R3(Z)}}class v3{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{Dc as I3,Qc as P3,ic as y3,mc as V2,nc as f3,oc as F3,pd as _3,xc as B3}from"./chunk-tm4kfnqh.js";import{Dd as n}from"./chunk-hhka8j31.js";import{me as c2,oe as B2,re as t3,se as s3,te as L$,ve as T$}from"./chunk-wr7xq82n.js";import{Be as e2,Ce as _$,De as d3,Fe as c3,He as p3,Re as A,Se as i3,Te as l3,Ve as n3,We as C$,xe as b$,ye as u3}from"./chunk-nbdjbde4.js";import{Ze as B}from"./chunk-ptm1d4vp.js";import{Dh as J$,Eh as F$,Jf as O$,Jh as C2,Kf as p2,Kh as S2,Lh as k3,Mg as $3,Mh as q2,Nh as T2,Of as N2,Oh as R2,Pf as K2,Ph as S,Qh as O,Rh as b,Sh as E3,Th as M2,Uh as R,Vh as b3,Xg as s2,Zg as s,_h as M$,bh as Z$,ch as o2,dh as z$,eh as G$,fg as m2,ih as f2,jf as r2,jh as E2,kf as U$,lf as v2,nh as b2,oh as W$,pf as M3,ph as X2,qg as H2,qh as X$,rg as g2,rh as Y$,sf as k$,sg as M,sh as y2,tf as y$,th as $2,vg as N$,wf as B$,wg as Q$,wh as v$,xg as H$,xh as o,yh as d2,zf as I$,zg as h}from"./chunk-gv7eh0wd.js";import{Pj as N3,Tj as W2,kj as d,zj as t2}from"./chunk-pvs5qjs7.js";import{Vj as a3}from"./chunk-2kt5kgaq.js";import{$j as l,dk as R$,ek as I2,fk as g}from"./chunk-gx5yhz2m.js";import{nk as u}from"./chunk-vq0gcvcy.js";import{tk as u2}from"./chunk-cyxsmd4q.js";import{Ak as F2,Bk as n2,Ek as A$,wk as j$,xk as i2}from"./chunk-qbm49b1t.js";import{Sk as r3,Xk as e3}from"./chunk-k5vt2kz6.js";import{ll as m3,nl as c,zl as G2}from"./chunk-z5wwhgsg.js";import{Bl as q}from"./chunk-mbfjxyq0.js";import{Hl as q$}from"./chunk-kss2kkmm.js";import{nm as E$}from"./chunk-n26d4z3t.js";import{Dm as l2}from"./chunk-gm14dthh.js";import{Km as J2,Nm as E}from"./chunk-xac2vwtq.js";import{Wm as h2}from"./chunk-w31afsrx.js";import{kn as $$}from"./chunk-jzg9zdtj.js";var h$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class _ extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var Z3=/^[A-Za-z0-9_-]{1,64}$/,m$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,z3=4000,k=1e5,u$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L3=new WeakMap;function D9($){return L3.get($)}class t{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=l$(z.files),this.featureOn=z.featureOn??K2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,d$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(_2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(K3(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(K3(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={}){_2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`There is no tool named "${Z}".`,"unknown-tool");throw new _(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!Y2(X))throw new m(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,V=K.inputSchema.safeParse(z);if(V.ok===!1)throw new _(`Invalid arguments for "${Z}": ${V.errors.join(", ")}`);let U=V.value,Q={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,Q),{path:N}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(N!==K.url)throw new _(`"${Z}" has nothing at ${H}.`,404);let P={};for(let D of Y.jsonKeys)if(U[D]!==void 0)P[D]=U[D];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,Q);else if(K.method==="GET")J=z8(P);else if(Y.jsonKeys.length>0)I=P;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(Q)):void 0,L={...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 D=J?`${H}?${J}`:H;T=Object.keys(L).length>0?await this.dispatcher.dispatchAs($.req,K.method,D,I,L):await this.dispatcher.dispatchAs($.req,K.method,D,I)}catch(D){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,D),new _(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await J3(Z,T);return await this.project(Y,Q,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!Z3.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(m$)].map(([,F,C])=>({name:F,modifier:C})),V=X.params??{};for(let F of K)if(!(F.name in V))throw Error(`${z}: the path param "${F.name}" must be bound or declared "input".`);for(let[F,C]of Object.entries(V)){if(!K.some((w)=>w.name===F))throw Error(`${z}: "${F}" in params is not a param of the url.`);if(U3(C))a$(z,`params.${F}`,C);else V3(z,`params.${F}`,C)}let U=[],Q;if(X.input){if(Q=X.input.toJSONSchema(),Q.type!=="object"||!Q.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(Q.properties)}let H=Object.entries(X.files??{}).map(([F,C])=>({name:F,binder:C}));for(let F of H)V3(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=Q3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(F,C)=>{if(F in P)throw Error(`${z}: "${F}" is the input key of two params or files, and the model can only send one.`);P[F]=C},J=new Map,j=new Map;for(let F of K){let C=V[F.name];if(C==="input"){let w=l.string().describe(`The ":${F.name}" segment of the url.`);I(F.name,F.modifier==="?"||F.modifier==="*"?w.optional():w)}else if(U3(C)){let w=C.as??F.name;I(w,C.input),j.set(F.name,{key:w,param:C})}else J.set(F.name,C)}let L={};for(let F of H)if(F.binder==="input")I(F.name,l.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),L[F.name]=this.remoteFileSchema();let T=[...Object.keys(P),...H.map((F)=>F.name)];for(let F of new Set(T))if(U.includes(F))throw Error(`${z}: "${F}" is both an input field and a param or file, and the model can only send one.`);let D=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:H3(X.input,Q,l.object(P)),...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=!H.every((F)=>F.binder==="input")?null:H.length===0?D:Object.freeze({...D,inputSchema:H3(X.input,Q,l.object($8(P,Object.keys(L))),L)});return{kind:"route",descriptor:D,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:H,jsonKeys:U,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],V={};for(let U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let Q=Y[U];if(Q===void 0||Q===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof Q!=="string")K.push(`a file's "${U}" must be a string`);else V[U]=Q}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:V}};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(!Z3.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((V)=>typeof V!=="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:Q3(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},V;try{V=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof V!=="object"||V===null)return!0;let U=G.signal??new AbortController().signal;return Y3(X,Y.value,X3(W3(X,V,U,[])))}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(_2($),$.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 _(`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 _(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},V=(x,F)=>{if(!W.progress)return;let C;try{C=$.meta.remote?.progress?$.meta.remote.progress(x,F):p$(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 G3(this.runNative($,{...K,ctx:G},G),V)}let U=$.meta.remote,Q=await this.bind($,"the remote context",()=>U.context(K));if(typeof Q!=="object"||Q===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,Q),new _(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,N=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=N.length===0?new AbortController().signal:N.length===1?N[0]:AbortSignal.any(N),I=[],J=W3($,Q,P,I);if(!W.approved&&Y2($)&&await Y3($,K.input,X3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await G3(this.runNative($,{...K,ctx:J},J),V,P)}catch(x){if(P.aborted&&x===P.reason){if(W.signal?.aborted)throw new _(`"${X}" was cancelled.`,499);throw new _(`"${X}" did not finish within ${H} ms.`,504)}if(x instanceof _)throw x;if(x instanceof n||x instanceof m)throw new _(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new _(`"${X}" failed on the server.`,500)}let L=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new _(`"${X}" failed on the server.`,500)};if(B3(j))throw L("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(x){throw L(`could not read an image it showed: ${x}`)}let D=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(D);if(x.ok===!1)throw L(`answered what its output schema refuses: ${x.errors.join(", ")}`);D=x.value}for(let x of T)W.images?.(x);if(D===void 0)return null;if(typeof D==="string")return D.length>k?`${D.slice(0,k)}\u2026 [cut at ${k} of ${D.length} characters]`:D;let Z2=JSON.stringify(D);if(Z2!==void 0&&Z2.length>k)return`${Z2.slice(0,k)}\u2026 [cut at ${k} of ${Z2.length} characters]`;return D}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),V;if(Y||K){if(V=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)),V===void 0||V===null||V==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(V)}.`),new _(`"${$.descriptor.name}" failed on the server.`,500)}else V=z[X.name];let U=`:${X.name}${X.modifier}`;if(V===void 0||V===null||V===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new _(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${U}`,"");continue}W=W.replace(U,Z8($.descriptor.name,X,String(V)))}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[V,U]of Object.entries(Z))L2(K,V,U);for(let V of $.fileFields)K.append(V.name,await this.remoteFile(X,V.name,G[V.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,V]of Object.entries(Z))L2(Y,K,V);for(let K of $.fileFields){let V=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof V!=="string"||V==="")throw new _(`"${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(V))}return Y}async remoteFile($,Z,z){let G=(Q)=>new _(`"${Z}" of "${$}" ${Q}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!n$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!t$.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",V=typeof W.url==="string";if(K===V)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let Q=W.data.replace(/\s+/g,"");if(Math.floor(Q.length*3/4)-o$(Q)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(Q.length%4!==0||!s$.test(Q))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(Q,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let Q=await N3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!Q.ok)throw G(`could not be fetched: ${U.host} answered ${Q.status}.`);let H=await Q.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(Q){if(Q instanceof _)throw Q;throw G(`could not be fetched from ${U.host}: ${Q instanceof Error?Q.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(h$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!g$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:V}]of this.plans)if(V.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 J3(G,z);let X=(H,N)=>{if(N===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,N);return new _(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),V=null;if(K!=="")try{V=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let U=V;if($.result)try{U=await $.result(V,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let Q=JSON.stringify(U);if(Q!==void 0&&Q.length>k)return`${Q.slice(0,k)}\u2026 [cut at ${k} of ${Q.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new _(`"${$.descriptor.name}" failed on the server.`,500)}}}function d$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function c$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function G3($,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(!c$($))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 p$($,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 W3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(Q)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},U={put:async(Q,H={})=>{if(!H.showModel)return K("attachment store")();let N=H.mimeType||Q.type;if(!/^image\//i.test(N))throw new n(`"${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 P=Q.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:N}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(Q instanceof File?Q.name:"image"),mimeType:N,size:Q.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(Q)=>_3({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:I3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:P3(),meter:F3().meter}}function Y2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function X3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Y3($,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 _2($){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 K3($,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 i$=10485760;function l$($){let Z=$?.maxBytes??i$;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 n$($){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 t$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function o$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function U3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function a$($,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 r$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function e$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function Q3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?e$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!r$.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 H3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([V,U])=>[V,U.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(V)=>{if(typeof V!=="object"||V===null||Array.isArray(V))return{ok:!1,errors:["expected an object"]};let U=[],Q={};if($){let N=$.safeParse(V);if(N.ok===!1)U.push(...N.errors);else Q={...N.value}}let H=z.safeParse(V);if(H.ok===!1)U.push(...H.errors);else Q={...Q,...H.value};for(let[N,P]of Object.entries(G)){let I=V[N];if(I===void 0){U.push(`"${N}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((j)=>`${N}: ${j}`));else Q[N]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:Q}};return{toJSONSchema:()=>Y,safeParse:K,parse(V){let U=K(V);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function $8($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function Z8($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new _(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function L2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)L2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function z8($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function J3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!u$.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>k)return`${W.slice(0,k)}\u2026 [cut at ${k} 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 _(`"${$}" 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 _(`"${$}" failed on the server.`,Z.status)}import{createHash as G8,randomBytes as W8,timingSafeEqual as X8}from"crypto";function O2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class Y8{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`${$}${W8(32).toString("base64url")}`}static hash($){return G8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&X8(z,G)}async resolve($){let Z=O2($);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 w3,randomBytes as j3}from"crypto";import{createHmac as K8,timingSafeEqual as V8}from"crypto";function j2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O3($,Z,G).toString("base64url")}`}function D2($,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"),V=O3($,Z,X);if(K.length!==V.length||!V8(K,V))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function O3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var A2="gemi.mcp.request-state.v1",D3="gemi.mcp.session.v1",U8=86400000,A3=600000,x3="gemi_approval",x2=2000,Q8={limit:600,window:60},H8={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=F8(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,V2(A2),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??Q8,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 y3,this.approvalTimeoutMs=Z.approvalTimeoutMs??A3,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 O(S.InvalidRequest,"Origin not allowed.")),403);let G=z?N8(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 C3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return C3(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(O2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof Q2)return v(b(null,new O(S.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new O(S.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof O){let K=R(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 O(S.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=E3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},V=R(K._meta)?K._meta:{};if(typeof V[q2]==="string"){if(b3($,Y,V[q2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),q3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new O(S.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),Q=$.headers.get("mcp-protocol-version");if(Q!==null&&Q!==U.state.v)throw new O(S.InvalidRequest,`MCP-Protocol-Version ${Q} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,N=new AbortController;this.inflight.set(H,N);let P=AbortSignal.any([N.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),q3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:k3,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 O(S.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 O(S.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[R2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=S2.includes(G)?G:S2[0],X=R(Z.capabilities)?Z.capabilities:{},Y={v:W,e:S3(X.elicitation),p:U2(z),exp:Date.now()+U8},K=j2(D3,"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 O(S.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=D2(D3,"gms1",z);if(!G||G.p!==U2(Z))throw new O(S.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new O(S.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 O?X.message:"Internal error.",!(X instanceof O))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,L)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(L!==void 0)G.error=L},V=(await this.registry.available(W,{names:[Z]}))[0];if(!V)throw Y("unknown-tool",`Unknown tool: ${Z}`),new O(S.InvalidParams,`Unknown tool: ${Z}`);if(V.requiresApproval){let J=V.inputSchema.safeParse(z);if(J.ok===!1){let L=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(L),this.toolResult($,{content:[{type:"text",text:L}],isError:!0})}if($.era.modern&&R($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let L=await this.approval($,V,z,Y,G);if(L.kind==="answer")return L.result;G.approved=!0}}let U=P8($),Q=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>Q.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof _){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let L=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,L),new O(S.InvalidParams,L)}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 H==="string"?H:JSON.stringify(H??null),P=V.outputSchema&&($.era.modern||R(H))?{structuredContent:H}:{},I=[...Q.length>0&&H===null?[]:[{type:"text",text:N}],...Q];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(N,P="approval-declined")=>{return G(P,N),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:N}],isError:!0})}},K=(N,P)=>{return G(N,P.message),P};if($.era.modern){let N=R($.params._meta)?$.params._meta:{},P=R(N[T2])?N[T2]:{},I=R($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=B8(z);if(I&&J!==void 0){let T=D2(A2,"grs1",J);if(!T||T.p!==U2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new O(S.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new O(S.InvalidParams,"requestState has already been used."));return T3(I[x3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!S3(P.elicitation))throw K("approval-unavailable",new O(S.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let L={p:U2($.principal),t:Z.name,a:j,n:j3(16).toString("base64url"),exp:Date.now()+A3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[x3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:j2(A2,"grs1",L),_meta:{[R2]:this.serverInfo}}}}let V=$.era;if(!V.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${j3(12).toString("base64url")}`,Q=V.sessionId,H=await new Promise((N)=>{let P=setTimeout(()=>{this.pending.delete(U),N(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),N(J)};this.pending.set(U,{session:Q,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:V.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&T3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let V=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:V},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new v3(()=>X.abort());return(async()=>{try{let V=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:V})}catch(V){if(V instanceof O)K.send(b($.id,V));else console.error("[gemi/mcp] The MCP endpoint failed:",V),K.send(b($.id,new O(S.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 O(S.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=M3(new d($,{},"api",this.endpoint.pathname)),z=await C2(`mcp-auth-failed:${Z}`,H8);return z===null?null:R3(z)}async spend($){if(!this.rateLimit)return null;let Z=await C2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:R3(Z)}}class v3{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 Q2 extends Error{}async function J8($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new Q2;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 Q2;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 C3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function N8($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function F8($){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 w3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function B8($){return w3("sha256").update(f3($??{})).digest("base64url")}function S3($){if(!R($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function q3($){let Z=R($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function I8($,Z,z){if(Z.method!=="tools/call"||!z.e)return!1;let G=Z.params?.name;return typeof G==="string"&&$.descriptors({names:[G]})[0]?.requiresApproval===!0}function P8($){let z=(R($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function _8($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>x2?`${z.slice(0,x2)}\u2026 (${z.length-x2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Qa as m}from"./chunk-ba1h9pm6.js";import{createElement as j}from"react";function z(i,t){let u=Object.keys(t).sort((s,p)=>p.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(u.join("|"),"g");return i.replace(r,(s)=>t[s])}async function O(i,t,u=[],r){let s=[...u.map((n)=>`${i}/views/${n}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],p=new Set;for(let n of s){let e=t.moduleGraph.getModulesByFile(n);if(e)for(let d of e)p.add(d)}let b=[],l=[],g={};for(let n of p)if(n)for(let e of n.importedModules){if(e.file.includes("module.css"))g[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))l.push(e.file)}for(let n of l){let e=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),a="";if(d)a=z(g[n],e.default);b.push({isDev:!0,id:n,content:d?a:e.code})}return b.map((n,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Q(i=[]){return i.map((t,u)=>{return j("style",{key:u,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as f}from"fs";import{basename as q}from"path";import{networkInterfaces as k}from"os";var v={name:"gemi",version:"0.246.0",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./ai/voice":"./ai/voice/index.ts","./ai/testing":"./ai/testing/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./probe":"./probe/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=@azure/communication-email --external=@azure/identity --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/ai/voice dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"GEMI_AI_LIVE=1 bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0","happy-dom":"^21.0.4",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",sharp:"^0.35.5",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/communication-email":"^1.1.0","@azure/identity":"^4.0.0","@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2 || ^0.35.5",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/communication-email":{optional:!0},"@azure/identity":{optional:!0},"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var h=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],E=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,t)=>E?`\x1B[${i}m${t}\x1B[0m`:t,$=(i)=>c("1",i),x=(i)=>c("2",i),o=(i)=>c("36",i),G=(i)=>c("32",i),_=(i)=>c("35",i);function A(){return v.version??"?"}function J(i){for(let t of Object.values(k()))for(let u of t??[])if((u.family==="IPv4"||u.family===4)&&!u.internal)return`http://${u.address}:${i}`;return null}function L(i){return m(i).filter((t)=>f(t)).map((t)=>q(t))}function V(i){let{port:t,rootDir:u}=i,r=`http://localhost:${t}`,s=J(t),p=L(u),b=(g,n)=>` ${G("\u279C")} ${$(g.padEnd(9))}${n}`,l=["",...h.map((g)=>_(g)),"",` ${x("gemi")} ${o(`v${A()}`)}`,"",b("Local:",o(r)),b("Network:",s?o(s):x("unavailable")),b("Env:",p.length?p.join(", "):x("none")),""];console.log(l.join(`
2
+ import{Qa as m}from"./chunk-ba1h9pm6.js";import{createElement as j}from"react";function z(i,t){let u=Object.keys(t).sort((s,p)=>p.length-s.length).map((s)=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),r=new RegExp(u.join("|"),"g");return i.replace(r,(s)=>t[s])}async function O(i,t,u=[],r){let s=[...u.map((n)=>`${i}/views/${n}.tsx`),r?`${i}/views/${r}.tsx`:`${i}/views/RootLayout.tsx`],p=new Set;for(let n of s){let e=t.moduleGraph.getModulesByFile(n);if(e)for(let d of e)p.add(d)}let b=[],l=[],g={};for(let n of p)if(n)for(let e of n.importedModules){if(e.file.includes("module.css"))g[e.file]=e.ssrTransformResult.map.sourcesContent.join("");if(e.file.includes(".css"))l.push(e.file)}for(let n of l){let e=await t.transformRequest(n+"?direct"),d=n.includes("module.css"),a="";if(d)a=z(g[n],e.default);b.push({isDev:!0,id:n,content:d?a:e.code})}return b.map((n,e)=>{return j("style",{key:e,type:"text/css","data-vite-dev-id":n.id,dangerouslySetInnerHTML:{__html:n.content}})})}async function Q(i=[]){return i.map((t,u)=>{return j("style",{key:u,id:t?.id,type:"text/css",dangerouslySetInnerHTML:{__html:t.content}})})}import{existsSync as f}from"fs";import{basename as q}from"path";import{networkInterfaces as k}from"os";var v={name:"gemi",version:"0.246.2",private:!1,license:"MIT",author:"Enes Tufekci <enes@gemijs.dev>",repository:{type:"git",url:"git+https://github.com/nstfkc/gemi.git",directory:"packages/gemi"},bin:{gemi:"./dist/bin/gemi.js","gemi-orm-generator":"./dist/bin/orm-generator.js"},files:["dist/**/*","ide/typescript-plugin/package.json","skills/**/*"],module:!0,exports:{"./http":"./http/index.ts","./client":"./client/index.ts","./ai":"./ai/index.ts","./ai/client":"./ai/client/index.ts","./ai/voice":"./ai/voice/index.ts","./ai/testing":"./ai/testing/index.ts","./testing":"./testing/index.ts","./app":"./app/index.ts","./facades":"./facades/index.ts","./email":"./email/index.ts","./vite":"./dist/vite/index.mjs","./kernel":"./kernel/index.ts","./services":"./services/index.ts","./i18n":"./i18n/index.ts","./dictionary":"./i18n/dictionaryRuntime.ts","./server":"./server/index.ts","./config":"./config/index.ts","./container":"./container/index.ts","./foundation":"./foundation/index.ts","./database":"./database/index.ts","./orm":"./orm/index.ts","./support":"./support/index.ts","./probe":"./probe/index.ts","./console/run":"./console/run.ts","./queue/work":"./services/queue/work.ts","./stats/route-table":"./stats/route-table.ts","./ide/typescript-plugin":"./ide/typescript-plugin/index.ts","./bun/preload":"./bun/preload.ts","./bun/plugin":"./bun/plugin.ts","./vitest":"./vitest/index.ts"},scripts:{lint:"oxlint",typecheck:"tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.browser.json && tsc --noEmit -p ide/typescript-plugin/tsconfig.json",build:"NODE_ENV=production bun run build:core && bun run build:bin && bun run build:types && bun run build:client && bun run build:plugin && bun run build:ts-plugin && bun run build:client-types && bun run build:augmentation","build:core":"bun ./scripts/build.ts","build:bin":"bun build --outdir=./dist/bin --target=bun --external=vite --external=react-dom --external=react/jsx-runtime --external=bun --external=sharp --external=@azure/storage-blob --external=@azure/communication-email --external=@azure/identity --external=typescript --sourcemap ./bin/gemi.ts ./bin/orm-generator.ts && bun ./scripts/prepare-bin.ts","build:client":"rm -rf dist/client dist/testing dist/ai/client dist/ai/voice dist/chunks && vite build -c vite.client.config.mts","build:plugin":"vite build -c vite.plugin.config.mts","build:ts-plugin":"bun ./scripts/build-ts-plugin.ts","build:types":"tsc -p tsconfig.build.json","build:client-types":"tsc -p tsconfig.browser.json",test:"bun --bun x vitest","test:types":"vitest run --typecheck.only","test:live":"GEMI_AI_LIVE=1 bun --bun x vitest run ai/live","test:packaging":"bun --bun x vitest run --config vitest.packaging.config.ts","build:publish":"bun scripts/build-publish.ts",prepublishOnly:"echo 'Do not publish from this directory \u2014 its exports point at TS source. Run: bun run build:publish, then publish from .publish/' && exit 1","build:augmentation":"bun ./scripts/wire-augmentation.ts"},dependencies:{"@aws-sdk/client-s3":"^3.629.0","@aws-sdk/s3-request-presigner":"^3.629.0","ast-types":"^0.14.2",commander:"^12.1.0",history:"^5.3.0","jsx-email":"2.0.0-rc2.1","magic-string":"^0.30.17",open:"^10.1.0","react-error-boundary":"^6.0.0",recast:"^0.23.9",resend:"^6.12.3",satori:"^0.12.2","temporal-polyfill":"^0.2.5","twitter-api-v2":"^1.20.2","urlpattern-polyfill":"^10.0.0",uuid:"^9.0.1"},devDependencies:{"@babel/parser":"^7.25.4","@prisma/generator-helper":"^6.5.0","@repo/typescript-config":"*","@testing-library/react":"^16.3.2","@types/bun":"^1.3.14","@types/eslint":"^8.56.5","@types/node":"^20.11.24","@types/react":"^19.0.2","@types/react-dom":"^19.0.2",eslint:"^8.57.0","happy-dom":"^21.0.4",jsdom:"^30.0.1",oxlint:"^1.39.0",postgres:"^3.4.5",react:"19.2.3","react-dom":"19.2.3",sharp:"^0.35.5",typescript:"^5.7.3",vitest:"^4.0.0"},peerDependencies:{"@azure/communication-email":"^1.1.0","@azure/identity":"^4.0.0","@azure/storage-blob":"^12.28.0",react:">=19","react-dom":">=19",sharp:"^0.34.2 || ^0.35.5",typescript:">=5",vite:"^8.0.0",postgres:"^3.4.0"},peerDependenciesMeta:{"@azure/communication-email":{optional:!0},"@azure/identity":{optional:!0},"@azure/storage-blob":{optional:!0},typescript:{optional:!0},postgres:{optional:!0}}};var h=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551","\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551","\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551"," \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D"],E=Boolean(process.stdout.isTTY)&&!process.env.NO_COLOR,c=(i,t)=>E?`\x1B[${i}m${t}\x1B[0m`:t,$=(i)=>c("1",i),x=(i)=>c("2",i),o=(i)=>c("36",i),G=(i)=>c("32",i),_=(i)=>c("35",i);function A(){return v.version??"?"}function J(i){for(let t of Object.values(k()))for(let u of t??[])if((u.family==="IPv4"||u.family===4)&&!u.internal)return`http://${u.address}:${i}`;return null}function L(i){return m(i).filter((t)=>f(t)).map((t)=>q(t))}function V(i){let{port:t,rootDir:u}=i,r=`http://localhost:${t}`,s=J(t),p=L(u),b=(g,n)=>` ${G("\u279C")} ${$(g.padEnd(9))}${n}`,l=["",...h.map((g)=>_(g)),"",` ${x("gemi")} ${o(`v${A()}`)}`,"",b("Local:",o(r)),b("Network:",s?o(s):x("unavailable")),b("Env:",p.length?p.join(", "):x("none")),""];console.log(l.join(`
3
3
  `))}function I(i,t){return Error(`app/views/${i}.tsx is missing. gemi's auth routes render it because ${t} is on. Add the view, or turn that setting off in app/config/auth.ts.`)}function T(i=process.env.SERVER_IDLE_TIMEOUT){if(i===void 0||i.trim()==="")return 10;let t=Number(i.trim());if(!Number.isInteger(t)||t<0||t>255)throw Error(`SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 (0 disables the timeout), got ${JSON.stringify(i)}.`);return t}
4
4
  export{O as Z,Q as _,V as $,I as aa,T as ba};
5
5
 
6
- //# debugId=943155A7495B39F364756E2164756E21
6
+ //# debugId=09C19A8DE34FEFE564756E2164756E21
@@ -8,6 +8,6 @@
8
8
  "/**\n * Bun's default, and what both servers use when `SERVER_IDLE_TIMEOUT` is unset.\n */\nexport const DEFAULT_SERVER_IDLE_TIMEOUT = 10;\n\n/**\n * The `idleTimeout` (seconds) both `gemi dev` and `gemi start` pass to\n * `Bun.serve`, from `SERVER_IDLE_TIMEOUT` (#787).\n *\n * One reader for both servers, so a long-poll that works under `gemi start`\n * also works under `gemi dev`. Before this, only `httpProd` read the variable\n * and the dev server always ran at Bun's 10 seconds.\n *\n * It is the time a connection may stay silent, a response that has not started\n * included, before Bun closes it; `0` disables it. It does not apply to an\n * upgraded websocket (the HMR relay included), which has its own\n * `websocket.idleTimeout`.\n *\n * Unset or blank means the default. Anything that is not a whole number from 0\n * to 255 (Bun's own limits) fails the boot with the variable's name, instead\n * of Bun's \"expects idleTimeout to be an integer\", which does not say where the\n * value came from.\n */\nexport function serverIdleTimeout(raw: string | undefined = process.env.SERVER_IDLE_TIMEOUT): number {\n if (raw === undefined || raw.trim() === \"\") return DEFAULT_SERVER_IDLE_TIMEOUT;\n\n const seconds = Number(raw.trim());\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > 255) {\n throw new Error(\n `SERVER_IDLE_TIMEOUT must be a whole number of seconds from 0 to 255 ` +\n `(0 disables the timeout), got ${JSON.stringify(raw)}.`,\n );\n }\n return seconds;\n}\n"
9
9
  ],
10
10
  "mappings": ";yCAAA,wBAAS,cAGT,SAAS,CAAc,CAAC,EAAc,EAAwC,CAC5E,IAAM,EAAc,OAAO,KAAK,CAAM,EACnC,KAAK,CAAC,EAAG,IAAM,EAAE,OAAS,EAAE,MAAM,EAClC,IAAI,CAAC,IAAQ,EAAI,QAAQ,sBAAuB,MAAM,CAAC,EAGpD,EAAQ,IAAI,OAAO,EAAY,KAAK,GAAG,EAAG,GAAG,EAEnD,OAAO,EAAK,QAAQ,EAAO,CAAC,IAAU,EAAO,EAAM,EAGrD,eAAsB,CAAe,CACnC,EACA,EACA,EAAyB,CAAC,EAE1B,EACA,CACA,IAAM,EAAQ,CACZ,GAAG,EAAa,IAAI,CAAC,IAAS,GAAG,WAAgB,OAAU,EAC3D,EAAS,GAAG,WAAgB,QAAe,GAAG,wBAChD,EAEM,EAAU,IAAI,IACpB,QAAW,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAK,YAAY,iBAAiB,CAAI,EAClD,GAAI,EACF,QAAW,KAAK,EAAK,EAAQ,IAAI,CAAC,EAItC,IAAM,EAAS,CAAC,EACV,EAAa,CAAC,EACd,EAA2C,CAAC,EAClD,QAAW,KAAO,EAChB,GAAI,EACF,QAAW,KAAY,EAAI,gBAAiB,CAC1C,GAAI,EAAS,KAAK,SAAS,YAAY,EACrC,EAAiB,EAAS,MAAQ,EAAS,mBAAmB,IAAI,eAAe,KAAK,EAAE,EAE1F,GAAI,EAAS,KAAK,SAAS,MAAM,EAC/B,EAAW,KAAK,EAAS,IAAI,EAMrC,QAAW,KAAiB,EAAY,CACtC,IAAM,EAAY,MAAM,EAAK,iBAAiB,EAAgB,SAAS,EAEjE,EAAc,EAAc,SAAS,YAAY,EAEnD,EAAuB,GAE3B,GAAI,EACF,EAAuB,EACrB,EAAiB,GAGhB,EAA6D,OAChE,EAGF,EAAO,KAAK,CACV,MAAO,GACP,GAAI,EACJ,QAAS,EAAc,EAAuB,EAAU,IAC1D,CAAC,EAGH,OAAO,EAAO,IAAI,CAAC,EAAO,IAAM,CAC9B,OAAO,EAAc,QAAS,CAC5B,IAAK,EACL,KAAM,WACN,mBAAoB,EAAM,GAC1B,wBAAyB,CAAE,OAAQ,EAAM,OAAQ,CACnD,CAAC,EACF,EAGH,eAAsB,CAAY,CAAC,EAAS,CAAC,EAAG,CAC9C,OAAO,EAAO,IAAI,CAAC,EAAO,IAAM,CAC9B,OAAO,EAAc,QAAS,CAC5B,IAAK,EACL,GAAI,GAAO,GACX,KAAM,WACN,wBAAyB,CAAE,OAAQ,EAAM,OAAQ,CACnD,CAAC,EACF,EC3FH,qBAAS,WACT,mBAAS,aACT,4BAAS,kqIAKT,IAAM,EAAM,CACV,oKACA,mLACA,yKACA,oKACA,mLACA,yJACF,EAEM,EAAW,QAAQ,QAAQ,OAAO,KAAK,GAAK,CAAC,QAAQ,IAAI,SACzD,EAAQ,CAAC,EAAc,IAC3B,EAAW,QAAQ,KAAQ,WAAgB,EACvC,EAAO,CAAC,IAAc,EAAM,IAAK,CAAC,EAClC,EAAM,CAAC,IAAc,EAAM,IAAK,CAAC,EACjC,EAAO,CAAC,IAAc,EAAM,KAAM,CAAC,EACnC,EAAQ,CAAC,IAAc,EAAM,KAAM,CAAC,EACpC,EAAU,CAAC,IAAc,EAAM,KAAM,CAAC,EAE5C,SAAS,CAAW,EAAW,CAC7B,OAAQ,EAA6B,SAAW,IAGlD,SAAS,CAAU,CAAC,EAAsC,CACxD,QAAW,KAAU,OAAO,OAAO,EAAkB,CAAC,EACpD,QAAW,KAAS,GAAU,CAAC,EAG7B,IADa,EAAM,SAAW,QAAW,EAAM,SAAuB,IAC1D,CAAC,EAAM,SAAU,MAAO,UAAU,EAAM,WAAW,IAGnE,OAAO,KAGT,SAAS,CAAc,CAAC,EAA2B,CACjD,OAAO,EAAS,CAAO,EACpB,OAAO,CAAC,IAAS,EAAW,CAAI,CAAC,EACjC,IAAI,CAAC,IAAS,EAAS,CAAI,CAAC,EAG1B,SAAS,CAAkB,CAAC,EAGhC,CACD,IAAQ,OAAM,WAAY,EACpB,EAAQ,oBAAoB,IAC5B,EAAU,EAAW,CAAI,EACzB,EAAM,EAAe,CAAO,EAE5B,EAAM,CAAC,EAAe,IAC1B,KAAK,EAAM,QAAE,MAAM,EAAK,EAAM,OAAO,CAAC,CAAC,IAAI,IAEvC,EAAM,CACV,GACA,GAAG,EAAI,IAAI,CAAC,IAAS,EAAQ,CAAI,CAAC,EAClC,GACA,KAAK,EAAI,MAAM,KAAK,EAAK,IAAI,EAAY,GAAG,IAC5C,GACA,EAAI,SAAU,EAAK,CAAK,CAAC,EACzB,EAAI,WAAY,EAAU,EAAK,CAAO,EAAI,EAAI,aAAa,CAAC,EAC5D,EAAI,OAAQ,EAAI,OAAS,EAAI,KAAK,IAAI,EAAI,EAAI,MAAM,CAAC,EACrD,EACF,EAEA,QAAQ,IAAI,EAAI,KAAK;AAAA,CAAI,CAAC,ECjErB,SAAS,CAAwB,CAAC,EAAc,EAAoB,CACzE,OAAW,MACT,aAAa,0DAA6D,wEAE5E,ECcK,SAAS,CAAiB,CAAC,EAA0B,QAAQ,IAAI,oBAA6B,CACnG,GAAI,IAAQ,QAAa,EAAI,KAAK,IAAM,GAAI,MArBH,IAuBzC,IAAM,EAAU,OAAO,EAAI,KAAK,CAAC,EACjC,GAAI,CAAC,OAAO,UAAU,CAAO,GAAK,EAAU,GAAK,EAAU,IACzD,MAAU,MACR,qGACmC,KAAK,UAAU,CAAG,IACvD,EAEF,OAAO",
11
- "debugId": "943155A7495B39F364756E2164756E21",
11
+ "debugId": "09C19A8DE34FEFE564756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{Wj as _,Xj as $1,Yj as X1}from"./chunk-2kt5kgaq.js";import{Zj as N1,bk as T0}from"./chunk-gx5yhz2m.js";import{kk as R1,nk as f}from"./chunk-vq0gcvcy.js";import{Jm as J0}from"./chunk-zez3fjnf.js";import{Nm as Z0}from"./chunk-xac2vwtq.js";import{in as O0}from"./chunk-ket76475.js";import{qn as I4}from"./chunk-748evey0.js";class v1{static kind="controller";constructor(){}}class S0 extends v1{}function P1(Q){let Z=new Map;if(!Q)return Z;for(let J of Q.split(";")){let K=J.indexOf("=");if(K===-1)continue;let $=J.slice(0,K).trim();if(!$)continue;Z.set($,J.slice(K+1).trim())}return Z}function E4(Q){return P1(Q.headers.get("cookie"))}function m(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function f1(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let K=Z.slice(6).split(",").map((V)=>V.trim()).filter((V)=>V!=="");if(K.length!==1)return null;let $=K[0],X=$.indexOf("-");if(X===-1)return null;let Y=$.slice(0,X),H=$.slice(X+1);if(Y===""){let V=m(H);if(V===null)return null;return{kind:"suffix",suffixLength:V}}let G=m(Y);if(G===null)return null;if(H==="")return{kind:"offset",start:G,end:null};let W=m(H);if(W===null||W<G)return null;return{kind:"offset",start:G,end:W}}function y1(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let J,K;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;J=Math.max(0,Z-Q.suffixLength),K=Z-1}else{if(Q.start>=Z)return null;if(J=Q.start,K=Q.end===null?Z-1:Math.min(Q.end,Z-1),K<J)return null}return{start:J,end:K,length:K-J+1}}function q4(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function b4(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let J=m(Z[1]),K=m(Z[2]),$=m(Z[3]);if(J===null||K===null||$===null||K<J)return null;return{start:J,end:K,total:$}}function v4(Q,Z,J){return`bytes ${Q}-${Z}/${J}`}function g1(Q){return`bytes */${Q}`}import{randomBytes as k0}from"crypto";var D1=new WeakMap;function M1(Q){let Z=D1.get(Q);if(!Z)Z=k0(16).toString("base64"),D1.set(Q,Z);return Z}function h4(Q){return D1.get(Q)}function m4(){let Q=f.getStore()?.req?.rawRequest;if(!Q)throw Error("cspNonce() is only available while a request is being handled.");return M1(Q)}class o extends _{errors={};constructor(Q){super("Validation error");this.name="ValidationError",this.errors=Q,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:Q,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function m1(Q){let[Z,J]=Q.match(/\d+|\D+/g)??[];if(!Z||!J)return 0;let K=Number.parseInt(Z);switch(J){case"B":return K;case"KB":return K*1024;case"MB":return K*1024*1024;case"GB":return K*1024*1024*1024;case"TB":return K*1024*1024*1024*1024;default:return 0}}function E0(Q){switch(Q){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return Q}}function h1(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function U1(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var x0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class q extends Error{name="InvalidValidationRuleError"}function K1(Q,Z){let J=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN(J))throw new q(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return J}function c1(Q){let Z=!1,J=0;for(let K of Object.values(Q)){if(!K||typeof K!=="object")continue;for(let $ of Object.keys(K)){let X=$.indexOf(":"),Y=X===-1?$:$.slice(0,X);if(Y!=="file"&&Y!=="fileType"&&Y!=="fileSize")continue;if(Z=!0,Y==="fileSize")J+=m1($.slice(X+1))}}return Z?J:null}function p1(Q){let Z=Q.indexOf(":"),J=Z===-1?Q:Q.slice(0,Z),K=Z===-1?void 0:Q.slice(Z+1);switch(J){case"required":return($)=>{if($ instanceof Blob)return $.size>0;if($===null||$===void 0)return!1;if(typeof $==="string"||Array.isArray($))return $.length>0;return!0};case"string":return($)=>typeof $==="string";case"boolean":return($)=>typeof $==="boolean";case"number":return($)=>U1($);case"password":return($)=>{return typeof $==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test($)};case"min":{let $=K1(J,K);return(X)=>{let Y=h1(X);return Y!==void 0&&Y>=$}}case"max":{let $=K1(J,K);return(X)=>{let Y=h1(X);return Y!==void 0&&Y<=$}}case"gte":{let $=K1(J,K);return(X)=>U1(X)&&X>=$}case"lte":{let $=K1(J,K);return(X)=>U1(X)&&X<=$}case"email":return($)=>{return typeof $==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($)};case"file":return($)=>{return $ instanceof Blob};case"fileType":{if(!K)throw new q('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let $=E0(K);return(X)=>X instanceof Blob&&X.type.startsWith($)}case"fileSize":{let $=m1(K??"");if($===0&&!/^0+(B|KB|MB|GB|TB)$/.test(K??""))throw new q(`Validation rule "fileSize:${K??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(X)=>X instanceof Blob&&X.size<=$}case"array":return($)=>Array.isArray($);case"object":return($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&!($ instanceof Blob);case"in":{let $=(K??"").split(",").filter((X)=>X!=="");if($.length===0)throw new q('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(X)=>typeof X==="string"&&$.includes(X)}default:throw new q(`Unknown validation rule "${Q}". Known rules: ${x0.join(", ")}`)}}class L1 extends _{limit;constructor(Q){super("The request body is too large.",{status:413});this.limit=Q}}var u1={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function i4(Q){if(typeof Q==="number"){if(Number.isFinite(Q)&&Q>=0)return Math.floor(Q);if(Q===1/0)return 1/0}else{let Z=Q.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in u1)))return Math.floor(Number(J[1])*(u1[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify(Q)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var p=new WeakMap;function n4(Q){return p.has(Q)}function o4(Q){return p.get(Q)?.limit??null}function s4(Q){let Z=p.get(Q);return Z?Z.read>Z.limit:!1}function q0(Q){let Z=Q.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function C1(Q,Z){let J=q0(Q);if(J!==null&&J>Z)throw new L1(Z)}function a4(Q,Z,J={}){let K=J.uploadLimit??null,$=p.get(Q);if($)$.limit=Z,$.uploadLimit=K;else{let X={limit:Z,uploadLimit:K,read:0,stream:void 0,used:!1};p.set(Q,X),v0(Q,X)}if(J.checkDeclared!==!1)C1(Q,Z)}function l1(Q,Z){let J=p.get(Q);if(!J||J.uploadLimit===null||J.used||J.read>0)return;J.limit=Math.max(J.limit,J.uploadLimit,Z+J.limit),J.uploadLimit=null}function b0(Q){return Reflect.get(Object.getPrototypeOf(Q),"body",Q)??null}function B1(Q,Z){if(Z.stream!==void 0)return Z.stream;let J=b0(Q);if(!J)return Z.stream=null;let K;return Z.stream=new ReadableStream({async pull($){K??=J.getReader();let{done:X,value:Y}=await K.read();if(X){$.close();return}if(Z.read+=Y.byteLength,Z.read>Z.limit){let H=new L1(Z.limit);$.error(H),K.cancel(H).catch(()=>{});return}$.enqueue(Y)},cancel($){return K?K.cancel($):J.cancel($)}},{highWaterMark:0}),Z.stream}async function c(Q,Z){if(C1(Q,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=B1(Q,Z);if(!J)return new Uint8Array(0);let K=J.getReader(),$=[],X=0;for(;;){let{done:G,value:W}=await K.read();if(G)break;$.push(W),X+=W.byteLength}let Y=new Uint8Array(X),H=0;for(let G of $)Y.set(G,H),H+=G.byteLength;return Y}function d1(Q){return Q.headers.get("Content-Type")??""}function v0(Q,Z){let J=(K,$)=>Object.defineProperty(Q,K,{configurable:!0,...$});J("body",{get:()=>B1(Q,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf(Q),"bodyUsed",Q)}),J("bytes",{value:()=>c(Q,Z)}),J("arrayBuffer",{value:async()=>{let K=await c(Q,Z);return K.buffer.slice(K.byteOffset,K.byteOffset+K.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await c(Q,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await c(Q,Z)))}),J("blob",{value:async()=>new Blob([await c(Q,Z)],{type:d1(Q)})}),J("formData",{value:async()=>new Response(await c(Q,Z),{headers:{"Content-Type":d1(Q)}}).formData()}),J("clone",{value:()=>{C1(Q,Z.limit);let K=B1(Q,Z),$=null;if(K){let[X,Y]=K.tee();Z.stream=X,$=Y}return new Request(Q.url,{method:Q.method,headers:Q.headers,body:$,signal:Q.signal,duplex:"half"})}})}function i1(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),J=Z.trim().toLowerCase();return J===""?null:J}function n1(Q){if(Q===null)return!1;if(Q==="application/json")return!0;let Z=Q.indexOf("/");return Z>0&&Q.endsWith("+json")&&Q.length>Z+1+5}var s=new WeakMap;function e4(Q,Z,J,K){s.set(Q,{clientAddress:Z,...J?{grant:Object.freeze({...J,scopes:Object.freeze([...J.scopes])})}:{},...K?{progress:K}:{}})}function o1(Q){return s.get(Q)?.progress}function s1(Q){return s.get(Q)?.grant}function a1(Q){return s.has(Q)}function QQ(Q){return s.get(Q)?.clientAddress}var t1=new WeakMap;function JQ(Q,Z){t1.set(Q,Z)}function r1(Q){return t1.get(Q)??null}var _1=new WeakMap;function KQ(Q,Z){let J=_1.get(Q)??[];if(!J.includes(Z))_1.set(Q,[...J,Z])}function $Q(Q){return _1.get(Q)??[]}class u{data;constructor(Q){this.data=Q}get(Q){return this.data[Q]}has(Q){return this.data[Q]!==void 0}toJSON(){return this.data}}function e1(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function f0(Q,Z){if(!Z.includes(".")||Object.hasOwn(Q,Z))return[{path:[Z],value:Q[Z]}];let J=[{path:[],value:Q}];for(let K of Z.split(".")){let $=[];for(let{path:X,value:Y}of J){if(K==="*"){if(Array.isArray(Y))Y.forEach((H,G)=>$.push({path:[...X,G],value:H}));else if(e1(Y))for(let[H,G]of Object.entries(Y))$.push({path:[...X,H],value:G});continue}if(Array.isArray(Y)&&/^\d+$/.test(K)){$.push({path:[...X,Number(K)],value:Y[Number(K)]});continue}$.push({path:[...X,K],value:e1(Y)&&Object.hasOwn(Y,K)?Y[K]:void 0})}J=$}return J}function Q0(Q){return Q.join(".")}class y0{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(Q,Z,J,K){if(!Q){let G=f.getStore().req;this.params=G.params,this.rawRequest=G.rawRequest,this.kind=G.kind,this.routePath=G.routePath,this.domain=G.domain??null,this.state=G.state??new R1}else this.params=Z,this.rawRequest=Q,this.routePath=K,this.kind=J??"api",this.domain=r1(Q),this.state=new R1;this.headers=this.rawRequest.headers;let $=P1(this.rawRequest.headers.get("Cookie")),X=new URL(this.rawRequest.url),Y=new Map;for(let[G,W]of X.searchParams)if(Y.has(G)){let V=Y.get(G);if(Array.isArray(V))V.push(W),Y.set(G,V);else Y.set(G,[V,W])}else Y.set(G,W);let H=Object.fromEntries(Y.entries());this.search=new u(H),this.cookies=$}locale(){let Q=f.getStore();if(Q.locale)return Q.locale;let Z=Z0(J0);return Z.isLocaleAware?Z.detectLocale(Q.req):Q.locale}ctx(){return f.getStore()}isModelOriginated(){return a1(this.rawRequest)}mcpGrant(){return s1(this.rawRequest)??null}cspNonce(){return M1(this.rawRequest)}reportProgress(Q){let Z=o1(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return f1(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=i1(this.rawRequest.headers.get("Content-Type"));if(n1(Q))return new u(await this.parseJsonBody());if(Q==="application/x-www-form-urlencoded"||Q==="multipart/form-data"){if(Q==="multipart/form-data"&&!N1(this.schema)){let K=c1(this.schema??{});if(K!==null)l1(this.rawRequest,K)}let Z;try{Z=await this.rawRequest.formData()}catch(K){if(K instanceof _)throw K;throw new _("The request body could not be read as a form.")}let J=new Map;for(let[K,$]of Z.entries())if(J.has(K)){let X=J.get(K);if(Array.isArray(X))X.push($);else J.set(K,[X,$])}else J.set(K,$);return new u(Object.fromEntries(J.entries()))}return new u({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch(J){if(J instanceof _)throw J;throw new _("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new _("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new _("The request body must be a JSON object.");return Z}validateInput(Q){if(N1(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},J={},K=Object.entries(this.schema).map(([$,X])=>({key:$,rules:Object.entries(X).map(([Y,H])=>({rule:Y,message:H,check:typeof H==="function"?null:this.ruleFor($,Y)}))}));for(let{key:$,rules:X}of K)for(let{path:Y,value:H}of f0(Z,$)){let G=this.checkField(H,X);if(G.length>0){let W=J[Q0(Y)]??=[];for(let V of G)if(!W.includes(V))W.push(V)}}if(this.addRefinements(J,Z),Object.keys(J).length>0)throw new o(J);return Q}checkField(Q,Z){let J=Z.some(({rule:X})=>X==="required"),K=Q===void 0||Q===null||Q==="",$=[];for(let{rule:X,message:Y,check:H}of Z){let G=Y,W=!1;if(typeof Y==="function")G=Y(Q),W=typeof G>"u";else W=H(Q);if(W)continue;if(K&&!J)continue;if(X==="required")return[String(G)];if(!$.includes(String(G)))$.push(String(G))}return $}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),J={};if("issues"in Z)for(let $ of Z.issues){let X=Q0($.path),Y=J[X]??=[];if(!Y.includes($.message))Y.push($.message)}let K="value"in Z?new u(Z.value):Q;if(this.addRefinements(J,K.toJSON()),Object.keys(J).length>0)throw new o(J);return K}addRefinements(Q,Z){for(let[J,K]of Object.entries(this.refine(Z)??{})){let $=Q[J]??[];Q[J]=$.includes(K)?$:[...$,K]}}ruleFor(Q,Z){try{return p1(Z)}catch(J){if(J instanceof q)throw new q(`${this.constructor.name}.schema.${Q}: ${J.message}`);throw J}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let Q=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(Q)}}catch(Z){if(!(Z instanceof o))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}var K0="x-gemi-sign-in";class g0 extends _{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:X1("authorization",this.error,401)}},view:{}}}}class I1 extends _{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:I1.apiStatus,data:{error:X1("permission",this.error,I1.apiStatus)}},view:{status:403}}}}class A1 extends _{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:$1("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":g1(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class h0 extends _{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:$1("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class E extends _{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:$1("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class m0 extends _{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:X1("authentication","Authentication error",401)},headers:{[K0]:Z}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Z}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Z}}}}}import{Buffer as c0}from"buffer";function Y1(Q){if(typeof Q!=="string"||/^[\s/.]*$/.test(Q))throw Error(`Refusing to delete by prefix ${JSON.stringify(Q)}: it would match the whole store`)}class a{async putStream({body:Q,...Z},J={}){J.signal?.throwIfAborted();let K=[],$=Q.getReader();try{for(;;){J.signal?.throwIfAborted();let{done:X,value:Y}=await $.read();if(X)break;K.push(Y)}}catch(X){throw await $.cancel(X).catch(()=>{}),X}return this.put({...Z,body:c0.concat(K)},J)}async*objects(Q,Z={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(Q,Z={}){Y1(Q);let J=[];for await(let K of this.objects(Q,Z))J.push(K.name);for(let K of J)Z.signal?.throwIfAborted(),await this.delete({name:K,bucket:Z.bucket});return J.length}async delete(Q){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,J=await this.fetch({name:Z.name,bucket:Z.bucket});if(!J.ok)throw new E(Z.name);let K=J.headers.get("Content-Type")??"application/octet-stream",$=J.headers.get("ETag")??void 0,X=J.headers.get("Last-Modified"),Y=X?new Date(X):void 0;if(Z.range){let W=await J.blob();return{body:W,start:0,end:W.size-1,total:W.size,partial:!1,type:K,etag:$,lastModified:Y,name:Z.name}}let H=Number(J.headers.get("Content-Length")),G=Number.isFinite(H)?H:0;return{body:J.body,start:0,end:G-1,total:G,partial:!1,type:K,etag:$,lastModified:Y,name:Z.name}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,J=typeof Q==="string"?void 0:Q.bucket,K=await this.fetch({name:Z,bucket:J});if(!K.ok)throw new E(Z);let $=Number(K.headers.get("Content-Length"));if(Number.isFinite($))return await K.body?.cancel(),$;return(await K.blob()).size}}function $0(Q,Z){if(!Z)return Q;let J=Q.getReader(),K=!1,$,X=()=>{if(K=!0,$)Z.removeEventListener("abort",$)};return new ReadableStream({start(Y){if($=()=>{if(K)return;X(),Y.error(Z.reason),J.cancel(Z.reason).catch(()=>{})},Z.aborted)$();else Z.addEventListener("abort",$,{once:!0})},async pull(Y){let H;try{H=await J.read()}catch(G){if(K)return;X(),Y.error(G);return}if(K)return;if(H.done){X(),Y.close();return}Y.enqueue(H.value)},cancel(Y){return X(),J.cancel(Y)}},{highWaterMark:0})}import{constants as W1}from"fs";import{lstat as w1,mkdir as X0,open as T1,readdir as F1,realpath as Y0,rename as p0,rmdir as u0,unlink as G0}from"fs/promises";import{dirname as d0,isAbsolute as W0,relative as G1,resolve as t,sep as x}from"path";class S1 extends a{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${O0()}/storage`}async realRoot(Q){let Z=t(this.folderPath);try{return await Y0(Z)}catch(J){if(J?.code!=="ENOENT")throw J;if(Q!=="write")return Z}try{await X0(Z,{recursive:!0})}catch(J){if(J?.code==="EEXIST"&&(await w1(Z)).isSymbolicLink())throw Error(`The storage folder "${Z}" is a symbolic link to a missing directory`);throw J}return Y0(Z)}async passesThroughLink(Q,Z){if(!Z)return!1;let J=Q;for(let K of Z.split(x)){J=`${J}${x}${K}`;try{if((await w1(J)).isSymbolicLink())return!0}catch($){if($?.code==="ENOENT"||$?.code==="ENOTDIR")return!1;throw $}}return!1}async resolveObjectPath(Q,Z){if(!Q)throw Error("Object name has to be specified");let J=t(this.folderPath),K=G1(J,t(J,Q)),$=Q.includes("\x00");if($||!K||K===".."||K.startsWith(`..${x}`)||W0(K)){if(Z==="read")throw new E(Q);if($)throw Error(`Refusing to ${Z} an object name containing a NUL byte`);throw Error(`Refusing to ${Z} "${Q}": it is outside the storage folder`)}let X=await this.realRoot(Z);if(await this.passesThroughLink(X,K)){if(Z==="read")throw new E(Q);throw Error(`Refusing to ${Z} "${Q}": it is or passes through a symbolic link`)}return`${X}${x}${K}`}async writeThroughTemporary(Q,Z,J){let K=null;try{Z?.throwIfAborted();let $=await this.resolveObjectPath(Q,"write");await X0(d0($),{recursive:!0}),K=`${$}.${Bun.randomUUIDv7()}.partial`;let X=await T1(K,"wx");try{await J(X)}finally{await X.close()}if(Z?.throwIfAborted(),await this.resolveObjectPath(Q,"write")!==$)throw Error(`Refusing to write "${Q}": the storage folder moved during the write`);await p0(K,$)}catch($){if(K)await G0(K).catch(()=>{});throw $}}async put(Q,{signal:Z}={}){Z?.throwIfAborted();let J,K;if(Q instanceof Blob)J=Q,K=`${Bun.randomUUIDv7()}.${Q.type.split("/")[1].split(";")[0]}`;else J=Q.body,K=Q.name;return await this.writeThroughTemporary(K,Z,async($)=>{let X=J instanceof Buffer?J:J instanceof Blob||J instanceof File?new Uint8Array(await J.arrayBuffer()):new Uint8Array;Z?.throwIfAborted(),await H0($,X)}),K}async putStream({name:Q,body:Z},{signal:J}={}){let K=Z.getReader();try{return await this.writeThroughTemporary(Q,J,async($)=>{for(;;){J?.throwIfAborted();let{done:X,value:Y}=await K.read();if(X)break;await H0($,Y)}}),Q}catch($){throw await K.cancel($).catch(()=>{}),$}}async openForRead(Q){let Z=await this.resolveObjectPath(Q,"read"),J;try{J=await T1(Z,W1.O_RDONLY|(W1.O_NOFOLLOW??0))}catch(K){if(["ELOOP","ENOENT","ENOTDIR","EISDIR"].includes(K?.code))throw new E(Q);throw K}try{let K=await J.stat();if(!K.isFile())throw new E(Q);return{handle:J,info:K,path:Z}}catch(K){throw await J.close().catch(()=>{}),K}}async fetch(Q,{signal:Z}={}){Z?.throwIfAborted();let J=typeof Q==="string"?Q:Q.name,{handle:K,info:$,path:X}=await this.openForRead(J);await K.close();let Y=$0(l0(J,X,$),Z),H=$.mtime.toUTCString();return new Response(Y,{headers:{"Content-Type":Bun.file(X).type,"Content-Length":String($.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":H}})}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,{name:J,range:K=null}=Z,{handle:$,info:X,path:Y}=await this.openForRead(J);await $.close();let H=Bun.file(Y),G=X.size,W=K?y1(K,G):null;if(K&&!W)throw new A1(G);let V=W?.start??0,O=W?W.end:G-1;return{body:W?H.slice(V,O+1):H,start:V,end:O,total:G,partial:Boolean(W),type:H.type||"application/octet-stream",lastModified:X.mtime,name:J}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,{handle:J,info:K}=await this.openForRead(Z);return await J.close(),K.size}async delete(Q){let Z=typeof Q==="string"?Q:Q.name,J=await this.resolveObjectPath(Z,"delete");try{await G0(J)}catch(K){if(K?.code==="ENOENT")return;throw K}}async resolvePrefix(Q){let Z=t(this.folderPath),J=Q.lastIndexOf("/"),K=J===-1?"":Q.slice(0,J),$=J===-1?Q:Q.slice(J+1),X=G1(Z,t(Z,K));if(X===".."||X.startsWith(`..${x}`)||W0(X))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let Y=await this.realRoot("read"),H=X?`${Y}${x}${X}`:Y,G=await this.passesThroughLink(Y,X),W=X.split(x).join("/");return{root:Y,dir:H,linked:G,match:W?`${W}/${$}`:$}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:J,dir:K,linked:$,match:X}=await this.resolvePrefix(Q);if($)return;let Y=[],H=async(G)=>{let W;try{W=await F1(G,{withFileTypes:!0})}catch(V){if(V?.code==="ENOENT"||V?.code==="ENOTDIR")return;throw V}for(let V of W){let O=`${G}${x}${V.name}`,z=G1(J,O).split(x).join("/");if(V.isDirectory()){if(`${z}/`.startsWith(X)||X.startsWith(`${z}/`))await H(O)}else if(V.isFile()&&z.startsWith(X))Y.push(z)}};await H(K),Y.sort();for(let G of Y){Z?.throwIfAborted();let W;try{W=await w1(`${J}/${G}`)}catch(V){if(V?.code==="ENOENT")continue;throw V}if(!W.isFile())continue;yield{name:G,size:W.size,lastModified:W.mtime}}}async deletePrefix(Q,Z={}){Y1(Q);let{root:J,linked:K,match:$}=await this.resolvePrefix(Q);if(Y1($),K)throw Error(`Refusing to delete by prefix "${Q}": it passes through a symbolic link`);let X=await super.deletePrefix(Q,Z);if(X>0)await this.pruneEmptyDirs(J,$);return X}async pruneEmptyDirs(Q,Z){let J=[],K=async($)=>{let X;try{X=await F1($,{withFileTypes:!0})}catch{return}for(let Y of X){if(!Y.isDirectory())continue;let H=`${$}${x}${Y.name}`,G=G1(Q,H).split(x).join("/");if(`${G}/`.startsWith(Z)||Z.startsWith(`${G}/`)){if(await K(H),`${G}/`.startsWith(Z))J.push(H)}}};await K(Q);for(let $ of J)try{await u0($)}catch{}}async list(){return await F1(this.folderPath)}}async function H0(Q,Z){for(let J=0;J<Z.byteLength;){let{bytesWritten:K}=await Q.write(Z,J);J+=K}}var V0=65536;function l0(Q,Z,J){let K=null,$=0,X=!1,Y=async()=>{if(X)return;X=!0,await K?.close().catch(()=>{})},H=async()=>{let G;try{G=await T1(Z,W1.O_RDONLY|(W1.O_NOFOLLOW??0))}catch(V){if(["ELOOP","ENOENT","ENOTDIR","EISDIR"].includes(V?.code))throw new E(Q);throw V}if(X)throw await G.close().catch(()=>{}),Error("The body was cancelled");K=G;let W=await G.stat();if(!W.isFile()||W.dev!==J.dev||W.ino!==J.ino)throw new E(Q);return G};return new ReadableStream({async pull(G){try{if(X)return;let W=K??await H(),V=new Uint8Array(V0),{bytesRead:O}=await W.read(V,0,V0,$);if(O===0){await Y(),G.close();return}$+=O,G.enqueue(V.subarray(0,O))}catch(W){await Y(),G.error(W)}},cancel:Y},{highWaterMark:0})}var y=30000;function cQ(Q){return Q}function j0(){return{driver:new S1,fetchTimeoutMs:y,fetchIdleTimeoutMs:y}}class k1{static token="filesystem";driver;fetchTimeoutMs;fetchIdleTimeoutMs;constructor(Q={}){this.driver=Q.driver??j0().driver,this.fetchTimeoutMs=Q.fetchTimeoutMs??y,this.fetchIdleTimeoutMs=Q.fetchIdleTimeoutMs??y}}class z0 extends Error{driver;limit;timeoutMs;object;code="storage-fetch-timeout";constructor(Q,Z,J,K){super(Z==="fetchTimeoutMs"?`${Q}: no response for "${K}" within ${J}ms (fetchTimeoutMs)`:`${Q}: the body of "${K}" sent nothing for ${J}ms (fetchIdleTimeoutMs)`);this.driver=Q;this.limit=Z;this.timeoutMs=J;this.object=K;this.name="StorageFetchTimeoutError"}}async function P0(Q,Z,J,K){let{fetchTimeoutMs:$,fetchIdleTimeoutMs:X}=K;if(J.signal||!$&&!X)return Q.fetch(Z,J);let Y=new AbortController,H=Q.constructor?.name||"FileStorageDriver",G=typeof Z==="string"?Z:Z.name,W=(z,P)=>{let M=new z0(H,z,P,G);return Y.abort(M),M},V=Promise.resolve(Q.fetch(Z,{...J,signal:Y.signal})),O;if($){let z,P=new Promise((M,U)=>{z=setTimeout(()=>U(W("fetchTimeoutMs",$)),$)});try{O=await Promise.race([V,P])}catch(M){if(Y.signal.aborted)throw V.then((U)=>U.body?.cancel(Y.signal.reason).catch(()=>{}),()=>{}),Y.signal.reason;throw M}finally{clearTimeout(z)}}else O=await V;if(!X||!O.body)return O;return new Response(i0(O.body,X,()=>W("fetchIdleTimeoutMs",X)),{status:O.status,statusText:O.statusText,headers:O.headers})}function i0(Q,Z,J){let K=Q.getReader();return new ReadableStream({async pull($){let X,Y,H=new Promise((G,W)=>{X=setTimeout(()=>{Y=J(),W(Y)},Z)});try{let G=await Promise.race([K.read(),H]);if(G.done)$.close();else $.enqueue(G.value)}catch(G){let W=Y??G;$.error(W),K.cancel(W).catch(()=>{})}finally{clearTimeout(X)}},cancel($){return K.cancel($)}},{highWaterMark:0})}class A extends Error{code="safe-fetch";url;constructor(Q,Z,J){super(Q,J);this.name=new.target.name,this.url=Z}}class g extends A{reason;code="invalid-url";constructor(Q,Z,J){super(J,Q);this.reason=Z}}class H1 extends A{host;reason;code="blocked-host";constructor(Q,Z,J){super(J==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,Q);this.host=Z;this.reason=J}}class d extends A{host;address;range;code="blocked-address";constructor(Q,Z,J,K){super(Z===J?`${J} is not a public address (${K}).`:`${Z} resolves to ${J}, which is not a public address (${K}).`,Q);this.host=Z;this.address=J;this.range=K}}class V1 extends A{host;code="dns";constructor(Q,Z,J){super(`Couldn't resolve ${Z}.`,Q,{cause:J});this.host=Z}}class O1 extends A{phase;ms;code="timeout";constructor(Q,Z,J){super(Z==="connect"?`Couldn't connect within ${J} ms.`:`The request didn't finish within ${J} ms.`,Q);this.phase=Z;this.ms=J}}class j1 extends A{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class r extends A{contentType;allowed;code="content-type";constructor(Q,Z,J){super(`The response is ${Z??"of no content type"}, not ${J.join(" or ")}.`,Q);this.contentType=Z;this.allowed=J}}class E1 extends A{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class l extends A{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class x1 extends A{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function n0(Q){if(Q==="")return null;let Z=Q.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let J=[];for(let X of Z){let Y=o0(X);if(Y===null)return null;J.push(Y)}let K=J.pop();for(let X of J)if(X>255)return null;if(K>=256**(4-J.length))return null;let $=K;return J.forEach((X,Y)=>{$+=X*256**(3-Y)}),new Uint8Array([Math.floor($/16777216)&255,Math.floor($/65536)&255,Math.floor($/256)&255,$&255])}function o0(Q){if(Q==="")return null;let Z=Q,J=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),J=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),J=8;if(!(J===16?/^[0-9a-f]+$/i:J===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let $=parseInt(Z,J);return Number.isSafeInteger($)?$:null}function D0(Q){let Z=Q;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let J=Z.indexOf("%");if(J!==-1)Z=Z.slice(0,J);if(!Z.includes(":"))return null;let K=Z.split("::");if(K.length>2)return null;let $=(W,V)=>{if(W==="")return[];let O=[],z=W.split(":");for(let P=0;P<z.length;P++){let M=z[P];if(V&&P===z.length-1&&M.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(M))return null;let U=M.split(".").map(Number);if(U.some((w)=>w>255))return null;O.push(U[0]<<8|U[1],U[2]<<8|U[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(M))return null;O.push(parseInt(M,16))}return O},X=$(K[0],K.length===1),Y=K.length===2?$(K[1],!0):[];if(!X||!Y)return null;let H;if(K.length===2){let W=8-X.length-Y.length;if(W<1)return null;H=[...X,...Array.from({length:W},()=>0),...Y]}else H=X;if(H.length!==8)return null;let G=new Uint8Array(16);return H.forEach((W,V)=>{G[V*2]=W>>8,G[V*2+1]=W&255}),G}function e(Q){let Z=D0(Q);if(Z)return{family:6,bytes:Z};let J=n0(Q);if(J)return{family:4,bytes:J};return null}function h(Q){if(Q.family===6&&s0(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function s0(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function Q1(Q){if(Q.family===4)return Array.from(Q.bytes).join(".");let Z=[];for(let J=0;J<16;J+=2)Z.push((Q.bytes[J]<<8|Q.bytes[J+1]).toString(16));return Z.join(":")}function i(Q){let Z=Q.lastIndexOf("/"),J=Z===-1?Q:Q.slice(0,Z),K=/^[0-9.]+$/.test(J)?a0(J):D0(J);if(!K)return null;let $=h(K.length===4?{family:4,bytes:K}:{family:6,bytes:K}),X=$.family===4?32:128,Y=X;if(Z!==-1){let H=Q.slice(Z+1);if(!/^\d{1,3}$/.test(H))return null;if(Y=Number(H),K.length===16&&$.family===4)Y-=96;if(Y<0||Y>X)return null}return{family:$.family,bytes:$.bytes,prefix:Y}}function a0(Q){return/^\d{1,3}(\.\d{1,3}){3}$/.test(Q)&&Q.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array(Q.split(".").map(Number)):null}function b(Q,Z){let J=h(Q);if(J.family!==Z.family)return!1;let K=Z.prefix;for(let $=0;K>0;$++){let X=Math.min(8,K),Y=255<<8-X&255;if((J.bytes[$]&Y)!==(Z.bytes[$]&Y))return!1;K-=X}return!0}var D=(Q,Z)=>({cidr:i(Q),kind:Z,text:Q}),t0=[D("0.0.0.0/8","unspecified"),D("10.0.0.0/8","private"),D("100.64.0.0/10","shared"),D("127.0.0.0/8","loopback"),D("169.254.169.254/32","metadata"),D("169.254.0.0/16","link-local"),D("168.63.129.16/32","metadata"),D("172.16.0.0/12","private"),D("192.0.0.0/24","reserved"),D("192.0.2.0/24","documentation"),D("192.88.99.0/24","reserved"),D("192.168.0.0/16","private"),D("198.18.0.0/15","benchmarking"),D("198.51.100.0/24","documentation"),D("203.0.113.0/24","documentation"),D("224.0.0.0/4","multicast"),D("255.255.255.255/32","broadcast"),D("240.0.0.0/4","reserved")],r0=[D("::/128","unspecified"),D("::1/128","loopback"),D("64:ff9b:1::/48","private"),D("::/8","reserved"),D("100::/64","reserved"),D("2001:db8::/32","documentation"),D("2001::/23","reserved"),D("3fff::/20","documentation"),D("fd00:ec2::254/128","metadata"),D("fc00::/7","unique-local"),D("fe80::/10","link-local"),D("fec0::/10","private"),D("ff00::/8","multicast")],e0=i("64:ff9b::/96"),Q4=i("2002::/16"),Z4=i("2000::/3");function z1(Q){let Z=typeof Q==="string"?e(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let J=h(Z);if(J.family===4){let $=t0.find((X)=>b(J,X.cidr));return $?{kind:$.kind,range:$.text}:null}if(b(J,e0))return z1({family:4,bytes:J.bytes.slice(12)});if(b(J,Q4))return z1({family:4,bytes:J.bytes.slice(2,6)});let K=r0.find(($)=>b(J,$.cidr));if(K)return{kind:K.kind,range:K.text};return b(J,Z4)?null:{kind:"reserved",range:"outside 2000::/3"}}function M0(Q,Z){let J=h(Q),K=h(Z);return J.family===K.family&&J.bytes.every(($,X)=>$===K.bytes[X])}import{lookup as J4}from"dns/promises";import*as K4 from"http";import*as $4 from"https";import*as n from"zlib";class q1 extends Response{#Q;#Z;address;constructor(Q,Z,J){super(Q,Z);this.#Q=J.url,this.#Z=J.redirected,this.address=J.address}get url(){return this.#Q}get redirected(){return this.#Z}}var Z1={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},X4=new Set([301,302,303,307,308]),Y4=new Set([101,103,204,205,304]),G4=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],W4=["authorization","cookie","proxy-authorization"];async function L0(Q,Z={}){let J=H4(Z),K=Z.signal;K?.throwIfAborted();let $=new AbortController,X=$.signal,Y=String(Q),H=(O)=>{if(!X.aborted)$.abort(O)},G=setTimeout(()=>H(new O1(Y,"total",J.timeout)),J.timeout),W=()=>H(K.reason);K?.addEventListener("abort",W,{once:!0});let V=()=>{clearTimeout(G),K?.removeEventListener("abort",W)};try{let O=B0(Y,J),z=(Z.method??"GET").toUpperCase(),P=new Headers(Z.headers);for(let U of G4)P.delete(U);if(!P.has("accept"))P.set("accept","*/*");if(!P.has("user-agent"))P.set("user-agent","gemi");if(!P.has("accept-encoding"))P.set("accept-encoding","gzip, deflate, br");let M=await z4(z,Z.body,P);for(let U=0;;U++){Y=O.href;let{request:w,response:C,address:S}=await P4(O,z,P,M,J,X),N=C.statusCode??0,I=C.headers.location;if(X4.has(N)&&I&&Z.redirect!=="manual"){if(w.destroy(),U>=J.maxRedirects)throw new E1(O.href,J.maxRedirects);let k;try{k=new URL(I,O)}catch{throw new g(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(N===303?z!=="HEAD":(N===301||N===302)&&z==="POST"){z="GET",M=null;let L=[];P.forEach((B,j)=>{if(j.startsWith("content-"))L.push(j)});for(let B of L)P.delete(B)}if(k.origin!==O.origin)for(let L of W4)P.delete(L);O=B0(k.href,J);continue}return D4({url:O,hop:U,method:z,request:w,response:C,address:S,policy:J,signal:X,release:V})}}catch(O){throw V(),X.aborted?X.reason:O}}function H4(Q){let Z=(K,$)=>{let X={hosts:[],ranges:[]};for(let Y of K){let H=Y.includes("/")||Y.includes(":")||/^[\d.]+$/.test(Y),G=H?i(Y):null;if(G)X.ranges.push(G);else if(!H&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(Y))X.hosts.push(C0(Y));else throw TypeError(`safeFetch: "${Y}" in ${$} is not a host name or an IP range.`)}return X},J=Q.allowPrivate;return{timeout:Q.timeout??Z1.timeout,connectTimeout:Q.connectTimeout??Z1.connectTimeout,maxSize:Q.maxSize??Z1.maxSize,maxRedirects:Q.maxRedirects??Z1.maxRedirects,ports:Q.ports??Z1.ports,allow:Q.allow&&Q.allow.length>0?Z(Q.allow,"allow"):null,deny:Z(Q.deny??[],"deny"),allowPrivate:J===!0?!0:Z(J||[],"allowPrivate").ranges,contentTypes:Q.contentTypes?.length?Q.contentTypes:null,resolve:Q.resolve??V4}}async function V4(Q){return(await J4(Q,{all:!0,verbatim:!0})).map((J)=>J.address)}function C0(Q){return Q.toLowerCase().replace(/\.$/,"")}function U0(Q,Z){return Z.some((J)=>J.startsWith("*.")?Q.endsWith(J.slice(1)):Q===J)}function B0(Q,Z){let J;try{J=new URL(Q)}catch{throw new g(Q,"malformed",`"${Q}" is not a URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new g(J.href,"scheme",`Only http and https URLs can be fetched, not ${J.protocol.slice(0,-1)}.`);if(J.username||J.password)throw new g(J.href,"credentials","The URL has a username or password in it.");let K=_0(J);if(Z.ports!=="any"&&!Z.ports.includes(K))throw new g(J.href,"port",`Port ${K} is not allowed.`);return J}function _0(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function O4(Q,Z,J){let K=C0(Q.hostname.replace(/^\[(.*)\]$/,"$1")),$=e(K),X=$!==null&&(K.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(K));if(!X&&U0(K,Z.deny.hosts))throw new H1(Q.href,K,"denied");let Y=!X&&Z.allow!==null&&U0(K,Z.allow.hosts);if(Z.allow&&!Y&&Z.allow.ranges.length===0)throw new H1(Q.href,K,"not-allowed");let H;if(X)H=[$];else{let G;try{G=await j4(Z.resolve(K),J)}catch(W){if(J.aborted)throw J.reason;throw new V1(Q.href,K,W)}if(H=G.map((W)=>e(W)).filter((W)=>W!==null),H.length===0)throw new V1(Q.href,K)}for(let G of H){let W=Q1(G);if(Z.deny.ranges.some((O)=>b(G,O)))throw new d(Q.href,K,W,"denied");if(Z.allow&&!Y&&!Z.allow.ranges.some((O)=>b(G,O)))throw new d(Q.href,K,W,"not-allowed");let V=z1(G);if(V&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((O)=>b(G,O)))throw new d(Q.href,K,W,V.kind)}return{host:K,addresses:H,isLiteral:X}}function j4(Q,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise((J,K)=>{let $=()=>K(Z.reason);Z.addEventListener("abort",$,{once:!0}),Q.then((X)=>{Z.removeEventListener("abort",$),J(X)},(X)=>{Z.removeEventListener("abort",$),K(X)})})}async function z4(Q,Z,J){if(Z===void 0||Z===null)return null;if(Q==="GET"||Q==="HEAD")throw TypeError(`safeFetch: a ${Q} request can't have a body.`);let K=new Request("http://body.invalid/",{method:"POST",body:Z}),$=K.headers.get("content-type");if($&&!J.has("content-type"))J.set("content-type",$);return new Uint8Array(await K.arrayBuffer())}async function P4(Q,Z,J,K,$,X){let Y=new AbortController,H=setTimeout(()=>Y.abort(new O1(Q.href,"connect",$.connectTimeout)),$.connectTimeout),G=AbortSignal.any([X,Y.signal]);try{let{host:W,addresses:V,isLiteral:O}=await O4(Q,$,G),z=Q.protocol==="https:",P={};if(J.forEach((M,U)=>{P[U]=M}),K)P["content-length"]=String(K.byteLength);return await new Promise((M,U)=>{let w={method:Z,host:W,port:_0(Q),path:`${Q.pathname}${Q.search}`,headers:P,agent:!1,lookup:(L,B,j)=>{let F=B?.family,R=V.filter((J1)=>!F||J1.family===F);if(R.length===0)j(Object.assign(Error(`No IPv${F} address for ${W}`),{code:"ENOTFOUND"}));else if(B?.all)j(null,R.map((J1)=>({address:Q1(J1),family:J1.family})));else j(null,Q1(R[0]),R[0].family)}};if(z&&!O)w.servername=W;let C=(z?$4:K4).request(w),S=null,N=(L)=>{G.removeEventListener("abort",I),C.destroy(),U(L)},I=()=>N(G.aborted?G.reason:X.reason);G.addEventListener("abort",I,{once:!0});let k=(L)=>{let B=L?.remoteAddress;if(!B||S!==null)return!0;let j=e(B);if(!j||!V.some((F)=>M0(F,j)))return N(new d(Q.href,W,B,"not-allowed")),!1;return S=Q1(h(j)),!0};C.once("socket",(L)=>{let B=()=>{if(k(L)&&!z)clearTimeout(H)};if(L.connecting)L.once("connect",B);else B();if(z)L.once("secureConnect",()=>clearTimeout(H))}),C.once("response",(L)=>{if(clearTimeout(H),L.on("error",()=>{}),!k(L.socket))return;G.removeEventListener("abort",I),M({request:C,response:L,address:S})}),C.on("error",(L)=>{if(G.aborted)return N(G.reason);N(L instanceof A?L:new l(Q.href,L))}),C.end(K??void 0)})}finally{clearTimeout(H)}}function D4({url:Q,hop:Z,method:J,request:K,response:$,address:X,policy:Y,signal:H,release:G}){let W=$.statusCode??0;if(W<200||W>599)throw K.destroy(),new l(Q.href,Error(`Unexpected status ${W}`));let V=new Headers,O=$.rawHeaders;for(let B=0;B<O.length;B+=2)V.append(O[B],O[B+1]);if(Y.contentTypes){let B=V.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!B||!Y.contentTypes.some((j)=>M4(B,j)))throw K.destroy(),new r(Q.href,B,Y.contentTypes)}let z={url:Q.href,redirected:Z>0,address:X},P={status:W,statusText:$.statusMessage??"",headers:V};if(J==="HEAD"||Y4.has(W))return K.destroy(),G(),new q1(null,P,z);let M=V.get("content-encoding")?.trim().toLowerCase(),U=M==="gzip"||M==="x-gzip"?n.createGunzip():M==="deflate"?n.createInflate():M==="br"?n.createBrotliDecompress():null,w=Number(V.get("content-length"));if(!U&&Number.isFinite(w)&&w>Y.maxSize)throw K.destroy(),new j1(Q.href,Y.maxSize);if(U)V.delete("content-encoding"),V.delete("content-length");let C=U?$.pipe(U):$,S=0,N=!1,I=()=>{},k=()=>{N=!0,H.removeEventListener("abort",I),G()},L=new ReadableStream({start(B){let j=(R)=>{if(N)return;if(k(),R===void 0)B.close();else K.destroy(),U?.destroy(),B.error(R)};if(I=()=>j(H.reason),H.addEventListener("abort",I,{once:!0}),H.aborted)return I();C.on("data",(R)=>{if(N)return;if(S+=R.byteLength,S>Y.maxSize)return j(new j1(Q.href,Y.maxSize));if(B.enqueue(new Uint8Array(R)),(B.desiredSize??1)<=0)C.pause()}),C.once("end",()=>j());let F=(R)=>j(R instanceof A?R:new l(Q.href,R));if(C.on("error",F),U)$.on("error",F);$.once("aborted",()=>j(new l(Q.href,Error("The response was cut off."))))},pull(){C.resume()},cancel(){if(N)return;k(),K.destroy(),U?.destroy()}});return new q1(L,P,z)}function M4(Q,Z){let J=Z.toLowerCase();return J.endsWith("/*")?Q.startsWith(J.slice(0,-1)):Q===J}function N0(Q){return L4(Q)??_4(Q)??R4(Q)}var b1=4096,U4={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/heic":"heic","image/heif":"heif","image/bmp":"bmp","image/tiff":"tiff","image/x-icon":"ico","image/svg+xml":"svg","audio/mpeg":"mp3","audio/aac":"aac","audio/mp4":"m4a","audio/ogg":"ogg","audio/flac":"flac","audio/wav":"wav","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm","video/x-matroska":"mkv","video/x-msvideo":"avi","font/woff":"woff","font/woff2":"woff2","font/ttf":"ttf","font/otf":"otf","application/pdf":"pdf","application/zip":"zip","application/gzip":"gz","application/xml":"xml","text/html":"html","text/plain":"txt","application/octet-stream":"bin"};function I0(Q){return U4[Q]??"bin"}function T(Q,Z,J=0){if(Q.length<J+Z.length)return!1;return Z.every((K,$)=>Q[J+$]===K)}function v(Q,Z,J){return String.fromCharCode(...Q.subarray(Z,J))}var B4={avif:"image/avif",avis:"image/avif",heic:"image/heic",heix:"image/heic",hevc:"image/heic",hevx:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif","qt ":"video/quicktime","M4A ":"audio/mp4","M4B ":"audio/mp4"};function L4(Q){if(T(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(T(Q,[255,216,255]))return"image/jpeg";if(Q.length>=6&&(v(Q,0,6)==="GIF87a"||v(Q,0,6)==="GIF89a"))return"image/gif";if(Q.length>=12&&v(Q,0,4)==="RIFF"){let Z=v(Q,8,12);if(Z==="WEBP")return"image/webp";if(Z==="WAVE")return"audio/wav";if(Z==="AVI ")return"video/x-msvideo"}if(Q.length>=12&&v(Q,4,8)==="ftyp"){let Z=v(Q,8,12);return B4[Z]??"video/mp4"}if(T(Q,[73,73,42,0])||T(Q,[77,77,0,42]))return"image/tiff";if(T(Q,[66,77])&&T(Q,[0,0,0,0],6))return"image/bmp";if(T(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(T(Q,[37,80,68,70,45]))return"application/pdf";if(T(Q,[80,75,3,4]))return"application/zip";if(T(Q,[31,139]))return"application/gzip";if(T(Q,[26,69,223,163]))return v(Q,0,Math.min(Q.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(Q.length>=4){let Z=v(Q,0,4);if(Z==="OggS")return"audio/ogg";if(Z==="fLaC")return"audio/flac";if(Z==="wOFF")return"font/woff";if(Z==="wOF2")return"font/woff2";if(Z==="OTTO")return"font/otf"}if(T(Q,[0,1,0,0,0]))return"font/ttf";if(Q.length>=3&&v(Q,0,3)==="ID3")return"audio/mpeg";if(Q.length>=2&&Q[0]===255){if((Q[1]&246)===240)return"audio/aac";if((Q[1]&224)===224&&(Q[1]&6)!==0)return"audio/mpeg"}return null}var C4=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function _4(Q){let Z=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(Z.charCodeAt(0)===65279)Z=Z.slice(1);if(Z=Z.trimStart(),!Z.startsWith("<"))return null;let J=Z.toLowerCase(),K=J;for(;;){K=K.trimStart();let $=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(K);if(!$)break;K=K.slice($[0].length)}if(/^<svg[\s>/]/.test(K))return"image/svg+xml";for(let $ of C4){if(!J.startsWith(`<${$}`))continue;if(/^[\s>]/.test(J.charAt($.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(K))return"text/html";if(J.startsWith("<?xml"))return"application/xml";return null}function R4(Q){if(Q.length===0)return"application/octet-stream";for(let Z of Q)if(Z<32&&Z!==9&&Z!==10&&Z!==12&&Z!==13&&Z!==27)return"application/octet-stream";try{return new TextDecoder("utf-8",{fatal:!0}).decode(Q,{stream:!0}),"text/plain"}catch{return"application/octet-stream"}}var N4=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function R0(Q){let Z=Q.split(";")[0].trim().toLowerCase();return N4.has(Z)||Z.endsWith("+xml")}function A0(Q,Z){let J=Q.split(";")[0].trim().toLowerCase();return Z.some((K)=>{let $=K.split(";")[0].trim().toLowerCase();if($==="*/*"||$==="*")return!R0(J);if($.endsWith("/*"))return J.startsWith($.slice(0,-1))&&!R0(J);return J===$})}import{Buffer as w4}from"buffer";async function w0(Q){try{return(await import("sharp")).default}catch(Z){throw Error(`${Q} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Z})}}async function F0(Q,Z,J={}){let{name:K,directory:$,bucket:X,maxSize:Y,timeout:H,contentTypes:G,signal:W}=J;if(K!==void 0&&$!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(K!==void 0&&!K)throw TypeError("Storage.putFromUrl(): `name` is empty.");let V=await L0(Z,{...J.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:W,timeout:H,maxSize:Y});if(!V.ok)throw await V.body?.cancel().catch(()=>{}),new x1(V.url,V.status);let O=(V.body??new Response(new Uint8Array).body).getReader(),z=async(j)=>{throw await O.cancel(j).catch(()=>{}),j},P=[],M=0,U=!1;while(M<b1){let{done:j,value:F}=await O.read();if(j){U=!0;break}P.push(F),M+=F.byteLength}let w=A4(P,M),C=N0(w.subarray(0,Math.min(M,b1))),S=G?.length?G:["*/*"];if(!A0(C,S))await z(new r(V.url,C,S));let N=K??[($??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${I0(C)}`].filter(Boolean).join("/"),I=M,k=new ReadableStream({start(j){if(M>0)j.enqueue(w);if(U)j.close()},async pull(j){let{done:F,value:R}=await O.read();if(F){j.close();return}I+=R.byteLength,j.enqueue(R)},cancel(j){return O.cancel(j)}}),L={name:N,bucket:X,body:k,contentType:C},B;try{B=Q.putStream?await Q.putStream(L,{signal:W}):await a.prototype.putStream.call(Q,L,{signal:W})}catch(j){throw await z(j),j}return{name:B,contentType:C,size:I,url:V.url}}function A4(Q,Z){if(Q.length===1)return Q[0];let J=new Uint8Array(Z),K=0;for(let $ of Q)J.set($,K),K+=$.byteLength;return J}class F4 extends T0{static getFacadeAccessor(){return k1}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return F0(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=w4.from(await Q.arrayBuffer()),J=await w0("Storage.metadata()");try{return await J(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){Z.signal?.throwIfAborted();let J=this.getFacadeRoot();return P0(J.driver,Q,Z,{fetchTimeoutMs:J.fetchTimeoutMs??y,fetchIdleTimeoutMs:J.fetchIdleTimeoutMs??y})}static async read(Q,Z={}){let J=typeof Q==="string"?{name:Q}:{...Q},K="range"in Z?Z.range??null:J.range!==void 0?J.range:f.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...J,range:K})}static list(Q){return this.getFacadeRoot().driver.list(Q)}static objects(Q,Z={}){return this.getFacadeRoot().driver.objects(Q,Z)}static async deletePrefix(Q,Z={}){return this.getFacadeRoot().driver.deletePrefix(Q,Z)}static async delete(Q){return this.getFacadeRoot().driver.delete(Q)}}class T4{config;static token="redis";instance=null;connectingSince=null;downSince=null;replaceDelay=500;constructor(Q={}){this.config=Q}get client(){if(this.instance===null)return this.build();let Q=this.instance;if(this.isDown(Q,Date.now())){this.instance=null;try{Q.close()}catch{}return this.build()}return Q}set client(Q){this.instance=Q,this.connectingSince=null,this.downSince=null,this.replaceDelay=500}close(){let Q=this.instance;this.instance=null,this.connectingSince=null,this.downSince=null,this.replaceDelay=500,Q?.close()}build(){let Q=new(S4())(this.config.url,this.config.options);if(this.instance=Q,this.downSince=null,this.connectingSince=null,typeof Q.connect==="function"){this.connectingSince=Date.now();let Z;try{Z=Promise.resolve(Q.connect())}catch(J){Z=Promise.reject(J)}Z.then(()=>{if(this.instance!==Q)return;this.connectingSince=null,this.replaceDelay=500},()=>{if(this.instance!==Q)return;this.connectingSince=null})}return Q}isDown(Q,Z){if(Q.connected!==!1||typeof Q.connect!=="function")return this.downSince=null,!1;if(this.connectingSince!==null){let J=(this.config.options?.connectionTimeout??1e4)+5000;if(Z-this.connectingSince<J)return!1;this.connectingSince=null}if(this.downSince??=Z,Z-this.downSince<this.replaceDelay)return!1;return this.replaceDelay=Math.min(this.replaceDelay*2,1e4),!0}}function S4(){let Q=globalThis.Bun?.RedisClient;if(typeof Q!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return Q}
3
+ export{v1 as Ki,S0 as Li,E4 as Mi,i1 as Ni,e4 as Oi,s1 as Pi,QQ as Qi,f1 as Ri,y1 as Si,q4 as Ti,b4 as Ui,v4 as Vi,g1 as Wi,M1 as Xi,h4 as Yi,m4 as Zi,JQ as _i,r1 as $i,KQ as aj,$Q as bj,o as cj,q as dj,L1 as ej,i4 as fj,n4 as gj,o4 as hj,s4 as ij,a4 as jj,y0 as kj,K0 as lj,g0 as mj,I1 as nj,A1 as oj,h0 as pj,E as qj,m0 as rj,w0 as sj,Y1 as tj,a as uj,$0 as vj,S1 as wj,cQ as xj,j0 as yj,k1 as zj,z0 as Aj,A as Bj,g as Cj,H1 as Dj,d as Ej,V1 as Fj,O1 as Gj,j1 as Hj,r as Ij,E1 as Jj,l as Kj,x1 as Lj,e as Mj,z1 as Nj,q1 as Oj,L0 as Pj,N0 as Qj,R0 as Rj,F4 as Sj,T4 as Tj};
4
+
5
+ //# debugId=B724C6970AE52CB364756E2164756E21