gemi 0.179.0 → 0.180.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +1 -1
- package/dist/auth/AuthManager.d.ts +5 -4
- package/dist/auth/AuthManager.d.ts.map +1 -1
- package/dist/auth/UserProvider.d.ts +1 -1
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/{chunk-q30ryk1a.js → chunk-6x3315an.js} +1 -1
- package/dist/chunk-gtfwk0ss.js +15 -0
- package/dist/{chunk-c0qq5t8a.js.map → chunk-gtfwk0ss.js.map} +5 -4
- package/dist/{chunk-f5mhc5eh.js → chunk-najr8410.js} +2 -2
- package/dist/{chunk-f5mhc5eh.js.map → chunk-najr8410.js.map} +1 -1
- package/dist/{chunk-xf8f9tbf.js → chunk-pqnva7v8.js} +1 -1
- package/dist/{chunk-66xyz4m3.js → chunk-qry4bf38.js} +4 -4
- package/dist/{chunk-66xyz4m3.js.map → chunk-qry4bf38.js.map} +4 -4
- package/dist/{chunk-ssmq5r41.js → chunk-y2rzqpgd.js} +1 -1
- package/dist/{chunk-51yv7x03.js → chunk-zd67c5rp.js} +1 -1
- package/dist/chunks/{RealtimeClient-DpAJYcF5.js → RealtimeClient-CHNbqDr7.js} +2 -2
- package/dist/chunks/{RealtimeClient-DpAJYcF5.js.map → RealtimeClient-CHNbqDr7.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-DAbL-cqC.js → ThemeProvider-Bkc6A9Nn.js} +240 -9
- package/dist/chunks/ThemeProvider-Bkc6A9Nn.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-yAKa_pKx.js → fetchFileRequest-BGEW4Wd7.js} +2 -2
- package/dist/chunks/{fetchFileRequest-yAKa_pKx.js.map → fetchFileRequest-BGEW4Wd7.js.map} +1 -1
- package/dist/chunks/{live-BvhWo-yY.js → live-l4vtaqXd.js} +3 -3
- package/dist/chunks/{live-BvhWo-yY.js.map → live-l4vtaqXd.js.map} +1 -1
- package/dist/chunks/{mutationExtras-_hbHxr6-.js → mutationExtras-C7UPW9XP.js} +2 -2
- package/dist/chunks/{mutationExtras-_hbHxr6-.js.map → mutationExtras-C7UPW9XP.js.map} +1 -1
- package/dist/client/ClientRouter.d.ts.map +1 -1
- package/dist/client/QueryResource.d.ts.map +1 -1
- package/dist/client/authenticationErrors.d.ts +116 -0
- package/dist/client/authenticationErrors.d.ts.map +1 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +41 -53
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts +15 -0
- package/dist/client/init.d.ts.map +1 -1
- package/dist/client/retryPolicy.d.ts +14 -3
- package/dist/client/retryPolicy.d.ts.map +1 -1
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/errors.d.ts.map +1 -1
- package/dist/http/index.js +1 -1
- package/dist/http/signInHeader.d.ts +14 -0
- package/dist/http/signInHeader.d.ts.map +1 -0
- 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/dist/testing/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-c0qq5t8a.js +0 -15
- package/dist/chunks/ThemeProvider-DAbL-cqC.js.map +0 -1
- /package/dist/{chunk-q30ryk1a.js.map → chunk-6x3315an.js.map} +0 -0
- /package/dist/{chunk-xf8f9tbf.js.map → chunk-pqnva7v8.js.map} +0 -0
- /package/dist/{chunk-ssmq5r41.js.map → chunk-y2rzqpgd.js.map} +0 -0
- /package/dist/{chunk-51yv7x03.js.map → chunk-zd67c5rp.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$b as $8,$c as J6,Ac as t9,Bc as r9,Cc as C8,Ec as _8,Fc as T8,Gc as A8,Hc as R8,Ic as E8,Jc as j8,Kc as k8,Lc as x8,Mc as q8,Nc as I8,Oc as w8,Pc as b8,Rc as w,Sc as $9,Tc as s,Uc as T,Vc as Z8,Wc as s0,Xc as a0,Yb as J8,Yc as t0,Zb as NQ,Zc as r0,_b as UQ,_c as e0,ad as $6,bd as Q6,cc as xJ,cd as Z6,dc as S,dd as W6,ec as A,ed as K6,fd as DJ,gc as t8,gd as X6,hc as d8,hd as AQ,ic as KJ,id as Y6,jc as o0,jd as RQ,kc as g,kd as G6,lc as Q8,ld as EJ,mc as LQ,md as B$,nc as OQ,nd as V6,oc as CQ,od as H6,pc as m,pd as EQ,qc as _Q,qd as z6,rc as oJ,rd as D6,sc as MQ,sd as B6,tc as SQ,td as z$,uc as sJ,vc as U8,wc as L8,yc as O8,zc as v}from"../chunk-
|
|
2
|
+
import{$b as $8,$c as J6,Ac as t9,Bc as r9,Cc as C8,Ec as _8,Fc as T8,Gc as A8,Hc as R8,Ic as E8,Jc as j8,Kc as k8,Lc as x8,Mc as q8,Nc as I8,Oc as w8,Pc as b8,Rc as w,Sc as $9,Tc as s,Uc as T,Vc as Z8,Wc as s0,Xc as a0,Yb as J8,Yc as t0,Zb as NQ,Zc as r0,_b as UQ,_c as e0,ad as $6,bd as Q6,cc as xJ,cd as Z6,dc as S,dd as W6,ec as A,ed as K6,fd as DJ,gc as t8,gd as X6,hc as d8,hd as AQ,ic as KJ,id as Y6,jc as o0,jd as RQ,kc as g,kd as G6,lc as Q8,ld as EJ,mc as LQ,md as B$,nc as OQ,nd as V6,oc as CQ,od as H6,pc as m,pd as EQ,qc as _Q,qd as z6,rc as oJ,rd as D6,sc as MQ,sd as B6,tc as SQ,td as z$,uc as sJ,vc as U8,wc as L8,yc as O8,zc as v}from"../chunk-zd67c5rp.js";import{Ld as D8}from"../chunk-9aj6eavs.js";import"../chunk-r7j4c5t2.js";import{$h as _9,Ih as zQ,Ki as FQ,Lh as BQ,Ni as p$,Ri as PQ,ai as d0,bi as i0,ci as n0,di as q}from"../chunk-gtfwk0ss.js";import{Si as DQ,Ui as iJ,Vi as nJ}from"../chunk-jwvwve00.js";import{cj as h}from"../chunk-8zwm5n7d.js";import"../chunk-mby1wdny.js";import"../chunk-8v95cjc5.js";import"../chunk-q3g4xs1z.js";import{fk as n,gk as o,uk as SJ}from"../chunk-nwg70wza.js";import"../chunk-6t9zjhm6.js";import"../chunk-93s13x3v.js";import{hl as c9}from"../chunk-r36kq8x1.js";import"../chunk-9mcweetq.js";import"../chunk-zm4fdsq5.js";import{Al as eJ}from"../chunk-4hj0q8fs.js";import"../chunk-pw6ssy3a.js";import{existsSync as wQ,readdirSync as P6,readFileSync as V8}from"fs";import{isAbsolute as bQ,join as UJ,relative as fQ,sep as vQ}from"path";var H8="prompts.json",yQ=/\{\{>\s*([\w./-]+)\s*\}\}/g,X8=/\{\{(\w+)\}\}/g,hQ=/^[\w-]+(\/[\w-]+)*$/,Y8={dir:"app/agents",shared:"prompts"},OJ={},tJ=new Map,LJ;function gQ(){if(LJ===void 0){let J=UJ(eJ(),"dist","server",H8);LJ=wQ(J)?JSON.parse(V8(J,"utf8")):null}return LJ??null}function uQ(J){return J.replace(/\r?\n$/,"")}function G8(){return OJ.cache??Bun.env.NODE_ENV==="production"}function cQ(J){if(!hQ.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=OJ.dir??Y8.dir,Q=bQ($)?$:UJ(process.cwd(),$),Z=J.includes("/")?`${J}.md`:UJ(OJ.shared??Y8.shared,`${J}.md`);return UJ(Q,Z)}function mQ(J){let $=cQ(J),Q=G8()?tJ.get($):void 0;if(Q!==void 0)return Q;let Z=Bun.env.NODE_ENV==="production";if(Z){let K=gQ()?.[fQ(eJ(),$).split(vQ).join("/")];if(K!==void 0)return K}let W;try{W=uQ(V8($,"utf8"))}catch(K){if(K.code==="ENOENT"){let X=Z?` or in dist/server/${H8}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${$}${X}).`)}throw K}if(G8())tJ.set($,W);return W}function rJ(J,$){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return mQ(J).replace(yQ,(Q,Z)=>rJ(Z,[...$,J]))}class z8{static configure(J){OJ={...J},tJ.clear(),LJ=void 0}static render(J,$={}){return rJ(J,[]).replace(X8,(Q,Z)=>{if(!Object.hasOwn($,Z))throw Error(`The prompt "${J}" has no value for {{${Z}}}.`);return String($[Z])})}static placeholders(J){let $=[...rJ(J,[]).matchAll(X8)].map((Q)=>Q[1]);return[...new Set($)]}}class J$ extends D8{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await v.sweep({limit:100})===100);}}var CJ=20;function F8(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>K.state==="running").sort(Q),...J.filter((K)=>K.state!=="running").sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="running")X.push(`running since ${$$(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${$$(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${B8(K.error.message,200)}`:"failed";X.push(`failed at ${$$(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${B8(JSON.stringify(K.summary),300)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
|
|
3
3
|
`)}function $$(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function B8(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}class Z${table;sql;dialect;connection;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of pQ(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return SJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=this.q(),Q=this.clock($);await $`
|
|
4
4
|
INSERT INTO ${this.name($)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
@@ -167,10 +167,11 @@ export declare class AuthManager {
|
|
|
167
167
|
* row `createSessionV2` returns has the base select and none of a provider's
|
|
168
168
|
* `findSession` shaping, and every sign-in path returns this to the client or
|
|
169
169
|
* passes its `user` to `extendSession` (#619). One extra lookup by its unique
|
|
170
|
-
* token, on sign-in only. Should the read come back empty — a
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
* sign-in that has already
|
|
170
|
+
* token, on sign-in only. Should the read fail or come back empty — a
|
|
171
|
+
* database error on the read (which `findSession` no longer swallows, #1120),
|
|
172
|
+
* or an override that filters more narrowly than the row just written — the
|
|
173
|
+
* created row is returned rather than failing a sign-in that has already
|
|
174
|
+
* succeeded.
|
|
174
175
|
*/
|
|
175
176
|
createOrUpdateSession(user: {
|
|
176
177
|
email: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthManager.d.ts","sourceRoot":"","sources":["../../auth/AuthManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAItC,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAOlE,OAAO,EAIL,KAAK,UAAU,EAEhB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAgClE,qBAAa,WAAW;IACtB,MAAM,CAAC,KAAK,SAAU;IAEtB,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC;IAKtC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoB;IAE7C;;;;;;;;;;;;;;OAcG;gBAED,MAAM,GAAE,UAAe,EACvB,QAAQ,GAAE,YAAY,CAAC,GAAG,CAAsB;IAYlD;;;OAGG;IACG,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAIhE;;;OAGG;IACG,kBAAkB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAI7C;;;OAGG;IACH,IAAI,YAAY,IAAI,YAAY,CAE/B;IAED,+EAA+E;IAC/E,wBAAwB,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,GAAG,mBAAmB;IAcxF;;;;;;;;OAQG;IACH,OAAO,CAAC,YAAY;IAKpB,4EAA4E;IAC5E,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,MAAM,GAAG,SAAS;IAgB5D;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAiCjD;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;YACW,oBAAoB;IAiElC;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,SAAS,EAAE,MAAM;IA0BvE,8EAA8E;IAC9E,OAAO,CAAC,qBAAqB;IAK7B;;;;;;;;;;OAUG;YACW,YAAY;IA4B1B,OAAO,CAAC,aAAa;IASf,iBAAiB,CAAC,KAAK,EAAE,MAAM;IAE/B,aAAa,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE;IAI1D,YAAY,CAAC,KAAK,EAAE,MAAM;IA0B1B,uBAAuB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE;IAalE
|
|
1
|
+
{"version":3,"file":"AuthManager.d.ts","sourceRoot":"","sources":["../../auth/AuthManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAItC,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAOlE,OAAO,EAIL,KAAK,UAAU,EAEhB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAgClE,qBAAa,WAAW;IACtB,MAAM,CAAC,KAAK,SAAU;IAEtB,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC;IAKtC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoB;IAE7C;;;;;;;;;;;;;;OAcG;gBAED,MAAM,GAAE,UAAe,EACvB,QAAQ,GAAE,YAAY,CAAC,GAAG,CAAsB;IAYlD;;;OAGG;IACG,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;IAIhE;;;OAGG;IACG,kBAAkB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAI7C;;;OAGG;IACH,IAAI,YAAY,IAAI,YAAY,CAE/B;IAED,+EAA+E;IAC/E,wBAAwB,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,GAAG,mBAAmB;IAcxF;;;;;;;;OAQG;IACH,OAAO,CAAC,YAAY;IAKpB,4EAA4E;IAC5E,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,MAAM,GAAG,SAAS;IAgB5D;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAiCjD;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;YACW,oBAAoB;IAiElC;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,SAAS,EAAE,MAAM;IA0BvE,8EAA8E;IAC9E,OAAO,CAAC,qBAAqB;IAK7B;;;;;;;;;;OAUG;YACW,YAAY;IA4B1B,OAAO,CAAC,aAAa;IASf,iBAAiB,CAAC,KAAK,EAAE,MAAM;IAE/B,aAAa,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE;IAI1D,YAAY,CAAC,KAAK,EAAE,MAAM;IA0B1B,uBAAuB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE;IAalE;;;;;;;;;;;;;;;;;;;OAmBG;IACG,qBAAqB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE;IAiChE;;;;;;;OAOG;IACG,oBAAoB,CAAC,KAAK,EAAE,MAAM;;;;;;;;;;;IAgBxC;;;;;;;;;;OAUG;IACG,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;;;;;IA+BpD;;;OAGG;YACW,eAAe;IAS7B;;;;;OAKG;IACG,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAUnE;;;;;;;;;;;OAWG;IACG,iBAAiB,CACrB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,OAAO,EACb,OAAO,GAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAO,GAChC,OAAO,CACN;QAAE,MAAM,EAAE,IAAI,CAAC;QAAC,GAAG,EAAE,iBAAiB,CAAA;KAAE,GACxC;QAAE,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,mBAAmB,CAAA;KAAE,CAC1D;IAmDD;;;;;;OAMG;IACG,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;CAqB5E"}
|
|
@@ -7,7 +7,7 @@ import type { Account, AuthModels, CreateAccountArgs, CreateMagicLinkTokenArgs,
|
|
|
7
7
|
* Exported so that an override can **build on it rather than copy it**. A copy
|
|
8
8
|
* made field for field goes stale silently: it is how an application came to
|
|
9
9
|
* keep selecting `User.organizationId` after gemi stopped (#346), and a schema
|
|
10
|
-
* error inside `findSession`
|
|
10
|
+
* error inside `findSession` fails every signed-in request.
|
|
11
11
|
* Spread this, and the columns gemi adds later arrive on their own.
|
|
12
12
|
*
|
|
13
13
|
* Frozen, because it is shared: assigning into it would change every
|
|
@@ -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;;;;OAIG;gBACmB,MAAM,GAAE,UAA6B;IAE3D;;;;;;;OAOG;IACH,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAIlD;;;;;;;;;;;;;;;;;;;OAmBG;IACH,SAAS,CAAC,aAAa,IAAI,aAAa;IAIxC;;;;;;;;;;;;;;;;OAgBG;IACH,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAIhD;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,qBAAqB,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAuBzE;;;;;;;;;;;;;;;;OAgBG;IACG,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAO/C,kBAAkB,CAAC,IAAI,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAa/D,sBAAsB,CAC1B,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,OAAO,GACnB,OAAO,CAAC,IAAI,CAAC;IAaV,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAShE,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASxC,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,eAAe,CAAC;IAMtE;;;;OAIG;IACG,eAAe,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAMjE;;;;;;;;;OASG;IACG,WAAW,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;
|
|
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;;;;OAIG;gBACmB,MAAM,GAAE,UAA6B;IAE3D;;;;;;;OAOG;IACH,SAAS,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAIlD;;;;;;;;;;;;;;;;;;;OAmBG;IACH,SAAS,CAAC,aAAa,IAAI,aAAa;IAIxC;;;;;;;;;;;;;;;;OAgBG;IACH,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAIhD;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,qBAAqB,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAuBzE;;;;;;;;;;;;;;;;OAgBG;IACG,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAO/C,kBAAkB,CAAC,IAAI,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC;IAa/D,sBAAsB,CAC1B,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,OAAO,GACnB,OAAO,CAAC,IAAI,CAAC;IAaV,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAShE,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASxC,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,eAAe,CAAC;IAMtE;;;;OAIG;IACG,eAAe,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAMjE;;;;;;;;;OASG;IACG,WAAW,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAkBlE;;;;;OAKG;IACG,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;IAUhE,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAc3D;;;;;;;;OAQG;IACG,kBAAkB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC;IAU7D,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMpD,wBAAwB,CAC5B,IAAI,EAAE,4BAA4B,GACjC,OAAO,CAAC,MAAM,CAAC;IAWZ,sBAAsB,CAC1B,IAAI,EAAE,0BAA0B,GAC/B,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAU/B,wBAAwB,CAC5B,IAAI,EAAE,4BAA4B,GACjC,OAAO,CAAC,MAAM,CAAC;IAMZ,cAAc,CAClB,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,UAAU,CAAC;IAWhB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQzD,aAAa,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAY/D,oBAAoB,CACxB,IAAI,EAAE,wBAAwB,GAC7B,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAQ1C;;;;OAIG;IACG,sBAAsB,CAAC,IAAI,EAAE;QACjC,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,KAAK,EAAE,MAAM,CAAC;KACf,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAwBxB;;;;OAIG;IACG,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IASjF;;;OAGG;IACG,0BAA0B,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAU3F,gFAAgF;IAC1E,2BAA2B,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;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{Dc as B9,Qc as P9,Yb as E9,ac as K3,bc as b9,fc as F9,kc as e,ud as I9,xc as N9}from"./chunk-51yv7x03.js";import{Bd as i3,Dd as B3,Gd as i9,Hd as l9,Id as J$,Kd as O$}from"./chunk-rv0r5fde.js";import{$d as x,Nd as h9,Sd as m9,Ud as u9,ae as d9,be as c9,de as p9,ee as L$}from"./chunk-r7j4c5t2.js";import{he as P}from"./chunk-zqptpk90.js";import{Af as Z3,Bg as w3,Cg as $$,De as x$,Dg as G3,Eg as Z$,Fg as z$,Ge as U$,Gf as H3,Gg as v3,Hf as u3,Hg as a,If as k,Kg as q$,Lf as V$,Lg as L3,Mf as Y$,Mg as p3,Nf as K$,Pf as w,Qe as F$,Re as l3,Rg as Q$,Sg as H$,Ve as J3,We as X3,Yg as A$,ag as e3,lg as a3,mf as d3,ng as n,rg as r3,sg as r9,tg as e9,ve as l,we as X$,xg as g3,yg as f3,ze as R9}from"./chunk-66xyz4m3.js";import{Hi as J9,Li as P3,Mi as F3,Ni as z3,bi as p,di as m,si as o3}from"./chunk-c0qq5t8a.js";import{Ti as s9}from"./chunk-jwvwve00.js";import{cj as g}from"./chunk-8zwm5n7d.js";import{ij as c3}from"./chunk-47cjayhh.js";import{lj as N$,mj as n3,pj as N3,qj as t3,tj as P$}from"./chunk-s0m717j8.js";import{Hj as t9,Mj as o9}from"./chunk-mby1wdny.js";import{ak as g9,ck as u}from"./chunk-8v95cjc5.js";import{dk as A}from"./chunk-q3g4xs1z.js";import{jk as D$}from"./chunk-nwg70wza.js";import{Zk as s3}from"./chunk-y3pnwpvp.js";import{el as U3,hl as y}from"./chunk-r36kq8x1.js";import{ql as m3}from"./chunk-zm4fdsq5.js";import{Cl as a9}from"./chunk-e7hb47yy.js";var T$="mcp",k$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends e{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class v extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $9=/^[A-Za-z0-9_-]{1,64}$/,M$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z9=4000,M=1e5,R$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L9=new WeakMap;function V6($){return L9.get($)}class i{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=w$(z.files),this.featureOn=z.featureOn??X3;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,E$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D3($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y9(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(Y9(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={}){D3($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new v(`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 v(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!W3(X))throw new v(`"${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 V=Q.value,H={caller:$,req:$.req,tool:K,input:V,ctx:G},U=await this.fillPath(Y,H),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${U}`));if(I!==K.url)throw new O(`"${Z}" has nothing at ${U}.`,404);let J={};for(let _ of Y.jsonKeys)if(V[_]!==void 0)J[_]=V[_];let F,B="";if(Y.fileFields.length>0)F=await this.formData(Y,J,H);else if(K.method==="GET")B=l$(J);else if(Y.jsonKeys.length>0)F=J;let T=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(H)):void 0,j={...T?{credentials:T}:{},...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}:{}}}}:{}},C;try{let _=B?`${U}?${B}`:U;C=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,_,F,j):await this.dispatcher.dispatchAs($.req,K.method,_,F)}catch(_){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,_),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await U9(Z,C);return await this.project(Y,H,C)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$9.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(M$)].map(([,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((h)=>h.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(Q9(S))u$(z,`params.${N}`,S);else K9(z,`params.${N}`,S)}let V=[],H;if(X.input){if(H=X.input.toJSONSchema(),H.type!=="object"||!H.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);V=Object.keys(H.properties)}let U=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of U)K9(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 I=V9(z,G,X.annotations);if(U.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let J={},F=(N,S)=>{if(N in J)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);J[N]=S},B=new Map,T=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let h=p.string().describe(`The ":${N.name}" segment of the url.`);F(N.name,N.modifier==="?"||N.modifier==="*"?h.optional():h)}else if(Q9(S)){let h=S.as??N.name;F(h,S.input),T.set(N.name,{key:h,param:S})}else B.set(N.name,S)}let j={};for(let N of U)if(N.binder==="input")F(N.name,p.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let C=[...Object.keys(J),...U.map((N)=>N.name)];for(let N of new Set(C))if(V.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let _=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:H9(X.input,H,p.object(J)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),r=!U.every((N)=>N.binder==="input")?null:U.length===0?_:Object.freeze({..._,inputSchema:H9(X.input,H,p.object(p$(J,Object.keys(j))),j)});return{kind:"route",descriptor:_,remote:r,params:K,paramBinders:B,modelParams:T,fileFields:U,jsonKeys:V,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let V of Object.keys(Y))if(!W.includes(V))K.push(`a file has no field "${V}"`);for(let V of W){let H=Y[V];if(H===void 0||H===null){if(V==="name"||V==="mimeType")K.push(`a file needs "${V}"`);continue}if(typeof H!=="string")K.push(`a file's "${V}" must be a string`);else Q[V]=H}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$9.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:V9(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(!W3(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 V=G.signal??new AbortController().signal;return X9(X,Y.value,W9(G9(X,Q,V)))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return W3(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(D3($),$.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 L9.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=(_,_3)=>{if(!W.progress)return;let r;try{r=$.meta.remote?.progress?$.meta.remote.progress(_,_3):y$(_,_3)}catch(N){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,N);return}if(r)W.progress(r)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z9(this.runNative($,{...K,ctx:G},G),Q)}let V=$.meta.remote,H=await this.bind($,"the remote context",()=>V.context(K));if(typeof H!=="object"||H===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,H),new O(`"${X}" failed on the server.`,500);let U=$.tool.timeoutMs,I=[...W.signal?[W.signal]:[],...U!==void 0?[AbortSignal.timeout(U)]:[]],J=I.length===0?new AbortController().signal:I.length===1?I[0]:AbortSignal.any(I),F=G9($,H,J);if(!W.approved&&W3($)&&await X9($,K.input,W9(F)))throw new v(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let B;try{B=await z9(this.runNative($,{...K,ctx:F},F),Q,J)}catch(_){if(J.aborted&&_===J.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${U} ms.`,504)}if(_ instanceof O)throw _;if(_ instanceof e||_ instanceof v)throw new O(_.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,_),new O(`"${X}" failed on the server.`,500)}let T=(_)=>{return console.error(`[gemi/mcp] "${X}" ${_}`),new O(`"${X}" failed on the server.`,500)};if(N9(B))throw T("answered a job handle, and a remote call has no background jobs.");let j=B;if($.descriptor.outputSchema){let _=$.descriptor.outputSchema.safeParse(j);if(_.ok===!1)throw T(`answered what its output schema refuses: ${_.errors.join(", ")}`);j=_.value}if(j===void 0)return null;if(typeof j==="string")return j.length>M?`${j.slice(0,M)}\u2026 [cut at ${M} of ${j.length} characters]`:j;let C=JSON.stringify(j);if(C!==void 0&&C.length>M)return`${C.slice(0,M)}\u2026 [cut at ${M} of ${C.length} characters]`;return j}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let V=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${V}`,"");continue}W=W.replace(V,i$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,V]of Object.entries(Z))O3(K,Q,V);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O3(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=(H)=>new O(`"${Z}" of "${$}" ${H}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!v$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!g$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let H=W.data.replace(/\s+/g,"");if(Math.floor(H.length*3/4)-m$(H)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(H.length%4!==0||!h$.test(H))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(H,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let V;try{V=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(V.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let H=await J9(V.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!H.ok)throw G(`could not be fetched: ${V.host} answered ${H.status}.`);let U=await H.arrayBuffer();return new File([U],W.name,{type:W.mimeType})}catch(H){if(H instanceof O)throw H;throw G(`could not be fetched from ${V.host}: ${H instanceof Error?H.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(T$,{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(!k$.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 U9(G,z);let X=(U,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${G}" ${U}`);else console.error(`[gemi/mcp] "${G}" ${U}`,I);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 V=Q;if($.result)try{V=await $.result(Q,Z)}catch(U){throw X("failed in its result projection:",U)}if(W){let U=W.safeParse(V);if(U.ok===!1)throw X(`answered what its output schema refuses: ${U.errors.join(", ")}`);V=U.value}if(V===void 0)return null;let H=JSON.stringify(V);if(H!==void 0&&H.length>M)return`${H.slice(0,M)}\u2026 [cut at ${M} of ${H.length} characters]`;return V}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof e)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function E$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function b$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z9($,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(!b$($))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 y$($,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 G9($,Z,z){let G=$.descriptor.name,W=`mcp_${crypto.randomUUID()}`,X=`mcp_call_${crypto.randomUUID()}`,Y=(Q)=>async()=>{throw new e(`"${G}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},K={put:Y("attachment store"),get:Y("attachment store"),read:Y("attachment store"),file:Y("attachment store")};return{context:Z,body:{},runId:W,toolCallId:X,signal:z,step:1,depth:0,resumed:!1,attachments:K,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:Y("agent run to nest a sub-agent in"),generateImage:Y("attachment store to put an image in"),editImage:Y("attachment store to put an image in"),generate:(Q)=>I9({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:G,runId:W,toolCallId:X}}),jobs:B9({jobs:void 0,threadId:void 0,runId:W,toolCallId:X,toolName:G,depth:0,async:$.tool.async,attachments:null}),memory:P9(),meter:F9().meter}}function W3($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W9($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X9($,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 D3($){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 Y9($,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 f$=10485760;function w$($){let Z=$?.maxBytes??f$;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 v$($){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 g$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,h$=/^[A-Za-z0-9+/]*={0,2}$/;function m$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K9($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q9($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function u$($,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 d$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function c$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function V9($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?c$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!d$.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 H9($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,V])=>[Q,V.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let V=[],H={};if($){let I=$.safeParse(Q);if(I.ok===!1)V.push(...I.errors);else H={...I.value}}let U=z.safeParse(Q);if(U.ok===!1)V.push(...U.errors);else H={...H,...U.value};for(let[I,J]of Object.entries(G)){let F=Q[I];if(F===void 0){V.push(`"${I}" is required`);continue}let B=J.safeParse(F);if(B.ok===!1)V.push(...B.errors.map((T)=>`${I}: ${T}`));else H[I]=B.value}return V.length>0?{ok:!1,errors:V}:{ok:!0,value:H}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let V=K(Q);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function p$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function i$($,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 O3($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O3($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function l$($){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 U9($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!R$.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>M)return`${W.slice(0,M)}\u2026 [cut at ${M} 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>Z9?`${z.slice(0,Z9)}\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 n$,randomBytes as s$,timingSafeEqual as t$}from"crypto";function j3($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class o${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`${$}${s$(32).toString("base64url")}`}static hash($){return n$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&t$(z,G)}async resolve($){let Z=j3($);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 y9,randomBytes as j9}from"crypto";async function A3($,Z){let z=a$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function a$(){try{let $=y();return $.bound(l)?$.make(l):null}catch{return null}}var x3=["2026-07-28"],Y3=["2025-11-25","2025-06-18","2025-03-26"],C3=[...x3,...Y3],S3="io.modelcontextprotocol/protocolVersion",q3="io.modelcontextprotocol/clientCapabilities";var T3="io.modelcontextprotocol/serverInfo",D={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function R($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _9($){if(Array.isArray($))throw new L(D.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(D.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(D.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(D.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(D.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function k3($,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 q($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D9($){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 r$,timingSafeEqual as e$}from"crypto";function M3($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O9($,Z,G).toString("base64url")}`}function R3($,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=O9($,Z,X);if(K.length!==Q.length||!e$(K,Q))return null;let V;try{V=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof V!=="object"||V===null)return null;if(typeof V.exp!=="number"||V.exp<=G)return null;return V}function O9($,Z,z){return r$("sha256",K3($)).update(`${Z}.${z}`).digest()}var E3="gemi.mcp.request-state.v1",A9="gemi.mcp.session.v1",$2=86400000,x9=600000,C9="gemi_approval",b3=2000,Z2={limit:600,window:60},z2={limit:30,window:60};class $3{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;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=X2(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");if(this.resolvers=G,K3(E3),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??Z2,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 E9,this.approvalTimeoutMs=Z.approvalTimeoutMs??x9,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??X3;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(Z.host!==this.endpoint.host)return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return f(R(null,new L(D.InvalidRequest,"Origin not allowed.")),403);let G=z?W2(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 S9(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S9(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(j3($)!==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 G2($,this.maxBodyBytes))}catch(Y){if(Y instanceof V3)return f(R(null,new L(D.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return f(R(null,new L(D.ParseError,"Parse error.")),400)}let X=new m($,{},"api",this.endpoint.pathname);return await g.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=q(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return f(R(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),f(R(null,new L(D.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_9(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let F=this.session($,z),B=this.pending.get(String(W.message.id));if(B&&B.session===F.id)this.pending.delete(String(W.message.id)),B.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=q(K._meta)?K._meta:{};if(typeof Q[S3]==="string"){if(this.checkModernHeaders($,Y,Q[S3]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(F,B)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:F,signal:B}),T9(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(D.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let V=this.session($,z),H=$.headers.get("mcp-protocol-version");if(H!==null&&H!==V.state.v)throw new L(D.InvalidRequest,`MCP-Protocol-Version ${H} is not the session's ${V.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let F=K.requestId;this.inflight.get(`${V.id}:${String(F)}`)?.abort()}return new Response(null,{status:202})}let U=`${V.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(U,I);let J=AbortSignal.any([I.signal,$.signal]);try{return await this.respond(Y,async(F,B)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:V.state,sessionId:V.id},stream:F,signal:B}),T9(K)||K2(this.registry,Y,V.state),J,()=>this.inflight.delete(U))}catch(F){throw this.inflight.delete(U),F}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C3,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)=>k3(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(D.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)=>k3(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(D.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T3]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Y3.includes(G)?G:Y3[0],X=q(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q9(X.elicitation),p:Q3(z),exp:Date.now()+$2},K=M3(A9,"gms1",Y);return f({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(D.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R3(A9,"gms1",z);if(!G||G.p!==Q3(Z))throw new L(D.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x3.includes(z))throw new L(D.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C3,requested:z},400);let G=(Y)=>new L(D.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||D9(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(D.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,F)=>{G.outcome="denied",G.reason=J,G.message=F},K=(J,F,B)=>{if(G.outcome="error",G.message=J,F!==void 0)G.status=F;if(B!==void 0)G.error=B},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(D.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let B=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(B),this.toolResult($,{content:[{type:"text",text:B}],isError:!0})}if($.era.modern&&q($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let B=await this.approval($,Q,z,Y,G);if(B.kind==="answer")return B.result;G.approved=!0}}let V=Q2($),H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,...V?{progress:V}:{}})}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 v){let B=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,B),new L(D.InvalidParams,B)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let F=`"${Z}" failed on the server.`;return K(F,void 0,J),this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}let U=typeof H==="string"?H:JSON.stringify(H??null),I=Q.outputSchema&&($.era.modern||q(H))?{structuredContent:H}:{};return G.outcome="ok",this.toolResult($,{content:[{type:"text",text:U}],...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=V2(Z,z),Y=(I,J="approval-declined")=>{return G(J,I),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:I}],isError:!0})}},K=(I,J)=>{return G(I,J.message),J};if($.era.modern){let I=q($.params._meta)?$.params._meta:{},J=q(I[q3])?I[q3]:{},F=q($.params.inputResponses)?$.params.inputResponses:null,B=$.params.requestState,T=Y2(z);if(F&&B!==void 0){let C=R3(E3,"grs1",B);if(!C||C.p!==Q3($.principal)||C.t!==Z.name||C.a!==T)throw K("approval-invalid",new L(D.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(C.n,C.exp))throw K("approval-replayed",new L(D.InvalidParams,"requestState has already been used."));return k9(F[C9])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q9(J.elicitation))throw K("approval-unavailable",new L(D.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:Q3($.principal),t:Z.name,a:T,n:j9(16).toString("base64url"),exp:Date.now()+x9};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C9]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:M3(E3,"grs1",j),_meta:{[T3]: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 V=`gemi-approval-${j9(12).toString("base64url")}`,H=Q.sessionId,U=await new Promise((I)=>{let J=setTimeout(()=>{this.pending.delete(V),I(null)},this.approvalTimeoutMs),F=(B)=>{clearTimeout(J),I(B)};this.pending.set(V,{session:H,resolve:F}),$.signal.addEventListener("abort",()=>{this.pending.delete(V),F(null)}),$.stream.send({jsonrpc:"2.0",id:V,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return U&&!U.error&&k9(U.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 f({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f9(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(R($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(R($.id,new L(D.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return f(R(null,new L(D.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R9(new m($,{},"api",this.endpoint.pathname)),z=await A3(`mcp-auth-failed:${Z}`,z2);return z===null?null:M9(z)}async spend($){if(!this.rateLimit)return null;let Z=await A3(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:M9(Z)}}class f9{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
2
|
+
import{Dc as B9,Qc as P9,Yb as E9,ac as K3,bc as b9,fc as F9,kc as e,ud as I9,xc as N9}from"./chunk-zd67c5rp.js";import{Bd as i3,Dd as B3,Gd as i9,Hd as l9,Id as J$,Kd as O$}from"./chunk-rv0r5fde.js";import{$d as x,Nd as h9,Sd as m9,Ud as u9,ae as d9,be as c9,de as p9,ee as L$}from"./chunk-r7j4c5t2.js";import{he as P}from"./chunk-zqptpk90.js";import{Af as Z3,Bg as w3,Cg as $$,De as x$,Dg as G3,Eg as Z$,Fg as z$,Ge as U$,Gf as H3,Gg as v3,Hf as u3,Hg as a,If as k,Kg as q$,Lf as V$,Lg as L3,Mf as Y$,Mg as p3,Nf as K$,Pf as w,Qe as F$,Re as l3,Rg as Q$,Sg as H$,Ve as J3,We as X3,Yg as A$,ag as e3,lg as a3,mf as d3,ng as n,rg as r3,sg as r9,tg as e9,ve as l,we as X$,xg as g3,yg as f3,ze as R9}from"./chunk-qry4bf38.js";import{Hi as J9,Li as P3,Mi as F3,Ni as z3,bi as p,di as m,si as o3}from"./chunk-gtfwk0ss.js";import{Ti as s9}from"./chunk-jwvwve00.js";import{cj as g}from"./chunk-8zwm5n7d.js";import{ij as c3}from"./chunk-47cjayhh.js";import{lj as N$,mj as n3,pj as N3,qj as t3,tj as P$}from"./chunk-s0m717j8.js";import{Hj as t9,Mj as o9}from"./chunk-mby1wdny.js";import{ak as g9,ck as u}from"./chunk-8v95cjc5.js";import{dk as A}from"./chunk-q3g4xs1z.js";import{jk as D$}from"./chunk-nwg70wza.js";import{Zk as s3}from"./chunk-y3pnwpvp.js";import{el as U3,hl as y}from"./chunk-r36kq8x1.js";import{ql as m3}from"./chunk-zm4fdsq5.js";import{Cl as a9}from"./chunk-e7hb47yy.js";var T$="mcp",k$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends e{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class v extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var $9=/^[A-Za-z0-9_-]{1,64}$/,M$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,Z9=4000,M=1e5,R$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,L9=new WeakMap;function V6($){return L9.get($)}class i{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=w$(z.files),this.featureOn=z.featureOn??X3;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,E$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(D3($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(Y9(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(Y9(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={}){D3($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new v(`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 v(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!W3(X))throw new v(`"${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 V=Q.value,H={caller:$,req:$.req,tool:K,input:V,ctx:G},U=await this.fillPath(Y,H),{path:I}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${U}`));if(I!==K.url)throw new O(`"${Z}" has nothing at ${U}.`,404);let J={};for(let _ of Y.jsonKeys)if(V[_]!==void 0)J[_]=V[_];let F,B="";if(Y.fileFields.length>0)F=await this.formData(Y,J,H);else if(K.method==="GET")B=l$(J);else if(Y.jsonKeys.length>0)F=J;let T=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(H)):void 0,j={...T?{credentials:T}:{},...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}:{}}}}:{}},C;try{let _=B?`${U}?${B}`:U;C=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,_,F,j):await this.dispatcher.dispatchAs($.req,K.method,_,F)}catch(_){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,_),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await U9(Z,C);return await this.project(Y,H,C)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!$9.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(M$)].map(([,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((h)=>h.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(Q9(S))u$(z,`params.${N}`,S);else K9(z,`params.${N}`,S)}let V=[],H;if(X.input){if(H=X.input.toJSONSchema(),H.type!=="object"||!H.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);V=Object.keys(H.properties)}let U=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of U)K9(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 I=V9(z,G,X.annotations);if(U.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let J={},F=(N,S)=>{if(N in J)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);J[N]=S},B=new Map,T=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let h=p.string().describe(`The ":${N.name}" segment of the url.`);F(N.name,N.modifier==="?"||N.modifier==="*"?h.optional():h)}else if(Q9(S)){let h=S.as??N.name;F(h,S.input),T.set(N.name,{key:h,param:S})}else B.set(N.name,S)}let j={};for(let N of U)if(N.binder==="input")F(N.name,p.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let C=[...Object.keys(J),...U.map((N)=>N.name)];for(let N of new Set(C))if(V.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let _=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:H9(X.input,H,p.object(J)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:I,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),r=!U.every((N)=>N.binder==="input")?null:U.length===0?_:Object.freeze({..._,inputSchema:H9(X.input,H,p.object(p$(J,Object.keys(j))),j)});return{kind:"route",descriptor:_,remote:r,params:K,paramBinders:B,modelParams:T,fileFields:U,jsonKeys:V,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let V of Object.keys(Y))if(!W.includes(V))K.push(`a file has no field "${V}"`);for(let V of W){let H=Y[V];if(H===void 0||H===null){if(V==="name"||V==="mimeType")K.push(`a file needs "${V}"`);continue}if(typeof H!=="string")K.push(`a file's "${V}" must be a string`);else Q[V]=H}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!$9.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:V9(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(!W3(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 V=G.signal??new AbortController().signal;return X9(X,Y.value,W9(G9(X,Q,V)))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return W3(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(D3($),$.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 L9.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=(_,_3)=>{if(!W.progress)return;let r;try{r=$.meta.remote?.progress?$.meta.remote.progress(_,_3):y$(_,_3)}catch(N){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,N);return}if(r)W.progress(r)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await z9(this.runNative($,{...K,ctx:G},G),Q)}let V=$.meta.remote,H=await this.bind($,"the remote context",()=>V.context(K));if(typeof H!=="object"||H===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,H),new O(`"${X}" failed on the server.`,500);let U=$.tool.timeoutMs,I=[...W.signal?[W.signal]:[],...U!==void 0?[AbortSignal.timeout(U)]:[]],J=I.length===0?new AbortController().signal:I.length===1?I[0]:AbortSignal.any(I),F=G9($,H,J);if(!W.approved&&W3($)&&await X9($,K.input,W9(F)))throw new v(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let B;try{B=await z9(this.runNative($,{...K,ctx:F},F),Q,J)}catch(_){if(J.aborted&&_===J.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${U} ms.`,504)}if(_ instanceof O)throw _;if(_ instanceof e||_ instanceof v)throw new O(_.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,_),new O(`"${X}" failed on the server.`,500)}let T=(_)=>{return console.error(`[gemi/mcp] "${X}" ${_}`),new O(`"${X}" failed on the server.`,500)};if(N9(B))throw T("answered a job handle, and a remote call has no background jobs.");let j=B;if($.descriptor.outputSchema){let _=$.descriptor.outputSchema.safeParse(j);if(_.ok===!1)throw T(`answered what its output schema refuses: ${_.errors.join(", ")}`);j=_.value}if(j===void 0)return null;if(typeof j==="string")return j.length>M?`${j.slice(0,M)}\u2026 [cut at ${M} of ${j.length} characters]`:j;let C=JSON.stringify(j);if(C!==void 0&&C.length>M)return`${C.slice(0,M)}\u2026 [cut at ${M} of ${C.length} characters]`;return j}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let V=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${V}`,"");continue}W=W.replace(V,i$($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,V]of Object.entries(Z))O3(K,Q,V);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))O3(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=(H)=>new O(`"${Z}" of "${$}" ${H}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!v$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!g$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let H=W.data.replace(/\s+/g,"");if(Math.floor(H.length*3/4)-m$(H)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(H.length%4!==0||!h$.test(H))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(H,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let V;try{V=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(V.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let H=await J9(V.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!H.ok)throw G(`could not be fetched: ${V.host} answered ${H.status}.`);let U=await H.arrayBuffer();return new File([U],W.name,{type:W.mimeType})}catch(H){if(H instanceof O)throw H;throw G(`could not be fetched from ${V.host}: ${H instanceof Error?H.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(T$,{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(!k$.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 U9(G,z);let X=(U,I)=>{if(I===void 0)console.error(`[gemi/mcp] "${G}" ${U}`);else console.error(`[gemi/mcp] "${G}" ${U}`,I);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 V=Q;if($.result)try{V=await $.result(Q,Z)}catch(U){throw X("failed in its result projection:",U)}if(W){let U=W.safeParse(V);if(U.ok===!1)throw X(`answered what its output schema refuses: ${U.errors.join(", ")}`);V=U.value}if(V===void 0)return null;let H=JSON.stringify(V);if(H!==void 0&&H.length>M)return`${H.slice(0,M)}\u2026 [cut at ${M} of ${H.length} characters]`;return V}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof e)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function E$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function b$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function z9($,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(!b$($))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 y$($,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 G9($,Z,z){let G=$.descriptor.name,W=`mcp_${crypto.randomUUID()}`,X=`mcp_call_${crypto.randomUUID()}`,Y=(Q)=>async()=>{throw new e(`"${G}" was called by a remote MCP client, which has no ${Q}.`,{retryable:!1})},K={put:Y("attachment store"),get:Y("attachment store"),read:Y("attachment store"),file:Y("attachment store")};return{context:Z,body:{},runId:W,toolCallId:X,signal:z,step:1,depth:0,resumed:!1,attachments:K,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:Y("agent run to nest a sub-agent in"),generateImage:Y("attachment store to put an image in"),editImage:Y("attachment store to put an image in"),generate:(Q)=>I9({...Q,signal:Q.signal?AbortSignal.any([z,Q.signal]):z},{origin:{mcp:G,runId:W,toolCallId:X}}),jobs:B9({jobs:void 0,threadId:void 0,runId:W,toolCallId:X,toolName:G,depth:0,async:$.tool.async,attachments:null}),memory:P9(),meter:F9().meter}}function W3($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function W9($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function X9($,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 D3($){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 Y9($,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 f$=10485760;function w$($){let Z=$?.maxBytes??f$;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 v$($){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 g$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,h$=/^[A-Za-z0-9+/]*={0,2}$/;function m$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function K9($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function Q9($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function u$($,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 d$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function c$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function V9($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?c$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!d$.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 H9($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,V])=>[Q,V.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let V=[],H={};if($){let I=$.safeParse(Q);if(I.ok===!1)V.push(...I.errors);else H={...I.value}}let U=z.safeParse(Q);if(U.ok===!1)V.push(...U.errors);else H={...H,...U.value};for(let[I,J]of Object.entries(G)){let F=Q[I];if(F===void 0){V.push(`"${I}" is required`);continue}let B=J.safeParse(F);if(B.ok===!1)V.push(...B.errors.map((T)=>`${I}: ${T}`));else H[I]=B.value}return V.length>0?{ok:!1,errors:V}:{ok:!0,value:H}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let V=K(Q);if(V.ok===!1)throw Error(V.errors.join(", "));return V.value}}}function p$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function i$($,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 O3($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)O3($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function l$($){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 U9($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!R$.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>M)return`${W.slice(0,M)}\u2026 [cut at ${M} 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>Z9?`${z.slice(0,Z9)}\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 n$,randomBytes as s$,timingSafeEqual as t$}from"crypto";function j3($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class o${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`${$}${s$(32).toString("base64url")}`}static hash($){return n$("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&t$(z,G)}async resolve($){let Z=j3($);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 y9,randomBytes as j9}from"crypto";async function A3($,Z){let z=a$();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function a$(){try{let $=y();return $.bound(l)?$.make(l):null}catch{return null}}var x3=["2026-07-28"],Y3=["2025-11-25","2025-06-18","2025-03-26"],C3=[...x3,...Y3],S3="io.modelcontextprotocol/protocolVersion",q3="io.modelcontextprotocol/clientCapabilities";var T3="io.modelcontextprotocol/serverInfo",D={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class L extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function R($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function _9($){if(Array.isArray($))throw new L(D.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new L(D.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(D.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new L(D.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(D.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function k3($,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 q($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function D9($){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 r$,timingSafeEqual as e$}from"crypto";function M3($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${O9($,Z,G).toString("base64url")}`}function R3($,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=O9($,Z,X);if(K.length!==Q.length||!e$(K,Q))return null;let V;try{V=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof V!=="object"||V===null)return null;if(typeof V.exp!=="number"||V.exp<=G)return null;return V}function O9($,Z,z){return r$("sha256",K3($)).update(`${Z}.${z}`).digest()}var E3="gemi.mcp.request-state.v1",A9="gemi.mcp.session.v1",$2=86400000,x9=600000,C9="gemi_approval",b3=2000,Z2={limit:600,window:60},z2={limit:30,window:60};class $3{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;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=X2(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");if(this.resolvers=G,K3(E3),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??Z2,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 E9,this.approvalTimeoutMs=Z.approvalTimeoutMs??x9,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??X3;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(Z.host!==this.endpoint.host)return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return f(R(null,new L(D.InvalidRequest,"Origin not allowed.")),403);let G=z?W2(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 S9(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return S9(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(j3($)!==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 G2($,this.maxBodyBytes))}catch(Y){if(Y instanceof V3)return f(R(null,new L(D.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return f(R(null,new L(D.ParseError,"Parse error.")),400)}let X=new m($,{},"api",this.endpoint.pathname);return await g.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof L){let K=q(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return f(R(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),f(R(null,new L(D.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=_9(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let F=this.session($,z),B=this.pending.get(String(W.message.id));if(B&&B.session===F.id)this.pending.delete(String(W.message.id)),B.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=q(K._meta)?K._meta:{};if(typeof Q[S3]==="string"){if(this.checkModernHeaders($,Y,Q[S3]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(F,B)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:F,signal:B}),T9(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new L(D.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let V=this.session($,z),H=$.headers.get("mcp-protocol-version");if(H!==null&&H!==V.state.v)throw new L(D.InvalidRequest,`MCP-Protocol-Version ${H} is not the session's ${V.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let F=K.requestId;this.inflight.get(`${V.id}:${String(F)}`)?.abort()}return new Response(null,{status:202})}let U=`${V.id}:${String(Y.id)}`,I=new AbortController;this.inflight.set(U,I);let J=AbortSignal.any([I.signal,$.signal]);try{return await this.respond(Y,async(F,B)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:V.state,sessionId:V.id},stream:F,signal:B}),T9(K)||K2(this.registry,Y,V.state),J,()=>this.inflight.delete(U))}catch(F){throw this.inflight.delete(U),F}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C3,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)=>k3(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new L(D.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)=>k3(Z,!1))};case"tools/call":return await this.callTool($);default:throw new L(D.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T3]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=Y3.includes(G)?G:Y3[0],X=q(Z.capabilities)?Z.capabilities:{},Y={v:W,e:q9(X.elicitation),p:Q3(z),exp:Date.now()+$2},K=M3(A9,"gms1",Y);return f({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new L(D.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R3(A9,"gms1",z);if(!G||G.p!==Q3(Z))throw new L(D.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!x3.includes(z))throw new L(D.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C3,requested:z},400);let G=(Y)=>new L(D.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||D9(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(D.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof L?X.message:"Internal error.",!(X instanceof L))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,F)=>{G.outcome="denied",G.reason=J,G.message=F},K=(J,F,B)=>{if(G.outcome="error",G.message=J,F!==void 0)G.status=F;if(B!==void 0)G.error=B},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new L(D.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let B=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(B),this.toolResult($,{content:[{type:"text",text:B}],isError:!0})}if($.era.modern&&q($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let B=await this.approval($,Q,z,Y,G);if(B.kind==="answer")return B.result;G.approved=!0}}let V=Q2($),H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,...V?{progress:V}:{}})}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 v){let B=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,B),new L(D.InvalidParams,B)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let F=`"${Z}" failed on the server.`;return K(F,void 0,J),this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}let U=typeof H==="string"?H:JSON.stringify(H??null),I=Q.outputSchema&&($.era.modern||q(H))?{structuredContent:H}:{};return G.outcome="ok",this.toolResult($,{content:[{type:"text",text:U}],...I,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=V2(Z,z),Y=(I,J="approval-declined")=>{return G(J,I),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:I}],isError:!0})}},K=(I,J)=>{return G(I,J.message),J};if($.era.modern){let I=q($.params._meta)?$.params._meta:{},J=q(I[q3])?I[q3]:{},F=q($.params.inputResponses)?$.params.inputResponses:null,B=$.params.requestState,T=Y2(z);if(F&&B!==void 0){let C=R3(E3,"grs1",B);if(!C||C.p!==Q3($.principal)||C.t!==Z.name||C.a!==T)throw K("approval-invalid",new L(D.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(C.n,C.exp))throw K("approval-replayed",new L(D.InvalidParams,"requestState has already been used."));return k9(F[C9])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!q9(J.elicitation))throw K("approval-unavailable",new L(D.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:Q3($.principal),t:Z.name,a:T,n:j9(16).toString("base64url"),exp:Date.now()+x9};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[C9]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:M3(E3,"grs1",j),_meta:{[T3]: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 V=`gemi-approval-${j9(12).toString("base64url")}`,H=Q.sessionId,U=await new Promise((I)=>{let J=setTimeout(()=>{this.pending.delete(V),I(null)},this.approvalTimeoutMs),F=(B)=>{clearTimeout(J),I(B)};this.pending.set(V,{session:H,resolve:F}),$.signal.addEventListener("abort",()=>{this.pending.delete(V),F(null)}),$.stream.send({jsonrpc:"2.0",id:V,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return U&&!U.error&&k9(U.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 f({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new f9(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof L)K.send(R($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(R($.id,new L(D.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return f(R(null,new L(D.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=R9(new m($,{},"api",this.endpoint.pathname)),z=await A3(`mcp-auth-failed:${Z}`,z2);return z===null?null:M9(z)}async spend($){if(!this.rateLimit)return null;let Z=await A3(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:M9(Z)}}class f9{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 V3 extends Error{}async function G2($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V3;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 V3;W.push(K)}return Buffer.concat(W).toString("utf8")}function f($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function S9($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function W2($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function X2($){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 Q3($){return y9("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function Y2($){return y9("sha256").update(b9($??{})).digest("base64url")}function q9($){if(!q($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function T9($){let Z=q($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function K2($,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 Q2($){let z=(q($.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 V2($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b3?`${z.slice(0,b3)}\u2026 (${z.length-b3} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ui as q,Vi as L0,Wi as C0}from"./chunk-jwvwve00.js";import{$i as k0,cj as b}from"./chunk-8zwm5n7d.js";import{dl as P1}from"./chunk-93s13x3v.js";import{hl as _0}from"./chunk-r36kq8x1.js";import{Al as Y0}from"./chunk-4hj0q8fs.js";import{Il as lQ}from"./chunk-pw6ssy3a.js";class t0{static kind="controller";constructor(){}}class v1 extends t0{}function N0(Q){let Z=new Map;if(!Q)return Z;for(let $ of Q.split(";")){let X=$.indexOf("=");if(X===-1)continue;let G=$.slice(0,X).trim();if(!G)continue;Z.set(G,$.slice(X+1).trim())}return Z}function UZ(Q){return N0(Q.headers.get("cookie"))}function p(Q){if(!/^\d+$/.test(Q))return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}function s0(Q){if(!Q)return null;let Z=Q.trim();if(!/^bytes=/i.test(Z))return null;let X=Z.slice(6).split(",").map((D)=>D.trim()).filter((D)=>D!=="");if(X.length!==1)return null;let G=X[0],H=G.indexOf("-");if(H===-1)return null;let Y=G.slice(0,H),M=G.slice(H+1);if(Y===""){let D=p(M);if(D===null)return null;return{kind:"suffix",suffixLength:D}}let K=p(Y);if(K===null)return null;if(M==="")return{kind:"offset",start:K,end:null};let J=p(M);if(J===null||J<K)return null;return{kind:"offset",start:K,end:J}}function r0(Q,Z){if(!Number.isFinite(Z)||Z<=0)return null;let $,X;if(Q.kind==="suffix"){if(Q.suffixLength<=0)return null;$=Math.max(0,Z-Q.suffixLength),X=Z-1}else{if(Q.start>=Z)return null;if($=Q.start,X=Q.end===null?Z-1:Math.min(Q.end,Z-1),X<$)return null}return{start:$,end:X,length:X-$+1}}function VZ(Q){if(Q.kind==="suffix")return`bytes=-${Q.suffixLength}`;return Q.end===null?`bytes=${Q.start}-`:`bytes=${Q.start}-${Q.end}`}function BZ(Q){if(!Q)return null;let Z=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(Q.trim());if(!Z)return null;let $=p(Z[1]),X=p(Z[2]),G=p(Z[3]);if($===null||X===null||G===null||X<$)return null;return{start:$,end:X,total:G}}function PZ(Q,Z,$){return`bytes ${Q}-${Z}/${$}`}function a0(Q){return`bytes */${Q}`}class s extends q{errors={};constructor(Q){super("Validation error");this.name="ValidationError",this.errors=Q,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:Q,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function h1(Q){let[Z,$]=Q.match(/\d+|\D+/g)??[];if(!Z||!$)return 0;let X=Number.parseInt(Z);switch($){case"B":return X;case"KB":return X*1024;case"MB":return X*1024*1024;case"GB":return X*1024*1024*1024;case"TB":return X*1024*1024*1024*1024;default:return 0}}function m1(Q){switch(Q){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return Q}}function e0(Q){if(typeof Q==="string"||Array.isArray(Q))return Q.length;return}function w0(Q){return typeof Q==="number"&&!Number.isNaN(Q)}var c1=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class k extends Error{name="InvalidValidationRuleError"}function U0(Q,Z){let $=Z===void 0||Z.trim()===""?Number.NaN:Number(Z);if(Number.isNaN($))throw new k(`Validation rule "${Q}:${Z??""}" needs a number, e.g. "${Q}:3"`);return $}function Q1(Q){let Z=Q.indexOf(":"),$=Z===-1?Q:Q.slice(0,Z),X=Z===-1?void 0:Q.slice(Z+1);switch($){case"required":return(G)=>{if(G instanceof Blob)return G.size>0;if(G===null||G===void 0)return!1;if(typeof G==="string"||Array.isArray(G))return G.length>0;return!0};case"string":return(G)=>typeof G==="string";case"boolean":return(G)=>typeof G==="boolean";case"number":return(G)=>w0(G);case"password":return(G)=>{return typeof G==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(G)};case"min":{let G=U0($,X);return(H)=>{let Y=e0(H);return Y!==void 0&&Y>=G}}case"max":{let G=U0($,X);return(H)=>{let Y=e0(H);return Y!==void 0&&Y<=G}}case"gte":{let G=U0($,X);return(H)=>w0(H)&&H>=G}case"lte":{let G=U0($,X);return(H)=>w0(H)&&H<=G}case"email":return(G)=>{return typeof G==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G)};case"file":return(G)=>{return G instanceof Blob};case"fileType":{if(!X)throw new k('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let G=m1(X);return(H)=>H instanceof Blob&&H.type.startsWith(G)}case"fileSize":{let G=h1(X??"");if(G===0&&!/^0+(B|KB|MB|GB|TB)$/.test(X??""))throw new k(`Validation rule "fileSize:${X??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(H)=>H instanceof Blob&&H.size<=G}case"array":return(G)=>Array.isArray(G);case"object":return(G)=>typeof G==="object"&&G!==null&&!Array.isArray(G)&&!(G instanceof Blob);case"in":{let G=(X??"").split(",").filter((H)=>H!=="");if(G.length===0)throw new k('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(H)=>typeof H==="string"&&G.includes(H)}default:throw new k(`Unknown validation rule "${Q}". Known rules: ${c1.join(", ")}`)}}function u(Q){if(!Q.definition)throw Error(`gemi/ai: the recursive schema "${Q.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return Q.definition}var R0=new WeakMap;function X1(Q){return typeof Q==="object"&&Q!==null&&R0.has(Q)}function V0(Q){let Z=R0.get(Q);if(!Z)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return Z}function p1(Q){let Z={defs:{},cells:new Map},$=Q;if(Q.node.kind==="ref"){let G=u(Q.node.cell);$={...G,...Q.description?{description:Q.description}:{},optional:Q.optional,nullable:Q.nullable||G.nullable}}let X=a($,Z);return Object.keys(Z.defs).length>0?{...X,$defs:Z.defs}:X}function a(Q,Z){let $=(Q.optional||Q.nullable)&&Q.node.kind!=="json",X=i1(d1(Q.node,Z),$),G=[Q.description,u1(Q.node)].filter(Boolean).join(" ");if(G&&X.$ref!==void 0)X={anyOf:[X]};return G?{description:G,...X}:X}function u1(Q){let Z=[];if(Q.kind==="string"||Q.kind==="enum"){let $=Q.checks;if($?.format)Z.push(`Format: ${$.format.name}.`);if($?.minLength!==void 0)Z.push(`At least ${$.minLength} characters.`);if($?.maxLength!==void 0)Z.push(`At most ${$.maxLength} characters.`)}else if(Q.kind==="number"){let $=Q.checks;if($?.minimum!==void 0)Z.push(`Minimum ${$.minimum}.`);if($?.exclusiveMinimum!==void 0)Z.push(`Greater than ${$.exclusiveMinimum}.`);if($?.maximum!==void 0)Z.push(`Maximum ${$.maximum}.`);if($?.exclusiveMaximum!==void 0)Z.push(`Less than ${$.exclusiveMaximum}.`)}else if(Q.kind==="array"){let $=Q.checks;if($?.minItems!==void 0)Z.push(`At least ${$.minItems} items.`);if($?.maxItems!==void 0)Z.push(`At most ${$.maxItems} items.`)}return Z.join(" ")}function d1(Q,Z){switch(Q.kind){case"string":return{type:"string"};case"number":return{type:Q.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof Q.value,const:Q.value};case"enum":return{type:"string",enum:Q.values};case"array":return{type:"array",items:a(Q.item,Z)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,X])=>[$,a(X,Z)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(($)=>a($,Z))};case"json":return{};case"ref":{let{cell:$}=Q,X=Z.cells.get($.name);if(X&&X!==$)throw Error(`gemi/ai: two different recursive schemas are named "${$.name}" in one schema; give each s.recursive(...) its own name`);if(!X)Z.cells.set($.name,$),Z.defs[$.name]={},Z.defs[$.name]=a(u($),Z);return{$ref:`#/$defs/${$.name}`}}}}function i1(Q,Z){if(!Z)return Q;if(Q.anyOf)return{...Q,anyOf:[...Q.anyOf,{type:"null"}]};if(Q.enum||Q.const!==void 0)return{anyOf:[Q,{type:"null"}]};if(typeof Q.type==="string")return{...Q,type:[Q.type,"null"]};return{anyOf:[Q,{type:"null"}]}}function n1(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function l1(Q,Z){if(typeof Z==="number"&&!Number.isFinite(Z))return String(Z);if(Q.kind==="literal"||Q.kind==="enum"){if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return JSON.stringify(Z)}return n1(Z)}function G1(Q){let Z=Q.node,$=(()=>{switch(Z.kind){case"number":return Z.checks?.integer?"integer":"number";case"string":case"boolean":return Z.kind;case"literal":return JSON.stringify(Z.value);case"enum":return`one of ${Z.values.map((X)=>JSON.stringify(X)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return G1({...u(Z.cell),optional:!1,nullable:!1})}})();return Q.optional||Q.nullable?`${$} or null`:$}function o1(Q){let Z="";for(let $ of Q)Z+=typeof $==="number"?`[${$}]`:Z?`.${$}`:$;return Z}function t1(Q){let Z=o1(Q);return Z?`${Z}: `:""}function E0(Q){return`${t1(Q.path)}${Q.message}`}function B0(Q,Z){if(Z===null||Z===void 0)return Q.optional||Q.nullable?1:0;let $=Q.node;switch($.kind){case"string":return typeof Z==="string"?1:0;case"number":return typeof Z==="number"?1:0;case"boolean":return typeof Z==="boolean"?1:0;case"literal":return Z===$.value?10:0;case"enum":return typeof Z==="string"&&$.values.includes(Z)?10:0;case"array":return Array.isArray(Z)?1:0;case"object":{if(typeof Z!=="object"||Array.isArray(Z))return 0;let X=Z,G=1;for(let[H,Y]of Object.entries($.shape))G+=B0(Y,X[H]);return G}case"union":return $.members.reduce((X,G)=>Math.max(X,B0(G,Z)),0);case"json":return 1;case"ref":return H1($.cell,Z,()=>1,()=>B0(u($.cell),Z))}}function H1(Q,Z,$,X){if(typeof Z!=="object"||Z===null)return X();if(Q.active.has(Z))return $();Q.active.add(Z);try{return X()}finally{Q.active.delete(Z)}}function v(Q,Z,$,X){if(Q.optional&&(Z===null||Z===void 0))return{drop:!0,value:void 0};if(Q.nullable&&Z===null)return{drop:!1,value:null};return{drop:!1,value:s1(Q,Z,$,X)}}function s1(Q,Z,$,X){let G=Q.node,H=()=>{let Y=Z===void 0?"required":G.kind==="literal"?"const":G.kind==="enum"&&typeof Z==="string"?"enum":"type",M=Y==="const"?{allowedValue:G.value}:Y==="enum"?{allowedValues:G.values}:{};X.push({path:$,code:Y,message:`expected ${G1(Q)}, got ${l1(G,Z)}`,params:M});return};switch(G.kind){case"string":if(typeof Z!=="string")return H();return Z1(G.checks,Z,$,X),Z;case"number":if(typeof Z!=="number"||!Number.isFinite(Z))return H();if(G.checks?.integer&&!Number.isInteger(Z))return H();return a1(G.checks,Z,$,X),Z;case"boolean":return typeof Z==="boolean"?Z:H();case"literal":return Z===G.value?Z:H();case"enum":if(typeof Z!=="string"||!G.values.includes(Z))return H();return Z1(G.checks,Z,$,X),Z;case"array":{if(!Array.isArray(Z))return H();let Y=Z.map((J,D)=>{let U=v(G.item,J,[...$,D],X);return U.drop?void 0:U.value}),{minItems:M,maxItems:K}=G.checks??{};if(M!==void 0&&Z.length<M)X.push({path:$,code:"minItems",message:`expected at least ${M} items, got ${Z.length}`,params:{limit:M}});if(K!==void 0&&Z.length>K)X.push({path:$,code:"maxItems",message:`expected at most ${K} items, got ${Z.length}`,params:{limit:K}});return Y}case"object":{if(typeof Z!=="object"||Z===null||Array.isArray(Z))return H();let Y=Z,M={};for(let[K,J]of Object.entries(G.shape)){let D=v(J,Y[K],[...$,K],X);if(!D.drop)M[K]=D.value}if(G.unknownKeys)for(let K of Object.keys(Y)){if(Object.hasOwn(G.shape,K)||Y[K]===void 0)continue;if(G.unknownKeys==="error"){X.push({path:[...$,K],code:"additionalProperties",message:"unknown key",params:{additionalProperty:K}});continue}Z0(Y[K],[...$,K],X,new Set),Object.defineProperty(M,K,{value:Y[K],enumerable:!0,writable:!0,configurable:!0})}return M}case"union":{let Y;for(let M of G.members){let K=[],J=v(M,Z,$,K);if(K.length===0)return J.drop?void 0:J.value;let D=B0(M,Z);if(!Y||D>Y.score)Y={issues:K,score:D}}X.push({path:$,code:"anyOf",message:`no matching variant; closest: ${Y.issues.map(E0).join("; ")}`,params:{closest:Y.issues}});return}case"json":if(Z===void 0)return H();return Z0(Z,$,X,new Set),Z;case"ref":return H1(G.cell,Z,()=>{X.push({path:$,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>v(u(G.cell),Z,$,X).value)}}function r1(Q){let Z=0;for(let $ of Q)Z++;return Z}function Z1(Q,Z,$,X){if(!Q)return;let{minLength:G,maxLength:H,format:Y}=Q;if(G!==void 0||H!==void 0){let M=r1(Z);if(G!==void 0&&M<G)X.push({path:$,code:"minLength",message:`expected at least ${G} characters, got ${M}`,params:{limit:G}});if(H!==void 0&&M>H)X.push({path:$,code:"maxLength",message:`expected at most ${H} characters, got ${M}`,params:{limit:H}})}if(Y){let M=!1;try{M=Y.test(Z)===!0}catch{}if(!M)X.push({path:$,code:"format",message:`expected a string in format "${Y.name}"`,params:{format:Y.name}})}}function a1(Q,Z,$,X){if(!Q)return;let G=(H,Y,M,K)=>{if(Y===void 0||M(Y))return;X.push({path:$,code:H,message:`expected ${K} ${Y}, got ${Z}`,params:{limit:Y}})};G("minimum",Q.minimum,(H)=>Z>=H,"at least"),G("exclusiveMinimum",Q.exclusiveMinimum,(H)=>Z>H,"more than"),G("maximum",Q.maximum,(H)=>Z<=H,"at most"),G("exclusiveMaximum",Q.exclusiveMaximum,(H)=>Z<H,"less than")}function Z0(Q,Z,$,X,G=!0){let H=(M)=>{$.push({path:Z,code:"type",message:`expected a JSON value, got ${M}`,params:{}})};switch(typeof Q){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(Q))H(String(Q));return;case"bigint":return H("a bigint");case"function":return H("a function");case"symbol":return H("a symbol")}if(Q===null)return;let Y=Q;if(X.has(Y))return H("a circular reference");X.add(Y);try{let M=G?Y.toJSON:void 0;if(typeof M==="function"){let K;try{K=M.call(Y)}catch{return H("a toJSON that threw")}if(K===void 0)return H("a toJSON that returns undefined");return Z0(K,Z,$,X,!1)}if(Array.isArray(Q))Q.forEach((K,J)=>Z0(K,[...Z,J],$,X));else for(let[K,J]of Object.entries(Y))Z0(J,[...Z,K],$,X)}finally{X.delete(Y)}}function E(Q){return P0(Q)}function P0(Q){let Z={toJSONSchema:()=>p1(Q),parse($){let X=[],G=v(Q,$,[],X);if(X.length>0)throw Error(X.map(E0).join("; "));return G.drop?void 0:G.value},safeParse($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,errors:X.map(E0)};return{ok:!0,value:G.drop?void 0:G.value}},validate($){let X=[],G=v(Q,$,[],X);if(X.length>0)return{ok:!1,issues:X};return{ok:!0,value:G.drop?void 0:G.value}},describe:($)=>P0({...Q,description:$}),optional:()=>P0({...Q,optional:!0}),nullable:()=>P0({...Q,nullable:!0,optional:!1})};return R0.set(Z,Q),Z}function x(Q){return{node:Q,optional:!1,nullable:!1}}var $1=["strip","error","passthrough"];class Y1 extends Error{problems;constructor(Q){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
|
|
3
|
+
${Q.map((Z)=>`- ${Z}`).join(`
|
|
4
|
+
`)}`);this.name="JSONSchemaError",this.problems=Q}}var e1=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),r={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function z0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function j0(Q,Z,$,X){let G=(W,V=$)=>{X.push(V?`${V}: ${W}`:W);return},H=(W)=>$?`${$}.${W}`:W;if(!z0(Q))return G("expected a schema object");let Y=new Set(Z.ignoreKeywords??[]),M=(W)=>e1.has(W)||W.startsWith("x-")||Y.has(W),K=!1,J=Q.type;if(Array.isArray(J)){let W=J.filter((V)=>V!=="null");if(W.length!==1)return G(`type ${JSON.stringify(J)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,H("type"));K=W.length<J.length,J=W[0]}if(J!==void 0&&(typeof J!=="string"||!(J in r)))return G(`type ${JSON.stringify(J)} is not supported; expected one of ${Object.keys(r).join(", ")}`,H("type"));let D=new Set(["type","description","enum","const","anyOf",...J?r[J]:[]]),U=!1;for(let W of Object.keys(Q)){if(D.has(W)||M(W))continue;U=!0;let V=Object.entries(r).find(([,z])=>z.includes(W));G(V&&V[0]!==J?`"${W}" applies to type ${V[0]}, and this schema is ${J?`type ${J}`:"untyped"}`:`"${W}" is not supported by s.fromJSONSchema`,H(W))}if(U)return;if(Q.description!==void 0&&typeof Q.description!=="string")return G("expected a string",H("description"));let O=Q.description,B=(W)=>({node:W,optional:!1,nullable:K,...O?{description:O}:{}});if(Q.anyOf!==void 0){if(J!==void 0||Q.enum!==void 0||Q.const!==void 0)return G("anyOf cannot be combined with type, enum or const here",H("anyOf"));if(!Array.isArray(Q.anyOf)||Q.anyOf.length===0)return G("expected a non-empty array",H("anyOf"));let W=[],V=!1;if(Q.anyOf.forEach((z,P)=>{if(z0(z)&&z.type==="null"&&Object.keys(z).length===1){K=!0;return}let F=j0(z,Z,H(`anyOf[${P}]`),X);if(F)W.push(F);else V=!0}),V)return;if(W.length===0)return G("anyOf has only null in it",H("anyOf"));if(W.length===1){let z=W[0];return{...z,nullable:z.nullable||K,...O?{description:O}:{}}}return B({kind:"union",members:W})}if(Q.const!==void 0){let W=Q.const;if(typeof W!=="string"&&typeof W!=="number"&&typeof W!=="boolean")return G("only a string, number or boolean const is supported",H("const"));if(J!==void 0&&typeof W!==(J==="integer"?"number":J))return G(`const ${JSON.stringify(W)} is not of type ${J}`,H("const"));return B({kind:"literal",value:W})}let _;if(J==="string"){if(_=QQ(Q,Z,H,X),_===null)return}if(Q.enum!==void 0){if(!Array.isArray(Q.enum)||Q.enum.length===0)return G("expected a non-empty array",H("enum"));let W=Q.enum.filter((P)=>P!==null);if(W.length<Q.enum.length)K=!0;let V=W.find((P)=>!(typeof P==="string"||typeof P==="number"||typeof P==="boolean")||J!==void 0&&typeof P!==(J==="integer"?"number":J));if(V!==void 0||W.length===0)return G(J?`every value must be of type ${J}${W.length===0?", and there must be one":`; ${JSON.stringify(V)} is not`}`:"only strings, numbers and booleans are supported",H("enum"));if(W.every((P)=>typeof P==="string"))return B({kind:"enum",values:[...new Set(W)],..._?{checks:_}:{}});let z=[...new Set(W)];if(z.length===1)return B({kind:"literal",value:z[0]});return B({kind:"union",members:z.map((P)=>x({kind:"literal",value:P}))})}switch(J){case void 0:return G("a schema needs a type, an enum, a const or an anyOf");case"string":return B({kind:"string",..._?{checks:_}:{}});case"number":case"integer":{let W=J==="integer"?{integer:!0}:{},V=!1;for(let z of r.number){let P=Q[z];if(P===void 0)continue;if(typeof P!=="number"||!Number.isFinite(P)){G("expected a number",H(z)),V=!0;continue}W[z]=P}if(V)return;return B({kind:"number",...Object.keys(W).length>0?{checks:W}:{}})}case"boolean":return B({kind:"boolean"});case"array":{if(!z0(Q.items))return G('an array needs "items" to be one schema (tuples are not supported)',H("items"));let W={},V=!1;for(let P of["minItems","maxItems"]){let F=Q[P];if(F===void 0)continue;if(typeof F!=="number"||!Number.isInteger(F)||F<0){G("expected a non-negative integer",H(P)),V=!0;continue}W[P]=F}let z=j0(Q.items,Z,H("items"),X);if(!z||V)return;return B({kind:"array",item:z,...Object.keys(W).length>0?{checks:W}:{}})}case"object":{let W=Q.properties??{};if(!z0(W))return G("expected an object",H("properties"));if(Q.additionalProperties!==void 0&&Q.additionalProperties!==!1)return G("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",H("additionalProperties"));let V=Q.required??[];if(!Array.isArray(V)||!V.every((A)=>typeof A==="string"))return G("expected an array of property names",H("required"));let z=V.filter((A)=>!Object.hasOwn(W,A));if(z.length>0)return G(`lists properties the schema doesn't have: ${z.join(", ")}`,H("required"));let P={},F=!1;for(let[A,C]of Object.entries(W)){let R=j0(C,Z,H(`properties.${A}`),X);if(!R){F=!0;continue}P[A]=V.includes(A)?R:{...R,optional:!0}}if(F)return;let I=Z.unknownKeys;return B({kind:"object",shape:P,...I==="error"||I==="passthrough"?{unknownKeys:I}:{}})}}return}function QQ(Q,Z,$,X){let G={},H=!1;for(let Y of["minLength","maxLength"]){let M=Q[Y];if(M===void 0)continue;if(typeof M!=="number"||!Number.isInteger(M)||M<0){X.push(`${$(Y)}: expected a non-negative integer`),H=!0;continue}G[Y]=M}if(Q.format!==void 0){let Y=Q.format,M=typeof Y==="string"?Z.formats?.[Y]:void 0;if(typeof Y!=="string")X.push(`${$("format")}: expected a string`),H=!0;else if(!M||!Object.hasOwn(Z.formats,Y))X.push(`${$("format")}: unknown format ${JSON.stringify(Y)}; pass a check for it in the formats option`),H=!0;else G.format={name:Y,test:ZQ(M)}}if(H)return null;return Object.keys(G).length>0?G:void 0}function ZQ(Q){if(Q===!0)return()=>!0;if(Q instanceof RegExp)return(Z)=>{return Q.lastIndex=0,Q.test(Z)};return Q}var CZ={string:()=>E(x({kind:"string"})),number:()=>E(x({kind:"number"})),boolean:()=>E(x({kind:"boolean"})),literal:(Q)=>E(x({kind:"literal",value:Q})),enum:(Q)=>E(x({kind:"enum",values:Q})),object:(Q)=>E(x({kind:"object",shape:Object.fromEntries(Object.entries(Q).map(([Z,$])=>[Z,V0($)]))})),array:(Q)=>E(x({kind:"array",item:V0(Q)})),union:(Q)=>E(x({kind:"union",members:Q.map(V0)})),json:()=>E(x({kind:"json"})),recursive:XQ,fromJSONSchema:(Q,Z={})=>{let $=[];if(Z.unknownKeys!==void 0&&!$1.includes(Z.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${$1.map((G)=>JSON.stringify(G)).join(", ")}, got ${JSON.stringify(Z.unknownKeys)}`);let X=j0(Q,Z,"",$);if(!X||$.length>0)throw new Y1($.length>0?$:["unreadable schema"]);return E(X)}};function OZ(Q){let Z=R0.get(Q);if(Z)return Q0(Z.node);return e(Q.toJSONSchema())}function e(Q){if(!(Q.$ref!==void 0||Q.type!==void 0||Q.enum!==void 0||Q.const!==void 0||Q.anyOf!==void 0||Q.properties!==void 0||Q.items!==void 0))return!1;for(let $ of Object.values(Q.properties??{}))if(!e($))return!1;if(Q.items&&!e(Q.items))return!1;for(let $ of Q.anyOf??[])if(!e($))return!1;for(let $ of Object.values(Q.$defs??{}))if(!e($))return!1;return!0}function Q0(Q,Z=new Set){switch(Q.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(Q.shape).every(($)=>Q0($.node,Z));case"array":return Q0(Q.item.node,Z);case"union":return Q.members.every(($)=>Q0($.node,Z));case"json":return!1;case"ref":if(Z.has(Q.cell))return!0;return Z.add(Q.cell),Q0(u(Q.cell).node,Z)}}function S0(Q,Z,$=new Set){let X=Q.node;if(X.kind==="union")return X.members.some((G)=>S0(G,Z,$));if(X.kind!=="ref")return!1;if(X.cell===Z)return!0;if($.has(X.cell)||!X.cell.definition)return!1;return $.add(X.cell),S0(X.cell.definition,Z,$)}var $Q=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function XQ(Q,Z){if(typeof Q!=="string"||!$Q.test(Q))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(Q)}`);let $={name:Q,active:new Set},X=()=>x({kind:"ref",cell:$}),G=V0(Z(E(X())));if(G.optional)throw Error(`gemi/ai: the recursive schema "${Q}" is optional() as a whole; mark the places that use it optional instead`);if(S0(G,$))throw Error(`gemi/ai: the recursive schema "${Q}" refers to itself outside any object or array, so it describes no finite value; nest \`self\` in an s.object(...) field or an s.array(...)`);return $.definition=G,E(X())}function K1(Q){if(typeof Q!=="string")return null;let[Z]=Q.split(";",1),$=Z.trim().toLowerCase();return $===""?null:$}function M1(Q){if(Q===null)return!1;if(Q==="application/json")return!0;let Z=Q.indexOf("/");return Z>0&&Q.endsWith("+json")&&Q.length>Z+1+5}var $0=new WeakMap;function AZ(Q,Z,$,X){$0.set(Q,{clientAddress:Z,...$?{grant:Object.freeze({...$,scopes:Object.freeze([...$.scopes])})}:{},...X?{progress:X}:{}})}function J1(Q){return $0.get(Q)?.progress}function W1(Q){return $0.get(Q)?.grant}function D1(Q){return $0.has(Q)}function TZ(Q){return $0.get(Q)?.clientAddress}var U1=new WeakMap;function NZ(Q,Z){U1.set(Q,Z)}function z1(Q){return U1.get(Q)??null}var x0=new WeakMap;function wZ(Q,Z){let $=x0.get(Q)??[];if(!$.includes(Z))x0.set(Q,[...$,Z])}function EZ(Q){return x0.get(Q)??[]}class d{data;constructor(Q){this.data=Q}get(Q){return this.data[Q]}has(Q){return this.data[Q]!==void 0}toJSON(){return this.data}}function V1(Q){return typeof Q==="object"&&Q!==null&&!(Q instanceof Blob)}function GQ(Q,Z){if(!Z.includes(".")||Object.hasOwn(Q,Z))return[{path:[Z],value:Q[Z]}];let $=[{path:[],value:Q}];for(let X of Z.split(".")){let G=[];for(let{path:H,value:Y}of $){if(X==="*"){if(Array.isArray(Y))Y.forEach((M,K)=>G.push({path:[...H,K],value:M}));else if(V1(Y))for(let[M,K]of Object.entries(Y))G.push({path:[...H,M],value:K});continue}if(Array.isArray(Y)&&/^\d+$/.test(X)){G.push({path:[...H,Number(X)],value:Y[Number(X)]});continue}G.push({path:[...H,X],value:V1(Y)&&Object.hasOwn(Y,X)?Y[X]:void 0})}$=G}return $}function B1(Q){return Q.join(".")}class HQ{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(Q,Z,$,X){if(!Q){let K=b.getStore().req;this.params=K.params,this.rawRequest=K.rawRequest,this.kind=K.kind,this.routePath=K.routePath,this.domain=K.domain??null,this.state=K.state??new k0}else this.params=Z,this.rawRequest=Q,this.routePath=X,this.kind=$??"api",this.domain=z1(Q),this.state=new k0;this.headers=this.rawRequest.headers;let G=N0(this.rawRequest.headers.get("Cookie")),H=new URL(this.rawRequest.url),Y=new Map;for(let[K,J]of H.searchParams)if(Y.has(K)){let D=Y.get(K);if(Array.isArray(D))D.push(J),Y.set(K,D);else Y.set(K,[D,J])}else Y.set(K,J);let M=Object.fromEntries(Y.entries());this.search=new d(M),this.cookies=G}locale(){let Q=b.getStore();if(Q.locale)return Q.locale;let Z=_0(P1);return Z.isLocaleAware?Z.detectLocale(Q.req):Q.locale}ctx(){return b.getStore()}isModelOriginated(){return D1(this.rawRequest)}mcpGrant(){return W1(this.rawRequest)??null}reportProgress(Q){let Z=J1(this.rawRequest);if(!Z)return!1;return Z(Q),!0}get signal(){return this.rawRequest.signal}range(){return s0(this.rawRequest.headers.get("Range"))}refine(Q){return{}}async parseBody(){let Q=K1(this.rawRequest.headers.get("Content-Type"));if(M1(Q))return new d(await this.parseJsonBody());if(Q==="application/x-www-form-urlencoded"||Q==="multipart/form-data"){let Z;try{Z=await this.rawRequest.formData()}catch(X){if(X instanceof q)throw X;throw new q("The request body could not be read as a form.")}let $=new Map;for(let[X,G]of Z.entries())if($.has(X)){let H=$.get(X);if(Array.isArray(H))H.push(G);else $.set(X,[H,G])}else $.set(X,G);return new d(Object.fromEntries($.entries()))}return new d({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let Q;try{Q=await this.rawRequest.text()}catch($){if($ instanceof q)throw $;throw new q("The request body could not be read.")}if(Q.trim()==="")return{};let Z;try{Z=JSON.parse(Q)}catch{throw new q("The request body is not valid JSON.")}if(Z===null||typeof Z!=="object")throw new q("The request body must be a JSON object.");return Z}validateInput(Q){if(X1(this.schema))return this.validateWithSchema(Q);let Z=Q.toJSON()??{},$={},X=Object.entries(this.schema).map(([G,H])=>({key:G,rules:Object.entries(H).map(([Y,M])=>({rule:Y,message:M,check:typeof M==="function"?null:this.ruleFor(G,Y)}))}));for(let{key:G,rules:H}of X)for(let{path:Y,value:M}of GQ(Z,G)){let K=this.checkField(M,H);if(K.length>0){let J=$[B1(Y)]??=[];for(let D of K)if(!J.includes(D))J.push(D)}}if(this.addRefinements($,Z),Object.keys($).length>0)throw new s($);return Q}checkField(Q,Z){let $=Z.some(({rule:H})=>H==="required"),X=Q===void 0||Q===null||Q==="",G=[];for(let{rule:H,message:Y,check:M}of Z){let K=Y,J=!1;if(typeof Y==="function")K=Y(Q),J=typeof K>"u";else J=M(Q);if(J)continue;if(X&&!$)continue;if(H==="required")return[String(K)];if(!G.includes(String(K)))G.push(String(K))}return G}validateWithSchema(Q){let Z=this.schema.validate(Q.toJSON()),$={};if("issues"in Z)for(let G of Z.issues){let H=B1(G.path),Y=$[H]??=[];if(!Y.includes(G.message))Y.push(G.message)}let X="value"in Z?new d(Z.value):Q;if(this.addRefinements($,X.toJSON()),Object.keys($).length>0)throw new s($);return X}addRefinements(Q,Z){for(let[$,X]of Object.entries(this.refine(Z)??{})){let G=Q[$]??[];Q[$]=G.includes(X)?G:[...G,X]}}ruleFor(Q,Z){try{return Q1(Z)}catch($){if($ instanceof k)throw new k(`${this.constructor.name}.schema.${Q}: ${$.message}`);throw $}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let Q=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(Q)}}catch(Z){if(!(Z instanceof s))throw Z;return{isValid:!1,errors:Z.errors,input:Q}}}}var j1="x-gemi-sign-in";class YQ extends q{error;constructor(Q="Not authorized"){super(Q);this.name="AuthorizationError",this.error=Q,this.payload={api:{status:401,data:{error:C0("authorization",this.error,401)}},view:{}}}}class g0 extends q{static apiStatus=403;error;constructor(Q="Insufficient permissions"){super(Q);this.name="InsufficientPermissionsError",this.error=Q,this.payload={api:{status:g0.apiStatus,data:{error:C0("permission",this.error,g0.apiStatus)}},view:{status:403}}}}class y0 extends q{total;constructor(Q){super("Range not satisfiable");this.total=Q;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:L0("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":a0(Q),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class KQ extends q{constructor(Q="Not found"){super(Q);this.name="NotFoundError",this.payload={api:{status:404,data:{error:L0("not_found",Q,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class h extends q{fileName;constructor(Q){super("File not found");this.fileName=Q;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:L0("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class MQ extends q{constructor(Q={}){super("Authentication error");this.name="AuthenticationError";let Z=Q.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:C0("authentication","Authentication error",401)},headers:{[j1]:Z}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Z}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Z}}}}}class X0{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return _0(this.getFacadeAccessor())}}import{Buffer as JQ}from"buffer";function O0(Q){if(typeof Q!=="string"||/^[\s/.]*$/.test(Q))throw Error(`Refusing to delete by prefix ${JSON.stringify(Q)}: it would match the whole store`)}class G0{async putStream({body:Q,...Z},$={}){$.signal?.throwIfAborted();let X=[],G=Q.getReader();try{for(;;){$.signal?.throwIfAborted();let{done:H,value:Y}=await G.read();if(H)break;X.push(Y)}}catch(H){throw await G.cancel(H).catch(()=>{}),H}return this.put({...Z,body:JQ.concat(X)},$)}async*objects(Q,Z={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(Q,Z={}){O0(Q);let $=[];for await(let X of this.objects(Q,Z))$.push(X.name);for(let X of $)Z.signal?.throwIfAborted(),await this.delete({name:X,bucket:Z.bucket});return $.length}async delete(Q){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,$=await this.fetch({name:Z.name,bucket:Z.bucket});if(!$.ok)throw new h(Z.name);let X=$.headers.get("Content-Type")??"application/octet-stream",G=$.headers.get("ETag")??void 0,H=$.headers.get("Last-Modified"),Y=H?new Date(H):void 0;if(Z.range){let J=await $.blob();return{body:J,start:0,end:J.size-1,total:J.size,partial:!1,type:X,etag:G,lastModified:Y,name:Z.name}}let M=Number($.headers.get("Content-Length")),K=Number.isFinite(M)?M:0;return{body:$.body,start:0,end:K-1,total:K,partial:!1,type:X,etag:G,lastModified:Y,name:Z.name}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=typeof Q==="string"?void 0:Q.bucket,X=await this.fetch({name:Z,bucket:$});if(!X.ok)throw new h(Z);let G=Number(X.headers.get("Content-Length"));if(Number.isFinite(G))return await X.body?.cancel(),G;return(await X.blob()).size}}function R1(Q,Z){if(!Z)return Q;let $=Q.getReader(),X=!1,G,H=()=>{if(X=!0,G)Z.removeEventListener("abort",G)};return new ReadableStream({start(Y){if(G=()=>{if(X)return;H(),Y.error(Z.reason),$.cancel(Z.reason).catch(()=>{})},Z.aborted)G();else Z.addEventListener("abort",G,{once:!0})},async pull(Y){let M;try{M=await $.read()}catch(K){if(X)return;H(),Y.error(K);return}if(X)return;if(M.done){H(),Y.close();return}Y.enqueue(M.value)},cancel(Y){return H(),$.cancel(Y)}},{highWaterMark:0})}import{mkdir as WQ,open as DQ,readdir as b0,rename as UQ,rmdir as zQ,stat as VQ,unlink as _1}from"fs/promises";import{dirname as BQ,isAbsolute as f0,relative as H0,resolve as i,sep as f}from"path";class v0 extends G0{configured;constructor(Q){super();this.configured=Q}get folderPath(){return this.configured??`${Y0()}/storage`}async put(Q,{signal:Z}={}){Z?.throwIfAborted();let $,X;if(Q instanceof Blob)$=Q,X=`${Bun.randomUUIDv7()}.${Q.type.split("/")[1].split(";")[0]}`;else $=Q.body,X=Q.name;let G=$ instanceof Buffer?$:$ instanceof Blob||$ instanceof File?Buffer.from(await $.arrayBuffer()):"",H=`${this.folderPath}/${X}`;return Z?.throwIfAborted(),await Bun.write(H,G),X}async putStream({name:Q,body:Z},{signal:$}={}){let X=Z.getReader(),G=null;try{if($?.throwIfAborted(),!Q)throw Error("Object name has to be specified");let H=i(this.folderPath),Y=i(H,Q),M=H0(H,Y);if(!M||M===".."||M.startsWith(`..${f}`)||f0(M))throw Error(`Refusing to write "${Q}": it is outside the storage folder`);await WQ(BQ(Y),{recursive:!0}),G=`${Y}.${Bun.randomUUIDv7()}.partial`;let K=await DQ(G,"wx");try{for(;;){$?.throwIfAborted();let{done:J,value:D}=await X.read();if(J)break;for(let U=0;U<D.byteLength;){let{bytesWritten:O}=await K.write(D,U);U+=O}}}finally{await K.close()}return $?.throwIfAborted(),await UQ(G,Y),Q}catch(H){if(await X.cancel(H).catch(()=>{}),G)await _1(G).catch(()=>{});throw H}}async fetch(Q,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,X;if(typeof Q==="string")X=Q;else $=Q.bucket??$,X=Q.name;if(!X)throw Error("Object name has to be specified");let G=`${this.folderPath}/${X}`,H=Bun.file(G),Y=R1(Bun.file(G).stream(),Z),M=new Date(H.lastModified).toUTCString();return new Response(Y,{headers:{"Content-Type":H.type,"Content-Length":String(H.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":M}})}async read(Q){let Z=typeof Q==="string"?{name:Q}:Q,{name:$,range:X=null}=Z;if(!$)throw Error("Object name has to be specified");let G=Bun.file(`${this.folderPath}/${$}`);if(!await G.exists())throw new h($);let H=G.size,Y=X?r0(X,H):null;if(X&&!Y)throw new y0(H);let M=Y?.start??0,K=Y?Y.end:H-1;return{body:Y?G.slice(M,K+1):G,start:M,end:K,total:H,partial:Boolean(Y),type:G.type||"application/octet-stream",lastModified:new Date(G.lastModified),name:$}}async size(Q){let Z=typeof Q==="string"?Q:Q.name,$=Bun.file(`${this.folderPath}/${Z}`);if(!await $.exists())throw new h(Z);return $.size}async delete(Q){let Z=typeof Q==="string"?Q:Q.name;if(!Z)throw Error("Object name has to be specified");let $=i(this.folderPath),X=i($,Z),G=H0($,X);if(!G||G===".."||G.startsWith(`..${f}`)||f0(G))throw Error(`Refusing to delete "${Z}": it is outside the storage folder`);try{await _1(X)}catch(H){if(H?.code==="ENOENT")return;throw H}}resolvePrefix(Q){let Z=i(this.folderPath),$=Q.lastIndexOf("/"),X=$===-1?"":Q.slice(0,$),G=$===-1?Q:Q.slice($+1),H=i(Z,X),Y=H0(Z,H);if(Y===".."||Y.startsWith(`..${f}`)||f0(Y))throw Error(`Refusing to list "${Q}": it is outside the storage folder`);let M=Y.split(f).join("/");return{root:Z,dir:H,match:M?`${M}/${G}`:G}}async*objects(Q,{signal:Z}={}){Z?.throwIfAborted();let{root:$,dir:X,match:G}=this.resolvePrefix(Q),H=[],Y=async(M)=>{let K;try{K=await b0(M,{withFileTypes:!0})}catch(J){if(J?.code==="ENOENT"||J?.code==="ENOTDIR")return;throw J}for(let J of K){let D=`${M}${f}${J.name}`,U=H0($,D).split(f).join("/");if(J.isDirectory()){if(`${U}/`.startsWith(G)||G.startsWith(`${U}/`))await Y(D)}else if(J.isFile()&&U.startsWith(G))H.push(U)}};await Y(X),H.sort();for(let M of H){Z?.throwIfAborted();let K;try{K=await VQ(`${$}/${M}`)}catch(J){if(J?.code==="ENOENT")continue;throw J}yield{name:M,size:K.size,lastModified:K.mtime}}}async deletePrefix(Q,Z={}){O0(Q);let{root:$,match:X}=this.resolvePrefix(Q);O0(X);let G=await super.deletePrefix(Q,Z);if(G>0)await this.pruneEmptyDirs($,X);return G}async pruneEmptyDirs(Q,Z){let $=[],X=async(G)=>{let H;try{H=await b0(G,{withFileTypes:!0})}catch{return}for(let Y of H){if(!Y.isDirectory())continue;let M=`${G}${f}${Y.name}`,K=H0(Q,M).split(f).join("/");if(`${K}/`.startsWith(Z)||Z.startsWith(`${K}/`)){if(await X(M),`${K}/`.startsWith(Z))$.push(M)}}};await X(Q);for(let G of $)try{await zQ(G)}catch{}}async list(){return await b0(this.folderPath)}}function U8(Q){return Q}function L1(){return{driver:new v0}}class h0{static token="filesystem";driver;constructor(Q={}){this.driver=Q.driver??L1().driver}}class N extends Error{code="safe-fetch";url;constructor(Q,Z,$){super(Q,$);this.name=new.target.name,this.url=Z}}class m extends N{reason;code="invalid-url";constructor(Q,Z,$){super($,Q);this.reason=Z}}class F0 extends N{host;reason;code="blocked-host";constructor(Q,Z,$){super($==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,Q);this.host=Z;this.reason=$}}class n extends N{host;address;range;code="blocked-address";constructor(Q,Z,$,X){super(Z===$?`${$} is not a public address (${X}).`:`${Z} resolves to ${$}, which is not a public address (${X}).`,Q);this.host=Z;this.address=$;this.range=X}}class I0 extends N{host;code="dns";constructor(Q,Z,$){super(`Couldn't resolve ${Z}.`,Q,{cause:$});this.host=Z}}class A0 extends N{phase;ms;code="timeout";constructor(Q,Z,$){super(Z==="connect"?`Couldn't connect within ${$} ms.`:`The request didn't finish within ${$} ms.`,Q);this.phase=Z;this.ms=$}}class T0 extends N{limit;code="too-large";constructor(Q,Z){super(`The response is larger than ${Z} bytes.`,Q);this.limit=Z}}class K0 extends N{contentType;allowed;code="content-type";constructor(Q,Z,$){super(`The response is ${Z??"of no content type"}, not ${$.join(" or ")}.`,Q);this.contentType=Z;this.allowed=$}}class m0 extends N{limit;code="too-many-redirects";constructor(Q,Z){super(`More than ${Z} redirects.`,Q);this.limit=Z}}class l extends N{code="network";constructor(Q,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,Q,{cause:Z})}}class c0 extends N{status;code="http-status";constructor(Q,Z){super(`The server answered ${Z}.`,Q);this.status=Z}}function PQ(Q){if(Q==="")return null;let Z=Q.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let $=[];for(let H of Z){let Y=jQ(H);if(Y===null)return null;$.push(Y)}let X=$.pop();for(let H of $)if(H>255)return null;if(X>=256**(4-$.length))return null;let G=X;return $.forEach((H,Y)=>{G+=H*256**(3-Y)}),new Uint8Array([Math.floor(G/16777216)&255,Math.floor(G/65536)&255,Math.floor(G/256)&255,G&255])}function jQ(Q){if(Q==="")return null;let Z=Q,$=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),$=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),$=8;if(!($===16?/^[0-9a-f]+$/i:$===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let G=parseInt(Z,$);return Number.isSafeInteger(G)?G:null}function C1(Q){let Z=Q;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let $=Z.indexOf("%");if($!==-1)Z=Z.slice(0,$);if(!Z.includes(":"))return null;let X=Z.split("::");if(X.length>2)return null;let G=(J,D)=>{if(J==="")return[];let U=[],O=J.split(":");for(let B=0;B<O.length;B++){let _=O[B];if(D&&B===O.length-1&&_.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(_))return null;let W=_.split(".").map(Number);if(W.some((V)=>V>255))return null;U.push(W[0]<<8|W[1],W[2]<<8|W[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(_))return null;U.push(parseInt(_,16))}return U},H=G(X[0],X.length===1),Y=X.length===2?G(X[1],!0):[];if(!H||!Y)return null;let M;if(X.length===2){let J=8-H.length-Y.length;if(J<1)return null;M=[...H,...Array.from({length:J},()=>0),...Y]}else M=H;if(M.length!==8)return null;let K=new Uint8Array(16);return M.forEach((J,D)=>{K[D*2]=J>>8,K[D*2+1]=J&255}),K}function M0(Q){let Z=C1(Q);if(Z)return{family:6,bytes:Z};let $=PQ(Q);if($)return{family:4,bytes:$};return null}function c(Q){if(Q.family===6&&RQ(Q.bytes))return{family:4,bytes:Q.bytes.slice(12)};return Q}function RQ(Q){for(let Z=0;Z<10;Z++)if(Q[Z]!==0)return!1;return Q[10]===255&&Q[11]===255}function J0(Q){if(Q.family===4)return Array.from(Q.bytes).join(".");let Z=[];for(let $=0;$<16;$+=2)Z.push((Q.bytes[$]<<8|Q.bytes[$+1]).toString(16));return Z.join(":")}function o(Q){let Z=Q.lastIndexOf("/"),$=Z===-1?Q:Q.slice(0,Z),X=/^[0-9.]+$/.test($)?_Q($):C1($);if(!X)return null;let G=c(X.length===4?{family:4,bytes:X}:{family:6,bytes:X}),H=G.family===4?32:128,Y=H;if(Z!==-1){let M=Q.slice(Z+1);if(!/^\d{1,3}$/.test(M))return null;if(Y=Number(M),X.length===16&&G.family===4)Y-=96;if(Y<0||Y>H)return null}return{family:G.family,bytes:G.bytes,prefix:Y}}function _Q(Q){return/^\d{1,3}(\.\d{1,3}){3}$/.test(Q)&&Q.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array(Q.split(".").map(Number)):null}function g(Q,Z){let $=c(Q);if($.family!==Z.family)return!1;let X=Z.prefix;for(let G=0;X>0;G++){let H=Math.min(8,X),Y=255<<8-H&255;if(($.bytes[G]&Y)!==(Z.bytes[G]&Y))return!1;X-=H}return!0}var L=(Q,Z)=>({cidr:o(Q),kind:Z,text:Q}),LQ=[L("0.0.0.0/8","unspecified"),L("10.0.0.0/8","private"),L("100.64.0.0/10","shared"),L("127.0.0.0/8","loopback"),L("169.254.169.254/32","metadata"),L("169.254.0.0/16","link-local"),L("168.63.129.16/32","metadata"),L("172.16.0.0/12","private"),L("192.0.0.0/24","reserved"),L("192.0.2.0/24","documentation"),L("192.88.99.0/24","reserved"),L("192.168.0.0/16","private"),L("198.18.0.0/15","benchmarking"),L("198.51.100.0/24","documentation"),L("203.0.113.0/24","documentation"),L("224.0.0.0/4","multicast"),L("255.255.255.255/32","broadcast"),L("240.0.0.0/4","reserved")],CQ=[L("::/128","unspecified"),L("::1/128","loopback"),L("64:ff9b:1::/48","private"),L("::/8","reserved"),L("100::/64","reserved"),L("2001:db8::/32","documentation"),L("2001::/23","reserved"),L("3fff::/20","documentation"),L("fd00:ec2::254/128","metadata"),L("fc00::/7","unique-local"),L("fe80::/10","link-local"),L("fec0::/10","private"),L("ff00::/8","multicast")],OQ=o("64:ff9b::/96"),FQ=o("2002::/16"),IQ=o("2000::/3");function q0(Q){let Z=typeof Q==="string"?M0(Q):Q;if(!Z)return{kind:"reserved",range:"not an IP address"};let $=c(Z);if($.family===4){let G=LQ.find((H)=>g($,H.cidr));return G?{kind:G.kind,range:G.text}:null}if(g($,OQ))return q0({family:4,bytes:$.bytes.slice(12)});if(g($,FQ))return q0({family:4,bytes:$.bytes.slice(2,6)});let X=CQ.find((G)=>g($,G.cidr));if(X)return{kind:X.kind,range:X.text};return g($,IQ)?null:{kind:"reserved",range:"outside 2000::/3"}}function O1(Q,Z){let $=c(Q),X=c(Z);return $.family===X.family&&$.bytes.every((G,H)=>G===X.bytes[H])}import{lookup as AQ}from"dns/promises";import*as TQ from"http";import*as qQ from"https";import*as t from"zlib";class p0 extends Response{#Q;#Z;address;constructor(Q,Z,$){super(Q,Z);this.#Q=$.url,this.#Z=$.redirected,this.address=$.address}get url(){return this.#Q}get redirected(){return this.#Z}}var W0={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},NQ=new Set([301,302,303,307,308]),wQ=new Set([101,103,204,205,304]),EQ=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],SQ=["authorization","cookie","proxy-authorization"];async function A1(Q,Z={}){let $=xQ(Z),X=Z.signal;X?.throwIfAborted();let G=new AbortController,H=G.signal,Y=String(Q),M=(U)=>{if(!H.aborted)G.abort(U)},K=setTimeout(()=>M(new A0(Y,"total",$.timeout)),$.timeout),J=()=>M(X.reason);X?.addEventListener("abort",J,{once:!0});let D=()=>{clearTimeout(K),X?.removeEventListener("abort",J)};try{let U=I1(Y,$),O=(Z.method??"GET").toUpperCase(),B=new Headers(Z.headers);for(let W of EQ)B.delete(W);if(!B.has("accept"))B.set("accept","*/*");if(!B.has("user-agent"))B.set("user-agent","gemi");if(!B.has("accept-encoding"))B.set("accept-encoding","gzip, deflate, br");let _=await bQ(O,Z.body,B);for(let W=0;;W++){Y=U.href;let{request:V,response:z,address:P}=await fQ(U,O,B,_,$,H),F=z.statusCode??0,I=z.headers.location;if(NQ.has(F)&&I&&Z.redirect!=="manual"){if(V.destroy(),W>=$.maxRedirects)throw new m0(U.href,$.maxRedirects);let A;try{A=new URL(I,U)}catch{throw new m(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(F===303?O!=="HEAD":(F===301||F===302)&&O==="POST"){O="GET",_=null;let C=[];B.forEach((R,j)=>{if(j.startsWith("content-"))C.push(j)});for(let R of C)B.delete(R)}if(A.origin!==U.origin)for(let C of SQ)B.delete(C);U=I1(A.href,$);continue}return vQ({url:U,hop:W,method:O,request:V,response:z,address:P,policy:$,signal:H,release:D})}}catch(U){throw D(),H.aborted?H.reason:U}}function xQ(Q){let Z=(X,G)=>{let H={hosts:[],ranges:[]};for(let Y of X){let M=Y.includes("/")||Y.includes(":")||/^[\d.]+$/.test(Y),K=M?o(Y):null;if(K)H.ranges.push(K);else if(!M&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(Y))H.hosts.push(T1(Y));else throw TypeError(`safeFetch: "${Y}" in ${G} is not a host name or an IP range.`)}return H},$=Q.allowPrivate;return{timeout:Q.timeout??W0.timeout,connectTimeout:Q.connectTimeout??W0.connectTimeout,maxSize:Q.maxSize??W0.maxSize,maxRedirects:Q.maxRedirects??W0.maxRedirects,ports:Q.ports??W0.ports,allow:Q.allow&&Q.allow.length>0?Z(Q.allow,"allow"):null,deny:Z(Q.deny??[],"deny"),allowPrivate:$===!0?!0:Z($||[],"allowPrivate").ranges,contentTypes:Q.contentTypes?.length?Q.contentTypes:null,resolve:Q.resolve??kQ}}async function kQ(Q){return(await AQ(Q,{all:!0,verbatim:!0})).map(($)=>$.address)}function T1(Q){return Q.toLowerCase().replace(/\.$/,"")}function F1(Q,Z){return Z.some(($)=>$.startsWith("*.")?Q.endsWith($.slice(1)):Q===$)}function I1(Q,Z){let $;try{$=new URL(Q)}catch{throw new m(Q,"malformed",`"${Q}" is not a URL.`)}if($.protocol!=="http:"&&$.protocol!=="https:")throw new m($.href,"scheme",`Only http and https URLs can be fetched, not ${$.protocol.slice(0,-1)}.`);if($.username||$.password)throw new m($.href,"credentials","The URL has a username or password in it.");let X=q1($);if(Z.ports!=="any"&&!Z.ports.includes(X))throw new m($.href,"port",`Port ${X} is not allowed.`);return $}function q1(Q){return Q.port?Number(Q.port):Q.protocol==="https:"?443:80}async function gQ(Q,Z,$){let X=T1(Q.hostname.replace(/^\[(.*)\]$/,"$1")),G=M0(X),H=G!==null&&(X.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(X));if(!H&&F1(X,Z.deny.hosts))throw new F0(Q.href,X,"denied");let Y=!H&&Z.allow!==null&&F1(X,Z.allow.hosts);if(Z.allow&&!Y&&Z.allow.ranges.length===0)throw new F0(Q.href,X,"not-allowed");let M;if(H)M=[G];else{let K;try{K=await yQ(Z.resolve(X),$)}catch(J){if($.aborted)throw $.reason;throw new I0(Q.href,X,J)}if(M=K.map((J)=>M0(J)).filter((J)=>J!==null),M.length===0)throw new I0(Q.href,X)}for(let K of M){let J=J0(K);if(Z.deny.ranges.some((U)=>g(K,U)))throw new n(Q.href,X,J,"denied");if(Z.allow&&!Y&&!Z.allow.ranges.some((U)=>g(K,U)))throw new n(Q.href,X,J,"not-allowed");let D=q0(K);if(D&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((U)=>g(K,U)))throw new n(Q.href,X,J,D.kind)}return{host:X,addresses:M,isLiteral:H}}function yQ(Q,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise(($,X)=>{let G=()=>X(Z.reason);Z.addEventListener("abort",G,{once:!0}),Q.then((H)=>{Z.removeEventListener("abort",G),$(H)},(H)=>{Z.removeEventListener("abort",G),X(H)})})}async function bQ(Q,Z,$){if(Z===void 0||Z===null)return null;if(Q==="GET"||Q==="HEAD")throw TypeError(`safeFetch: a ${Q} request can't have a body.`);let X=new Request("http://body.invalid/",{method:"POST",body:Z}),G=X.headers.get("content-type");if(G&&!$.has("content-type"))$.set("content-type",G);return new Uint8Array(await X.arrayBuffer())}async function fQ(Q,Z,$,X,G,H){let Y=new AbortController,M=setTimeout(()=>Y.abort(new A0(Q.href,"connect",G.connectTimeout)),G.connectTimeout),K=AbortSignal.any([H,Y.signal]);try{let{host:J,addresses:D,isLiteral:U}=await gQ(Q,G,K),O=Q.protocol==="https:",B={};if($.forEach((_,W)=>{B[W]=_}),X)B["content-length"]=String(X.byteLength);return await new Promise((_,W)=>{let V={method:Z,host:J,port:q1(Q),path:`${Q.pathname}${Q.search}`,headers:B,agent:!1,lookup:(C,R,j)=>{let w=R?.family,T=D.filter((D0)=>!w||D0.family===w);if(T.length===0)j(Object.assign(Error(`No IPv${w} address for ${J}`),{code:"ENOTFOUND"}));else if(R?.all)j(null,T.map((D0)=>({address:J0(D0),family:D0.family})));else j(null,J0(T[0]),T[0].family)}};if(O&&!U)V.servername=J;let z=(O?qQ:TQ).request(V),P=null,F=(C)=>{K.removeEventListener("abort",I),z.destroy(),W(C)},I=()=>F(K.aborted?K.reason:H.reason);K.addEventListener("abort",I,{once:!0});let A=(C)=>{let R=C?.remoteAddress;if(!R||P!==null)return!0;let j=M0(R);if(!j||!D.some((w)=>O1(w,j)))return F(new n(Q.href,J,R,"not-allowed")),!1;return P=J0(c(j)),!0};z.once("socket",(C)=>{let R=()=>{if(A(C)&&!O)clearTimeout(M)};if(C.connecting)C.once("connect",R);else R();if(O)C.once("secureConnect",()=>clearTimeout(M))}),z.once("response",(C)=>{if(clearTimeout(M),C.on("error",()=>{}),!A(C.socket))return;K.removeEventListener("abort",I),_({request:z,response:C,address:P})}),z.on("error",(C)=>{if(K.aborted)return F(K.reason);F(C instanceof N?C:new l(Q.href,C))}),z.end(X??void 0)})}finally{clearTimeout(M)}}function vQ({url:Q,hop:Z,method:$,request:X,response:G,address:H,policy:Y,signal:M,release:K}){let J=G.statusCode??0;if(J<200||J>599)throw X.destroy(),new l(Q.href,Error(`Unexpected status ${J}`));let D=new Headers,U=G.rawHeaders;for(let R=0;R<U.length;R+=2)D.append(U[R],U[R+1]);if(Y.contentTypes){let R=D.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!R||!Y.contentTypes.some((j)=>hQ(R,j)))throw X.destroy(),new K0(Q.href,R,Y.contentTypes)}let O={url:Q.href,redirected:Z>0,address:H},B={status:J,statusText:G.statusMessage??"",headers:D};if($==="HEAD"||wQ.has(J))return X.destroy(),K(),new p0(null,B,O);let _=D.get("content-encoding")?.trim().toLowerCase(),W=_==="gzip"||_==="x-gzip"?t.createGunzip():_==="deflate"?t.createInflate():_==="br"?t.createBrotliDecompress():null,V=Number(D.get("content-length"));if(!W&&Number.isFinite(V)&&V>Y.maxSize)throw X.destroy(),new T0(Q.href,Y.maxSize);if(W)D.delete("content-encoding"),D.delete("content-length");let z=W?G.pipe(W):G,P=0,F=!1,I=()=>{},A=()=>{F=!0,M.removeEventListener("abort",I),K()},C=new ReadableStream({start(R){let j=(T)=>{if(F)return;if(A(),T===void 0)R.close();else X.destroy(),W?.destroy(),R.error(T)};if(I=()=>j(M.reason),M.addEventListener("abort",I,{once:!0}),M.aborted)return I();z.on("data",(T)=>{if(F)return;if(P+=T.byteLength,P>Y.maxSize)return j(new T0(Q.href,Y.maxSize));if(R.enqueue(new Uint8Array(T)),(R.desiredSize??1)<=0)z.pause()}),z.once("end",()=>j());let w=(T)=>j(T instanceof N?T:new l(Q.href,T));if(z.on("error",w),W)G.on("error",w);G.once("aborted",()=>j(new l(Q.href,Error("The response was cut off."))))},pull(){z.resume()},cancel(){if(F)return;A(),X.destroy(),W?.destroy()}});return new p0(C,B,O)}function hQ(Q,Z){let $=Z.toLowerCase();return $.endsWith("/*")?Q.startsWith($.slice(0,-1)):Q===$}function w1(Q){return pQ(Q)??dQ(Q)??iQ(Q)}var u0=4096,mQ={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/heic":"heic","image/heif":"heif","image/bmp":"bmp","image/tiff":"tiff","image/x-icon":"ico","image/svg+xml":"svg","audio/mpeg":"mp3","audio/aac":"aac","audio/mp4":"m4a","audio/ogg":"ogg","audio/flac":"flac","audio/wav":"wav","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm","video/x-matroska":"mkv","video/x-msvideo":"avi","font/woff":"woff","font/woff2":"woff2","font/ttf":"ttf","font/otf":"otf","application/pdf":"pdf","application/zip":"zip","application/gzip":"gz","application/xml":"xml","text/html":"html","text/plain":"txt","application/octet-stream":"bin"};function E1(Q){return mQ[Q]??"bin"}function S(Q,Z,$=0){if(Q.length<$+Z.length)return!1;return Z.every((X,G)=>Q[$+G]===X)}function y(Q,Z,$){return String.fromCharCode(...Q.subarray(Z,$))}var cQ={avif:"image/avif",avis:"image/avif",heic:"image/heic",heix:"image/heic",hevc:"image/heic",hevx:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif","qt ":"video/quicktime","M4A ":"audio/mp4","M4B ":"audio/mp4"};function pQ(Q){if(S(Q,[137,80,78,71,13,10,26,10]))return"image/png";if(S(Q,[255,216,255]))return"image/jpeg";if(Q.length>=6&&(y(Q,0,6)==="GIF87a"||y(Q,0,6)==="GIF89a"))return"image/gif";if(Q.length>=12&&y(Q,0,4)==="RIFF"){let Z=y(Q,8,12);if(Z==="WEBP")return"image/webp";if(Z==="WAVE")return"audio/wav";if(Z==="AVI ")return"video/x-msvideo"}if(Q.length>=12&&y(Q,4,8)==="ftyp"){let Z=y(Q,8,12);return cQ[Z]??"video/mp4"}if(S(Q,[73,73,42,0])||S(Q,[77,77,0,42]))return"image/tiff";if(S(Q,[66,77])&&S(Q,[0,0,0,0],6))return"image/bmp";if(S(Q,[0,0,1,0])&&Q.length>=6&&Q[4]>0)return"image/x-icon";if(S(Q,[37,80,68,70,45]))return"application/pdf";if(S(Q,[80,75,3,4]))return"application/zip";if(S(Q,[31,139]))return"application/gzip";if(S(Q,[26,69,223,163]))return y(Q,0,Math.min(Q.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(Q.length>=4){let Z=y(Q,0,4);if(Z==="OggS")return"audio/ogg";if(Z==="fLaC")return"audio/flac";if(Z==="wOFF")return"font/woff";if(Z==="wOF2")return"font/woff2";if(Z==="OTTO")return"font/otf"}if(S(Q,[0,1,0,0,0]))return"font/ttf";if(Q.length>=3&&y(Q,0,3)==="ID3")return"audio/mpeg";if(Q.length>=2&&Q[0]===255){if((Q[1]&246)===240)return"audio/aac";if((Q[1]&224)===224&&(Q[1]&6)!==0)return"audio/mpeg"}return null}var uQ=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function dQ(Q){let Z=new TextDecoder("utf-8",{fatal:!1}).decode(Q);if(Z.charCodeAt(0)===65279)Z=Z.slice(1);if(Z=Z.trimStart(),!Z.startsWith("<"))return null;let $=Z.toLowerCase(),X=$;for(;;){X=X.trimStart();let G=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(X);if(!G)break;X=X.slice(G[0].length)}if(/^<svg[\s>/]/.test(X))return"image/svg+xml";for(let G of uQ){if(!$.startsWith(`<${G}`))continue;if(/^[\s>]/.test($.charAt(G.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(X))return"text/html";if($.startsWith("<?xml"))return"application/xml";return null}function iQ(Q){if(Q.length===0)return"application/octet-stream";for(let Z of Q)if(Z<32&&Z!==9&&Z!==10&&Z!==12&&Z!==13&&Z!==27)return"application/octet-stream";try{return new TextDecoder("utf-8",{fatal:!0}).decode(Q,{stream:!0}),"text/plain"}catch{return"application/octet-stream"}}var nQ=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function N1(Q){let Z=Q.split(";")[0].trim().toLowerCase();return nQ.has(Z)||Z.endsWith("+xml")}function S1(Q,Z){let $=Q.split(";")[0].trim().toLowerCase();return Z.some((X)=>{let G=X.split(";")[0].trim().toLowerCase();if(G==="*/*"||G==="*")return!N1($);if(G.endsWith("/*"))return $.startsWith(G.slice(0,-1))&&!N1($);return $===G})}import{Buffer as tQ}from"buffer";async function x1(Q){try{return(await import("sharp")).default}catch(Z){throw Error(`${Q} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Z})}}async function k1(Q,Z,$={}){let{name:X,directory:G,bucket:H,maxSize:Y,timeout:M,contentTypes:K,signal:J}=$;if(X!==void 0&&G!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(X!==void 0&&!X)throw TypeError("Storage.putFromUrl(): `name` is empty.");let D=await A1(Z,{...$.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:J,timeout:M,maxSize:Y});if(!D.ok)throw await D.body?.cancel().catch(()=>{}),new c0(D.url,D.status);let U=(D.body??new Response(new Uint8Array).body).getReader(),O=async(j)=>{throw await U.cancel(j).catch(()=>{}),j},B=[],_=0,W=!1;while(_<u0){let{done:j,value:w}=await U.read();if(j){W=!0;break}B.push(w),_+=w.byteLength}let V=oQ(B,_),z=w1(V.subarray(0,Math.min(_,u0))),P=K?.length?K:["*/*"];if(!S1(z,P))await O(new K0(D.url,z,P));let F=X??[(G??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${E1(z)}`].filter(Boolean).join("/"),I=_,A=new ReadableStream({start(j){if(_>0)j.enqueue(V);if(W)j.close()},async pull(j){let{done:w,value:T}=await U.read();if(w){j.close();return}I+=T.byteLength,j.enqueue(T)},cancel(j){return U.cancel(j)}}),C={name:F,bucket:H,body:A,contentType:z},R;try{R=Q.putStream?await Q.putStream(C,{signal:J}):await G0.prototype.putStream.call(Q,C,{signal:J})}catch(j){throw await O(j),j}return{name:R,contentType:z,size:I,url:D.url}}function oQ(Q,Z){if(Q.length===1)return Q[0];let $=new Uint8Array(Z),X=0;for(let G of Q)$.set(G,X),X+=G.byteLength;return $}class sQ extends X0{static getFacadeAccessor(){return h0}static async put(Q,Z={}){return this.getFacadeRoot().driver.put(Q,Z)}static async putFromUrl(Q,Z={}){return k1(this.getFacadeRoot().driver,Q,Z)}static async metadata(Q){let Z=tQ.from(await Q.arrayBuffer()),$=await x1("Storage.metadata()");try{return await $(Z).metadata()}catch{return{}}}static async fetch(Q,Z={}){return Z.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(Q,Z)}static async read(Q,Z={}){let $=typeof Q==="string"?{name:Q}:{...Q},X="range"in Z?Z.range??null:$.range!==void 0?$.range:b.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...$,range:X})}static list(Q){return this.getFacadeRoot().driver.list(Q)}static objects(Q,Z={}){return this.getFacadeRoot().driver.objects(Q,Z)}static async deletePrefix(Q,Z={}){return this.getFacadeRoot().driver.deletePrefix(Q,Z)}static async delete(Q){return this.getFacadeRoot().driver.delete(Q)}}import{mkdir as i0,readdir as QZ,access as ZZ}from"fs/promises";var d0=["debug","info","notice","warning","error","critical","alert","emergency"],rQ=d0.indexOf("warning");function y1(Q){if(!Q)return-1;if(Q===!0)return 0;let Z=d0.indexOf(Q);return Z===-1?0:Z}function aQ(){let Q=new WeakSet;return function(Z,$){if(typeof $==="bigint")return $.toString();if($ instanceof Error){let X={name:$.name,message:$.message,stack:$.stack};for(let G of Object.keys($))X[G]=$[G];if($.cause!==void 0)X.cause=$.cause;return X}if($!==null&&typeof $==="object"){if(Q.has($))return"[Circular]";Q.add($)}return $}}function g1(Q){try{return JSON.stringify(Q,aQ())}catch{return'"[Unserializable]"'}}function eQ(Q,Z){if(Z==="json")return g1({...Q.metadata,timestamp:Q.timestamp,level:Q.level,message:Q.message});let $=Object.keys(Q.metadata).length>0;return`${Q.timestamp} ${Q.level.toUpperCase()} ${Q.message}${$?` ${g1(Q.metadata)}`:""}`}function b1(Q,Z){let $=d0.indexOf(Q.level);if(Z.threshold===-1||$<Z.threshold)return;try{let X=eQ(Q,Z.format)+`
|
|
5
|
+
`;if($>=rQ)process.stderr.write(X);else process.stdout.write(X)}catch{}}async function n0(Q){try{return await ZZ(Q),!0}catch{return!1}}class l0{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${Y0()}/storage/logs`}consoleThreshold;constructor(Q){this.config=Q;this.consoleThreshold=y1(Q.console)}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((Q)=>{console.error("Log storage unavailable, file logging disabled",Q)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let Q=`${Y0()}/storage`;if(!await n0(Q))await i0(Q);if(!await n0(this.logsDirPath))await i0(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await n0(this.logsDirPath))await i0(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let $=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed($),this.fileSize=0,this.writerSize=0}let Z=(await QZ(this.logsDirPath)).sort().reverse()[0];if(Z){let $=Bun.file(`${this.logsDirPath}/${Z}`);if($.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Z}`,this.writer=$.writer(),this.writer.write(await $.text()),this.writer.write(`
|
|
6
|
+
`),this.writer.flush(),this.fileSize=$.size}if(!this.writer){let $=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${$}`;let X=Bun.file(`${this.logsDirPath}/${$}`);this.writer=X.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(Q,Z,$={}){if(!this.isReady)await this.boot();let X=b.getStore(),G={},H={};if(X)H={method:X.req.rawRequest.method,path:new URL(X.req.rawRequest.url).pathname},G={url:X.req.rawRequest.url,method:X.req.rawRequest.method,headers:X.req.rawRequest.headers,body:X.req.rawRequest.body};let Y={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:Q,message:Z,metadata:{...G,...$}};if(this.consoleThreshold!==-1)b1({timestamp:Y.timestamp,level:Q,message:Z,metadata:{...H,...$}},{threshold:this.consoleThreshold,format:this.config.consoleFormat});let M="";try{M=JSON.stringify(Y)}catch(K){console.log("Error parsing log object",K)}try{let K=this.config.onLogCreated(Y);if(K instanceof Promise)K.catch((J)=>console.error("Error in onLogCreated",J))}catch(K){console.error("Error in onLogCreated",K)}if(!this.writer)return;this.writerSize+=M.length,this.fileSize+=M.length;try{this.writer.write(M),this.writer.write(`
|
|
7
|
+
`),this.tryFlush()}catch(K){console.error("Error writing log",K)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class $Z extends X0{static getFacadeAccessor(){return l0}static debug(Q,Z){this.getFacadeRoot().log("debug",Q,Z)}static info(Q,Z){this.getFacadeRoot().log("info",Q,Z)}static notice(Q,Z){this.getFacadeRoot().log("notice",Q,Z)}static warning(Q,Z){this.getFacadeRoot().log("warning",Q,Z)}static error(Q,Z){this.getFacadeRoot().log("error",Q,Z)}static critical(Q,Z){this.getFacadeRoot().log("critical",Q,Z)}static alert(Q,Z){this.getFacadeRoot().log("alert",Q,Z)}static emergency(Q,Z){this.getFacadeRoot().log("emergency",Q,Z)}}class XZ{config;static token="redis";instance=null;connectingSince=null;downSince=null;replaceDelay=500;constructor(Q={}){this.config=Q}get client(){if(this.instance===null)return this.build();let Q=this.instance;if(this.isDown(Q,Date.now())){this.instance=null;try{Q.close()}catch{}return this.build()}return Q}set client(Q){this.instance=Q,this.connectingSince=null,this.downSince=null,this.replaceDelay=500}close(){let Q=this.instance;this.instance=null,this.connectingSince=null,this.downSince=null,this.replaceDelay=500,Q?.close()}build(){let Q=new(GZ())(this.config.url,this.config.options);if(this.instance=Q,this.downSince=null,this.connectingSince=null,typeof Q.connect==="function"){this.connectingSince=Date.now();let Z;try{Z=Promise.resolve(Q.connect())}catch($){Z=Promise.reject($)}Z.then(()=>{if(this.instance!==Q)return;this.connectingSince=null,this.replaceDelay=500},()=>{if(this.instance!==Q)return;this.connectingSince=null})}return Q}isDown(Q,Z){if(Q.connected!==!1||typeof Q.connect!=="function")return this.downSince=null,!1;if(this.connectingSince!==null){let $=(this.config.options?.connectionTimeout??1e4)+5000;if(Z-this.connectingSince<$)return!1;this.connectingSince=null}if(this.downSince??=Z,Z-this.downSince<this.replaceDelay)return!1;return this.replaceDelay=Math.min(this.replaceDelay*2,1e4),!0}}function GZ(){let Q=globalThis.Bun?.RedisClient;if(typeof Q!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return Q}var o0=new TextEncoder;function f1(Q){return`id: ${Q.seq}
|
|
8
|
+
data: ${JSON.stringify(Q.event)}
|
|
9
|
+
|
|
10
|
+
`}var HZ=5000,YZ=`: keepalive
|
|
11
|
+
|
|
12
|
+
`;function KZ(Q,Z=HZ){let $=null,X=!1,G=()=>{if(X)return;if($!==null)clearTimeout($);$=setTimeout(()=>{if($=null,X)return;try{Q.enqueue(o0.encode(YZ))}catch{H();return}G()},Z)},H=()=>{if(X=!0,$!==null)clearTimeout($);$=null};return G(),{touch:G,stop:H}}function MZ(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function n8(Q,Z=200){let $=Q[Symbol.asyncIterator](),X=-1,G,H=new ReadableStream({start(Y){G=KZ(Y)},async pull(Y){try{let M=await $.next();if(M.done){G.stop(),Y.close();return}X=M.value.seq,Y.enqueue(o0.encode(f1(M.value))),G.touch()}catch(M){let K={type:"error",error:WZ(M)};G.stop(),Y.enqueue(o0.encode(f1({seq:X+1,event:K}))),Y.close()}},cancel(Y){G.stop(),$.return?.(Y)}});return new Response(H,{status:Z,headers:MZ()})}var JZ=new Set(["frame_cursor_evicted","live_run_not_found"]);function WZ(Q){let Z=Q&&typeof Q==="object"?Q.code:void 0;if(Q instanceof Error&&typeof Z==="string"&&JZ.has(Z))return{code:"unknown",message:Q.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",Q),{code:"unknown",message:"The run's stream failed.",retryable:!1}}
|
|
13
|
+
export{t0 as Ih,v1 as Jh,UZ as Kh,K1 as Lh,AZ as Mh,W1 as Nh,TZ as Oh,s0 as Ph,r0 as Qh,VZ as Rh,BZ as Sh,PZ as Th,a0 as Uh,NZ as Vh,z1 as Wh,wZ as Xh,EZ as Yh,s as Zh,k as _h,X1 as $h,Y1 as ai,CZ as bi,OZ as ci,HQ as di,YQ as ei,g0 as fi,y0 as gi,KQ as hi,h as ii,MQ as ji,X0 as ki,x1 as li,O0 as mi,G0 as ni,R1 as oi,v0 as pi,U8 as qi,L1 as ri,h0 as si,N as ti,m as ui,F0 as vi,n as wi,I0 as xi,A0 as yi,T0 as zi,K0 as Ai,m0 as Bi,l as Ci,c0 as Di,M0 as Ei,q0 as Fi,p0 as Gi,A1 as Hi,w1 as Ii,N1 as Ji,sQ as Ki,l0 as Li,$Z as Mi,XZ as Ni,YZ as Oi,KZ as Pi,MZ as Qi,n8 as Ri};
|
|
14
|
+
|
|
15
|
+
//# debugId=6F21352C1B457E3864756E2164756E21
|