gemi 0.233.0 → 0.233.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/AuthController.d.ts.map +1 -1
- package/dist/auth/UserProvider.d.ts +19 -0
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/{chunk-5038v4f1.js → chunk-1eha67ey.js} +1 -1
- package/dist/{chunk-jnf0jhdz.js → chunk-6j439skq.js} +1 -1
- package/dist/chunk-hd9yny4q.js +88 -0
- package/dist/{chunk-vsh9jck0.js.map → chunk-hd9yny4q.js.map} +4 -4
- package/dist/{chunk-5b9fzma1.js → chunk-rgcdf5pb.js} +2 -2
- package/dist/{chunk-5b9fzma1.js.map → chunk-rgcdf5pb.js.map} +1 -1
- package/dist/{chunk-azj481bb.js → chunk-vsr08sbe.js} +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-vsh9jck0.js +0 -88
- /package/dist/{chunk-5038v4f1.js.map → chunk-1eha67ey.js.map} +0 -0
- /package/dist/{chunk-jnf0jhdz.js.map → chunk-6j439skq.js.map} +0 -0
- /package/dist/{chunk-azj481bb.js.map → chunk-vsr08sbe.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthController.d.ts","sourceRoot":"","sources":["../../auth/AuthController.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAgBlD,OAAO,KAAK,EAAc,IAAI,EAAE,MAAM,SAAS,CAAC;AAgGhD;;;;;GAKG;AACH,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,yFAAyF;AACzF,wBAAgB,QAAQ,CAAC,KAAK,EAAE,O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CAAC,CAAC;QAC3B,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,2CAA2C;QAC3C,KAAK,EAAE,MAAM,CAAC;QACd,mFAAmF;QACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;QACf;;;;WAIG;QACH,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB;;;WAGG;QACH,UAAU,CAAC,EAAE,OAAO,CAAC;KACtB,GAAG,OAAO,CACT;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,QAAQ,GAAG,QAAQ,CAAA;KAAE,GAAG,gBAAgB,GAAG,iBAAiB,GAAG,IAAI,CAC1F;IAsGK,oBAAoB,CAAC,GAAG;eAA4B,MAAM;6BAAK;;;IA2BrE;;;;;;;OAOG;IACG,gBAAgB,CAAC,GAAG;eAA4B,MAAM;6BAAK;;;IAqBjE;;;;;;;;;OASG;IACG,eAAe,CACnB,GAAG;eAA4B,MAAM;cAAQ,MAAM;eAAS,MAAM;6BAAK;;;;CAoH1E"}
|
|
@@ -113,8 +113,27 @@ export declare class UserProvider<TSession = SessionWithUser> {
|
|
|
113
113
|
* hoisting it here would silently suspend policies for `config.onUserCreated`
|
|
114
114
|
* too, and an application's provisioning writes should run under the same
|
|
115
115
|
* policy resolution as the rest of its code.
|
|
116
|
+
*
|
|
117
|
+
* On SQLite, transactions opened here queue in the process, one after
|
|
118
|
+
* another per connection, with the legacy-session ones
|
|
119
|
+
* (`withLegacySessionLock`): Bun's client runs every statement on one
|
|
120
|
+
* connection, where a second `BEGIN` while a transaction is open fails
|
|
121
|
+
* outright. Two sign-ups at once answered 500 there (#1356). Inside a
|
|
122
|
+
* transaction already, this is a savepoint and does not queue.
|
|
116
123
|
*/
|
|
117
124
|
transaction<T>(fn: () => Promise<T>): Promise<T>;
|
|
125
|
+
/**
|
|
126
|
+
* `begin` now, or, on SQLite outside a transaction, after the transactions
|
|
127
|
+
* this provider queued on the connection before it.
|
|
128
|
+
*
|
|
129
|
+
* The next one may begin at COMMIT, not when `begin` resolves: the first
|
|
130
|
+
* after-commit callback lets it go. `begin` resolves only after every
|
|
131
|
+
* callback deferred until the commit has run (a sync event listener, say),
|
|
132
|
+
* and one of those that opened a transaction here would otherwise wait on
|
|
133
|
+
* the very transaction that waits on it, and every sign-in on the process
|
|
134
|
+
* behind both. A rollback runs no callbacks; settling lets it go then.
|
|
135
|
+
*/
|
|
136
|
+
private queuedOnSqlite;
|
|
118
137
|
/**
|
|
119
138
|
* Runs `fn` in a transaction that no other conversion or revocation of the
|
|
120
139
|
* pre-0.64 token `token` can overlap. `AuthManager` converts a legacy
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserProvider.d.ts","sourceRoot":"","sources":["../../auth/UserProvider.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,wBAAwB,EACxB,iBAAiB,EACjB,4BAA4B,EAC5B,iBAAiB,EACjB,uBAAuB,EACvB,cAAc,EACd,4BAA4B,EAC5B,iBAAiB,EACjB,0BAA0B,EAC1B,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,EACjB,sBAAsB,EACtB,IAAI,EACL,MAAM,SAAS,CAAC;AAsJjB;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;CAQhB,CAAC;AAEZ;;;;;GAKG;AACH,MAAM,MAAM,aAAa,GAAG;IAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC;AAElE;;;;;;;;;GASG;AACH,qBAAa,YAAY,CAAC,QAAQ,GAAG,eAAe;IAMtC,SAAS,CAAC,MAAM,EAAE,UAAU;IALxC;;;;OA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AAC;IAMlF;;;;OAIG;IACG,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAOjD,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMlD,mBAAmB,CAAC,IAAI,EAAE,uBAAuB,GAAG,OAAO,CAAC,GAAG,CAAC;IAMtE;;;;;;;;;;;OAWG;IACG,uBAAuB,CAC3B,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAWjB,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,aAAa,EAAE,CAAC;IAS3B;;;;;;;OAOG;IACG,kBAAkB,CACtB,OAAO,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,GAAG,YAAY,CAAC,EACjD,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,OAAO,CAAC;CASpB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Cc as P3,Pc as _3,ic as y3,mc as U2,nc as f3,oc as B3,od as L3,wc as I3}from"./chunk-607nk925.js";import{Ad as l}from"./chunk-x6fa13e1.js";import{je as l2,le as P2,oe as n3,pe as t3,qe as P$,se as S$}from"./chunk-kpmp5hmc.js";import{Ae as d3,Ce as c3,Me as C,Ne as p3,Oe as i3,Qe as l3,Re as A$,ve as u3,ye as $3}from"./chunk-c71dr883.js";import{Ue as B}from"./chunk-7g3r55sj.js";import{$g as z$,Ef as _$,Ff as n2,Fh as T$,Hg as Z3,Jf as B2,Kf as Q2,Sg as r2,Ug as s,Yg as $$,Zg as e2,_g as Z$,ag as c2,dh as g2,ef as t,eh as f2,ff as Q$,gf as m2,ih as w2,jh as G$,kf as b3,kh as Y2,lg as F2,lh as W$,mg as d2,mh as X$,ng as k,nh as v2,of as M$,oh as Z2,qg as J$,rf as N$,rg as H$,rh as E$,sg as U$,sh as o,th as i2,uf as B$,ug as g,yh as V$,zh as F$}from"./chunk-vsh9jck0.js";import{Ri as u,ej as a2,uj as N3,yj as X2}from"./chunk-vjqpcet2.js";import{Aj as o3}from"./chunk-jqqyj6cr.js";import{Gj as i,Kj as q$,Lj as _2,Mj as $2}from"./chunk-30zs008n.js";import{Uj as m}from"./chunk-m4wagwhr.js";import{_j as p2}from"./chunk-6xt7w9bb.js";import{bk as L$,ck as t2,fk as I2,gk as o2,jk as D$}from"./chunk-c5kd7eac.js";import{Ck as r3,xk as a3}from"./chunk-9bjggtdt.js";import{Sk as m3,Uk as d,el as W2}from"./chunk-0zakpsep.js";import{gl as q}from"./chunk-djhr379j.js";import{ml as C$}from"./chunk-qgka1mvf.js";import{fm as s2}from"./chunk-qqe19gtm.js";import{mm as N2,pm as E}from"./chunk-6fpjc2eg.js";import{ym as u2}from"./chunk-0dp6jvrg.js";import{Om as e3}from"./chunk-kfcz4qa8.js";var b$="mcp",y$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends l{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var z3=/^[A-Za-z0-9_-]{1,64}$/,f$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,G3=4000,R=1e5,w$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,O3=new WeakMap;function B9($){return O3.get($)}class n{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=u$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,v$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Q3(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(Q3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let H=Q.value,U={caller:$,req:$.req,tool:K,input:H,ctx:G},V=await this.fillPath(Y,U),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${V}.`,404);let P={};for(let A of Y.jsonKeys)if(H[A]!==void 0)P[A]=H[A];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,U);else if(K.method==="GET")J=a$(P);else if(Y.jsonKeys.length>0)I=P;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(U)):void 0,D={...j?{credentials:j}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let A=J?`${V}?${J}`:V;T=Object.keys(D).length>0?await this.dispatcher.dispatchAs($.req,K.method,A,I,D):await this.dispatcher.dispatchAs($.req,K.method,A,I)}catch(A){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,A),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await F3(Z,T);return await this.project(Y,U,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(f$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(U3(S))l$(z,`params.${N}`,S);else H3(z,`params.${N}`,S)}let H=[],U;if(X.input){if(U=X.input.toJSONSchema(),U.type!=="object"||!U.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(U.properties)}let V=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of V)H3(z,`files.${N.name}`,N.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=V3(z,G,X.annotations);if(V.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,j=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=i.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(U3(S)){let w=S.as??N.name;I(w,S.input),j.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let D={};for(let N of V)if(N.binder==="input")I(N.name,i.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),D[N.name]=this.remoteFileSchema();let T=[...Object.keys(P),...V.map((N)=>N.name)];for(let N of new Set(T))if(H.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let A=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:J3(X.input,U,i.object(P)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),x=!V.every((N)=>N.binder==="input")?null:V.length===0?A:Object.freeze({...A,inputSchema:J3(X.input,U,i.object(s$(P,Object.keys(D))),D)});return{kind:"route",descriptor:A,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let H of Object.keys(Y))if(!W.includes(H))K.push(`a file has no field "${H}"`);for(let H of W){let U=Y[H];if(U===void 0||U===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof U!=="string")K.push(`a file's "${H}" must be a string`);else Q[H]=U}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!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((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:V3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!K2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let H=G.signal??new AbortController().signal;return K3(X,Y.value,Y3(X3(X,Q,H,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(O2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return O3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(x,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(x,N):h$(x,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await W3(this.runNative($,{...K,ctx:G},G),Q)}let H=$.meta.remote,U=await this.bind($,"the remote context",()=>H.context(K));if(typeof U!=="object"||U===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,U),new O(`"${X}" failed on the server.`,500);let V=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...V!==void 0?[AbortSignal.timeout(V)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=X3($,U,P,I);if(!W.approved&&K2($)&&await K3($,K.input,Y3(J)))throw new h(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await W3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(x){if(P.aborted&&x===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${V} ms.`,504)}if(x instanceof O)throw x;if(x instanceof l||x instanceof h)throw new O(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new O(`"${X}" failed on the server.`,500)}let D=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new O(`"${X}" failed on the server.`,500)};if(I3(j))throw D("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(x){throw D(`could not read an image it showed: ${x}`)}let A=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(A);if(x.ok===!1)throw D(`answered what its output schema refuses: ${x.errors.join(", ")}`);A=x.value}for(let x of T)W.images?.(x);if(A===void 0)return null;if(typeof A==="string")return A.length>R?`${A.slice(0,R)}\u2026 [cut at ${R} of ${A.length} characters]`:A;let z2=JSON.stringify(A);if(z2!==void 0&&z2.length>R)return`${z2.slice(0,R)}\u2026 [cut at ${R} of ${z2.length} characters]`;return A}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let H=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${H}`,"");continue}W=W.replace(H,o$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,H]of Object.entries(Z))D2(K,Q,H);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))D2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(U)=>new O(`"${Z}" of "${$}" ${U}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!d$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!c$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let U=W.data.replace(/\s+/g,"");if(Math.floor(U.length*3/4)-i$(U)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(U.length%4!==0||!p$.test(U))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(U,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(H.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let U=await N3(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!U.ok)throw G(`could not be fetched: ${H.host} answered ${U.status}.`);let V=await U.arrayBuffer();return new File([V],W.name,{type:W.mimeType})}catch(U){if(U instanceof O)throw U;throw G(`could not be fetched from ${H.host}: ${U instanceof Error?U.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(b$,{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(!y$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await F3(G,z);let X=(V,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${V}`);else console.error(`[gemi/mcp] "${G}" ${V}`,F);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=Q;if($.result)try{H=await $.result(Q,Z)}catch(V){throw X("failed in its result projection:",V)}if(W){let V=W.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let U=JSON.stringify(H);if(U!==void 0&&U.length>R)return`${U.slice(0,R)}\u2026 [cut at ${R} of ${U.length} characters]`;return H}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof l)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function v$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function g$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function W3($,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(!g$($))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 h$($,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 X3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(U)=>async()=>{throw new l(`"${W}" was called by a remote MCP client, which has no ${U}.`,{retryable:!1})},H={put:async(U,V={})=>{if(!V.showModel)return K("attachment store")();let F=V.mimeType||U.type;if(!/^image\//i.test(F))throw new l(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=U.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:V.name??(U instanceof File?U.name:"image"),mimeType:F,size:U.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:H,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(U)=>L3({...U,signal:U.signal?AbortSignal.any([z,U.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:P3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:_3(),meter:B3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function Y3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function K3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function O2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Q3($,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 m$=10485760;function u$($){let Z=$?.maxBytes??m$;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 d$($){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 c$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,p$=/^[A-Za-z0-9+/]*={0,2}$/;function i$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function H3($,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 l$($,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 n$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function t$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function V3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?t$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!n$.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 J3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,H])=>[Q,H.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let H=[],U={};if($){let F=$.safeParse(Q);if(F.ok===!1)H.push(...F.errors);else U={...F.value}}let V=z.safeParse(Q);if(V.ok===!1)H.push(...V.errors);else U={...U,...V.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){H.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)H.push(...J.errors.map((j)=>`${F}: ${j}`));else U[F]=J.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:U}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let H=K(Q);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function s$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function o$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function D2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)D2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function a$($){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 F3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!w$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>R)return`${W.slice(0,R)}\u2026 [cut at ${R} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>G3?`${z.slice(0,G3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as r$,randomBytes as e$,timingSafeEqual as $8}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class Z8{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`${$}${e$(32).toString("base64url")}`}static hash($){return r$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&$8(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as w3,randomBytes as x3}from"crypto";async function A2($,Z){let z=z8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function z8(){try{let $=E();return $.bound(t)?$.make(t):null}catch{return null}}var x2=["2026-07-28"],H2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...H2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as G8,timingSafeEqual as W8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!W8(K,Q))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=G)return null;return H}function A3($,Z,z){return G8("sha256",U2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",C3="gemi.mcp.session.v1",X8=86400000,S3=600000,q3="gemi_approval",b2=2000,Y8={limit:600,window:60},K8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=U8(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,U2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??Y8,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??S3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?H8(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 T3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return T3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await Q8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new u($,{},"api",this.endpoint.pathname);return await m.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),k3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let H=this.session($,z),U=$.headers.get("mcp-protocol-version");if(U!==null&&U!==H.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${U} is not the session's ${H.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${H.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(V,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:I,signal:J}),k3(K)||J8(this.registry,Y,H.state),P,()=>this.inflight.delete(V))}catch(I){throw this.inflight.delete(V),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=H2.includes(G)?G:H2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:M3(X.elicitation),p:V2(z),exp:Date.now()+X8},K=k2(C3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(C3,"gms1",z);if(!G||G.p!==V2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||j3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,j)=>{G.outcome="denied",G.reason=J,G.message=j},K=(J,j,D)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(D!==void 0)G.error=D},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let D=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(D),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let D=await this.approval($,Q,z,Y,G);if(D.kind==="answer")return D.result;G.approved=!0}}let H=F8($),U=[],V;try{V=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>U.push(J),...H?{progress:H}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof h){let D=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,D),new _(L.InvalidParams,D)}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 F=typeof V==="string"?V:JSON.stringify(V??null),P=Q.outputSchema&&($.era.modern||M(V))?{structuredContent:V}:{},I=[...U.length>0&&V===null?[]:[{type:"text",text:F}],...U];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=N8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=V8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==V2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return R3(I[q3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!M3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let D={p:V2($.principal),t:Z.name,a:j,n:x3(16).toString("base64url"),exp:Date.now()+S3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[q3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",D),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let H=`gemi-approval-${x3(12).toString("base64url")}`,U=Q.sessionId,V=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(H),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(H,{session:U,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(H),I(null)}),$.stream.send({jsonrpc:"2.0",id:H,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return V&&!V.error&&R3(V.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new v3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=b3(new u($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,K8);return z===null?null:E3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:E3(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{Cc as P3,Pc as _3,ic as y3,mc as U2,nc as f3,oc as B3,od as L3,wc as I3}from"./chunk-607nk925.js";import{Ad as l}from"./chunk-x6fa13e1.js";import{je as l2,le as P2,oe as n3,pe as t3,qe as P$,se as S$}from"./chunk-kpmp5hmc.js";import{Ae as d3,Ce as c3,Me as C,Ne as p3,Oe as i3,Qe as l3,Re as A$,ve as u3,ye as $3}from"./chunk-c71dr883.js";import{Ue as B}from"./chunk-7g3r55sj.js";import{$g as z$,Ef as _$,Ff as n2,Fh as T$,Hg as Z3,Jf as B2,Kf as Q2,Sg as r2,Ug as s,Yg as $$,Zg as e2,_g as Z$,ag as c2,dh as g2,ef as t,eh as f2,ff as Q$,gf as m2,ih as w2,jh as G$,kf as b3,kh as Y2,lg as F2,lh as W$,mg as d2,mh as X$,ng as k,nh as v2,of as M$,oh as Z2,qg as J$,rf as N$,rg as H$,rh as E$,sg as U$,sh as o,th as i2,uf as B$,ug as g,yh as V$,zh as F$}from"./chunk-hd9yny4q.js";import{Ri as u,ej as a2,uj as N3,yj as X2}from"./chunk-vjqpcet2.js";import{Aj as o3}from"./chunk-jqqyj6cr.js";import{Gj as i,Kj as q$,Lj as _2,Mj as $2}from"./chunk-30zs008n.js";import{Uj as m}from"./chunk-m4wagwhr.js";import{_j as p2}from"./chunk-6xt7w9bb.js";import{bk as L$,ck as t2,fk as I2,gk as o2,jk as D$}from"./chunk-c5kd7eac.js";import{Ck as r3,xk as a3}from"./chunk-9bjggtdt.js";import{Sk as m3,Uk as d,el as W2}from"./chunk-0zakpsep.js";import{gl as q}from"./chunk-djhr379j.js";import{ml as C$}from"./chunk-qgka1mvf.js";import{fm as s2}from"./chunk-qqe19gtm.js";import{mm as N2,pm as E}from"./chunk-6fpjc2eg.js";import{ym as u2}from"./chunk-0dp6jvrg.js";import{Om as e3}from"./chunk-kfcz4qa8.js";var b$="mcp",y$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends l{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class h extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var z3=/^[A-Za-z0-9_-]{1,64}$/,f$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,G3=4000,R=1e5,w$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,O3=new WeakMap;function B9($){return O3.get($)}class n{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=u$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,v$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Q3(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(Q3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new h(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new h(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new h(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let H=Q.value,U={caller:$,req:$.req,tool:K,input:H,ctx:G},V=await this.fillPath(Y,U),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${V}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${V}.`,404);let P={};for(let A of Y.jsonKeys)if(H[A]!==void 0)P[A]=H[A];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,U);else if(K.method==="GET")J=a$(P);else if(Y.jsonKeys.length>0)I=P;let j=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(U)):void 0,D={...j?{credentials:j}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let A=J?`${V}?${J}`:V;T=Object.keys(D).length>0?await this.dispatcher.dispatchAs($.req,K.method,A,I,D):await this.dispatcher.dispatchAs($.req,K.method,A,I)}catch(A){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,A),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await F3(Z,T);return await this.project(Y,U,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(f$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(U3(S))l$(z,`params.${N}`,S);else H3(z,`params.${N}`,S)}let H=[],U;if(X.input){if(U=X.input.toJSONSchema(),U.type!=="object"||!U.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);H=Object.keys(U.properties)}let V=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of V)H3(z,`files.${N.name}`,N.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=V3(z,G,X.annotations);if(V.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,j=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=i.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(U3(S)){let w=S.as??N.name;I(w,S.input),j.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let D={};for(let N of V)if(N.binder==="input")I(N.name,i.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),D[N.name]=this.remoteFileSchema();let T=[...Object.keys(P),...V.map((N)=>N.name)];for(let N of new Set(T))if(H.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let A=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:J3(X.input,U,i.object(P)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),x=!V.every((N)=>N.binder==="input")?null:V.length===0?A:Object.freeze({...A,inputSchema:J3(X.input,U,i.object(s$(P,Object.keys(D))),D)});return{kind:"route",descriptor:A,remote:x,params:K,paramBinders:J,modelParams:j,fileFields:V,jsonKeys:H,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let H of Object.keys(Y))if(!W.includes(H))K.push(`a file has no field "${H}"`);for(let H of W){let U=Y[H];if(U===void 0||U===null){if(H==="name"||H==="mimeType")K.push(`a file needs "${H}"`);continue}if(typeof U!=="string")K.push(`a file's "${H}" must be a string`);else Q[H]=U}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!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((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:V3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!K2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let H=G.signal??new AbortController().signal;return K3(X,Y.value,Y3(X3(X,Q,H,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(O2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return O3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(x,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(x,N):h$(x,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await W3(this.runNative($,{...K,ctx:G},G),Q)}let H=$.meta.remote,U=await this.bind($,"the remote context",()=>H.context(K));if(typeof U!=="object"||U===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,U),new O(`"${X}" failed on the server.`,500);let V=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...V!==void 0?[AbortSignal.timeout(V)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=X3($,U,P,I);if(!W.approved&&K2($)&&await K3($,K.input,Y3(J)))throw new h(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let j;try{j=await W3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(x){if(P.aborted&&x===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${V} ms.`,504)}if(x instanceof O)throw x;if(x instanceof l||x instanceof h)throw new O(x.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,x),new O(`"${X}" failed on the server.`,500)}let D=(x)=>{return console.error(`[gemi/mcp] "${X}" ${x}`),new O(`"${X}" failed on the server.`,500)};if(I3(j))throw D("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(x){throw D(`could not read an image it showed: ${x}`)}let A=j;if($.descriptor.outputSchema){let x=$.descriptor.outputSchema.safeParse(A);if(x.ok===!1)throw D(`answered what its output schema refuses: ${x.errors.join(", ")}`);A=x.value}for(let x of T)W.images?.(x);if(A===void 0)return null;if(typeof A==="string")return A.length>R?`${A.slice(0,R)}\u2026 [cut at ${R} of ${A.length} characters]`:A;let z2=JSON.stringify(A);if(z2!==void 0&&z2.length>R)return`${z2.slice(0,R)}\u2026 [cut at ${R} of ${z2.length} characters]`;return A}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let H=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${H}`,"");continue}W=W.replace(H,o$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,H]of Object.entries(Z))D2(K,Q,H);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))D2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(U)=>new O(`"${Z}" of "${$}" ${U}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!d$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!c$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let U=W.data.replace(/\s+/g,"");if(Math.floor(U.length*3/4)-i$(U)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(U.length%4!==0||!p$.test(U))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(U,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let H;try{H=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(H.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let U=await N3(H.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!U.ok)throw G(`could not be fetched: ${H.host} answered ${U.status}.`);let V=await U.arrayBuffer();return new File([V],W.name,{type:W.mimeType})}catch(U){if(U instanceof O)throw U;throw G(`could not be fetched from ${H.host}: ${U instanceof Error?U.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(b$,{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(!y$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await F3(G,z);let X=(V,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${V}`);else console.error(`[gemi/mcp] "${G}" ${V}`,F);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let H=Q;if($.result)try{H=await $.result(Q,Z)}catch(V){throw X("failed in its result projection:",V)}if(W){let V=W.safeParse(H);if(V.ok===!1)throw X(`answered what its output schema refuses: ${V.errors.join(", ")}`);H=V.value}if(H===void 0)return null;let U=JSON.stringify(H);if(U!==void 0&&U.length>R)return`${U.slice(0,R)}\u2026 [cut at ${R} of ${U.length} characters]`;return H}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof l)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function v$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function g$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function W3($,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(!g$($))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 h$($,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 X3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(U)=>async()=>{throw new l(`"${W}" was called by a remote MCP client, which has no ${U}.`,{retryable:!1})},H={put:async(U,V={})=>{if(!V.showModel)return K("attachment store")();let F=V.mimeType||U.type;if(!/^image\//i.test(F))throw new l(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=U.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:V.name??(U instanceof File?U.name:"image"),mimeType:F,size:U.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:H,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(U)=>L3({...U,signal:U.signal?AbortSignal.any([z,U.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:P3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:_3(),meter:B3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function Y3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function K3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function O2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function Q3($,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 m$=10485760;function u$($){let Z=$?.maxBytes??m$;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 d$($){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 c$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,p$=/^[A-Za-z0-9+/]*={0,2}$/;function i$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function H3($,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 l$($,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 n$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function t$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function V3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?t$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!n$.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 J3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,H])=>[Q,H.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let H=[],U={};if($){let F=$.safeParse(Q);if(F.ok===!1)H.push(...F.errors);else U={...F.value}}let V=z.safeParse(Q);if(V.ok===!1)H.push(...V.errors);else U={...U,...V.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){H.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)H.push(...J.errors.map((j)=>`${F}: ${j}`));else U[F]=J.value}return H.length>0?{ok:!1,errors:H}:{ok:!0,value:U}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let H=K(Q);if(H.ok===!1)throw Error(H.errors.join(", "));return H.value}}}function s$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function o$($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function D2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)D2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function a$($){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 F3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!w$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>R)return`${W.slice(0,R)}\u2026 [cut at ${R} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>G3?`${z.slice(0,G3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as r$,randomBytes as e$,timingSafeEqual as $8}from"crypto";function j2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class Z8{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`${$}${e$(32).toString("base64url")}`}static hash($){return r$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&$8(z,G)}async resolve($){let Z=j2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as w3,randomBytes as x3}from"crypto";async function A2($,Z){let z=z8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function z8(){try{let $=E();return $.bound(t)?$.make(t):null}catch{return null}}var x2=["2026-07-28"],H2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...x2,...H2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as G8,timingSafeEqual as W8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!W8(K,Q))return null;let H;try{H=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof H!=="object"||H===null)return null;if(typeof H.exp!=="number"||H.exp<=G)return null;return H}function A3($,Z,z){return G8("sha256",U2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",C3="gemi.mcp.session.v1",X8=86400000,S3=600000,q3="gemi_approval",b2=2000,Y8={limit:600,window:60},K8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=U8(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,U2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??Y8,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??S3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?H8(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 T3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return T3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(j2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await Q8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new u($,{},"api",this.endpoint.pathname);return await m.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),k3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let H=this.session($,z),U=$.headers.get("mcp-protocol-version");if(U!==null&&U!==H.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${U} is not the session's ${H.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${H.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let V=`${H.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(V,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:H.state,sessionId:H.id},stream:I,signal:J}),k3(K)||J8(this.registry,Y,H.state),P,()=>this.inflight.delete(V))}catch(I){throw this.inflight.delete(V),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=H2.includes(G)?G:H2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:M3(X.elicitation),p:V2(z),exp:Date.now()+X8},K=k2(C3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(C3,"gms1",z);if(!G||G.p!==V2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||j3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,j)=>{G.outcome="denied",G.reason=J,G.message=j},K=(J,j,D)=>{if(G.outcome="error",G.message=J,j!==void 0)G.status=j;if(D!==void 0)G.error=D},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let D=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(D),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let D=await this.approval($,Q,z,Y,G);if(D.kind==="answer")return D.result;G.approved=!0}}let H=F8($),U=[],V;try{V=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>U.push(J),...H?{progress:H}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof h){let D=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,D),new _(L.InvalidParams,D)}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 F=typeof V==="string"?V:JSON.stringify(V??null),P=Q.outputSchema&&($.era.modern||M(V))?{structuredContent:V}:{},I=[...U.length>0&&V===null?[]:[{type:"text",text:F}],...U];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=N8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,j=V8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==V2($.principal)||T.t!==Z.name||T.a!==j)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return R3(I[q3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!M3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let D={p:V2($.principal),t:Z.name,a:j,n:x3(16).toString("base64url"),exp:Date.now()+S3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[q3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",D),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let H=`gemi-approval-${x3(12).toString("base64url")}`,U=Q.sessionId,V=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(H),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(H,{session:U,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(H),I(null)}),$.stream.send({jsonrpc:"2.0",id:H,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return V&&!V.error&&R3(V.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new v3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=b3(new u($,{},"api",this.endpoint.pathname)),z=await A2(`mcp-auth-failed:${Z}`,K8);return z===null?null:E3(z)}async spend($){if(!this.rateLimit)return null;let Z=await A2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:E3(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 J2 extends Error{}async function Q8($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new J2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new J2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function T3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function H8($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function U8($){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 V2($){return w3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function V8($){return w3("sha256").update(f3($??{})).digest("base64url")}function M3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function k3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function J8($,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 F8($){let z=(M($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function N8($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as c,Z as P,aa as f,ba as l}from"./chunk-
|
|
2
|
+
import{$ as c,Z as P,aa as f,ba as l}from"./chunk-rgcdf5pb.js";import{Ba as u,Ca as m}from"./chunk-mcgcgm6g.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-keqjdy8q.js";import"./chunk-ba1h9pm6.js";import"./chunk-jrvqya5h.js";import{Dj as S}from"./chunk-jqqyj6cr.js";import{um as T}from"./chunk-1v1ek1ey.js";import{Om as y}from"./chunk-kfcz4qa8.js";import"./chunk-30jcs49q.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
|
|
3
3
|
`).split(`
|
|
4
4
|
`).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
|
|
5
5
|
`).trim()}function N(J){return`
|