gemi 0.246.0 → 0.246.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +1 -1
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/providers/stream.d.ts +5 -1
- package/dist/ai/providers/stream.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/{chunk-p8ypq16v.js → chunk-8adt2k7j.js} +1 -1
- package/dist/{chunk-t56z2zec.js → chunk-gv7eh0wd.js} +1 -1
- package/dist/{chunk-bcpxyv8m.js → chunk-hn2mm9r6.js} +4 -4
- package/dist/{chunk-bcpxyv8m.js.map → chunk-hn2mm9r6.js.map} +4 -4
- package/dist/{chunk-q0k1j5a4.js → chunk-n626761s.js} +1 -1
- package/dist/{chunk-dxtxvxcz.js → chunk-p9trv4kn.js} +2 -2
- package/dist/{chunk-dxtxvxcz.js.map → chunk-p9trv4kn.js.map} +1 -1
- package/dist/chunk-pvs5qjs7.js +5 -0
- package/dist/{chunk-dapd4vkd.js.map → chunk-pvs5qjs7.js.map} +3 -3
- package/dist/{chunk-ggh1hzdb.js → chunk-qqh6h36y.js} +1 -1
- package/dist/{chunk-11fc5nve.js → chunk-tm4kfnqh.js} +1 -1
- package/dist/client/describeCaughtError.d.ts +11 -0
- package/dist/client/describeCaughtError.d.ts.map +1 -0
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +2 -3
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-dapd4vkd.js +0 -5
- /package/dist/{chunk-p8ypq16v.js.map → chunk-8adt2k7j.js.map} +0 -0
- /package/dist/{chunk-t56z2zec.js.map → chunk-gv7eh0wd.js.map} +0 -0
- /package/dist/{chunk-q0k1j5a4.js.map → chunk-n626761s.js.map} +0 -0
- /package/dist/{chunk-ggh1hzdb.js.map → chunk-qqh6h36y.js.map} +0 -0
- /package/dist/{chunk-11fc5nve.js.map → chunk-tm4kfnqh.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ca as ZZ,da as GZ,ea as VZ,fa as Q0,ga as J0,ha as $0,ia as K$,ja as Z0,ka as W0,la as EJ,ma as X0,na as K0,oa as G0,pa as V0}from"../chunk-
|
|
2
|
+
import{ca as ZZ,da as GZ,ea as VZ,fa as Q0,ga as J0,ha as $0,ia as K$,ja as Z0,ka as W0,la as EJ,ma as X0,na as K0,oa as G0,pa as V0}from"../chunk-hn2mm9r6.js";import{$c as p6,Ac as vZ,Bc as yZ,Cc as A$,Ec as R$,Fc as I$,Gc as T$,Hc as j$,Ic as x$,Jc as w$,Kc as f$,Lc as q$,Mc as b$,Nc as v$,Oc as y$,Pc as h$,Rc as v6,Sc as y6,Tc as h6,Uc as g6,Vc as c6,Wc as OQ,Xc as u6,Yc as R8,Zc as m6,_c as E8,ad as l6,bd as i6,cd as gQ,dd as _J,ed as d6,fd as n6,gd as k8,hd as o6,ic as J$,id as s6,jc as C8,jd as a6,kc as U8,kd as t6,lc as $$,ld as r6,md as T8,nd as e6,od as CJ,pc as JZ,qc as $Z,rc as s$,sc as FQ,tc as x6,uc as g,vc as B$,wc as S$,yc as M$,zc as i}from"../chunk-tm4kfnqh.js";import{$d as W$,Dd as o,Ed as Z$,Hd as _8,Id as O8,Jd as L8,Kd as oQ,Ld as B8,Md as QJ,Nd as sQ,Od as oJ,Pd as S8,Qd as M8,Rd as JJ,Sd as A8,Yd as KQ,_d as XQ,ae as I6,be as X$,ce as w6,de as f6,ee as q6,fe as b6,sd as YZ,td as S,ud as k}from"../chunk-hhka8j31.js";import{we as F$}from"../chunk-mc7p37d0.js";import"../chunk-nbdjbde4.js";import{Ki as z8,Ni as D8,Sj as H8,Tj as bJ,kj as w}from"../chunk-pvs5qjs7.js";import{Uj as Y8,Wj as rQ,Xj as eQ}from"../chunk-2kt5kgaq.js";import{$j as T6,_j as k6,ak as j6}from"../chunk-gx5yhz2m.js";import{nk as n}from"../chunk-vq0gcvcy.js";import"../chunk-k5vt2kz6.js";import{ul as P8,vl as N8,wl as F8,xl as nJ}from"../chunk-z5wwhgsg.js";import"../chunk-mbfjxyq0.js";import{Dl as ZQ,El as WQ,Tl as vQ}from"../chunk-kss2kkmm.js";import{em as BZ}from"../chunk-n26d4z3t.js";import"../chunk-zez3fjnf.js";import{Nm as AZ}from"../chunk-xac2vwtq.js";import"../chunk-se0tnb9x.js";import"../chunk-w31afsrx.js";import{in as KJ}from"../chunk-ket76475.js";import"../chunk-748evey0.js";import{existsSync as v8,readdirSync as Y0,readFileSync as H$}from"fs";import{isAbsolute as y8,join as xQ,relative as h8,sep as g8}from"path";var P$="prompts.json",c8=/\{\{>\s*([\w./-]+)\s*\}\}/g,z$=/\{\{(\w+)\}\}/g,u8=/^[\w-]+(\/[\w-]+)*$/,Y$={dir:"app/agents",shared:"prompts"},wQ={},WJ=new Map,IQ;function m8(){if(IQ===void 0){let Q=xQ(KJ(),"dist","server",P$);IQ=v8(Q)?JSON.parse(H$(Q,"utf8")):null}return IQ??null}function p8(Q){return Q.replace(/\r?\n$/,"")}function D$(){return wQ.cache??Bun.env.NODE_ENV==="production"}function l8(Q,J){if(!u8.test(Q))throw Error(`"${Q}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let $=J.dir??wQ.dir??Y$.dir,Z=y8($)?$:xQ(process.cwd(),$),W=Q.includes("/")?`${Q}.md`:xQ(J.shared??wQ.shared??Y$.shared,`${Q}.md`);return xQ(Z,W)}function i8(Q,J){let $=l8(Q,J),Z=D$()?WJ.get($):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let K=m8()?.[h8(KJ(),$).split(g8).join("/")];if(K!==void 0)return K}let X;try{X=p8(H$($,"utf8"))}catch(K){if(K.code==="ENOENT"){let G=W?` or in dist/server/${P$}`:"";throw Error(`The prompt "${Q}" does not exist (looked for ${$}${G}).`)}throw K}if(D$())WJ.set($,X);return X}function XJ(Q,J,$){if(J.includes(Q))throw Error(`The prompt "${Q}" includes itself: ${[...J,Q].join(" > ")}.`);return i8(Q,$).replace(c8,(Z,W)=>XJ(W,[...J,Q],$))}class N${static configure(Q){wQ={...Q},WJ.clear(),IQ=void 0}static render(Q,J={},$={}){return XJ(Q,[],$).replace(z$,(Z,W)=>{if(!Object.hasOwn(J,W))throw Error(`The prompt "${Q}" has no value for {{${W}}}.`);return String(J[W])})}static placeholders(Q,J={}){let $=[...XJ(Q,[],J).matchAll(z$)].map((Z)=>Z[1]);return[...new Set($)]}}class GJ extends F${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await i.sweep({limit:100})===100);}}var qQ=20,d8=300,n8=200;function U$(Q,J){if(J<=0||Q.length===0)return null;let $=(X,K)=>K.createdAt-X.createdAt||(X.id<K.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.",...[...Q.filter((X)=>!g(X.state)).sort($),...Q.filter((X)=>g(X.state)).sort($)].slice(0,J).map((X)=>{let K=[`- ${X.id} (${X.toolName})`];if(X.state==="waiting")K.push(`waiting for ${(X.after??[]).join(", ")} since ${fQ(X.createdAt)}`);else if(X.state==="running")K.push(`running since ${fQ(X.createdAt)}`);else if(X.state==="ok")K.push(`finished at ${fQ(X.settledAt??X.updatedAt)}`);else{let G=X.error?`${X.error.code}: ${C$(X.error.message,n8)}`:"failed";K.push(`failed at ${fQ(X.settledAt??X.updatedAt)} (${G})`)}if(X.summary!==void 0)K.push(`summary: ${C$(JSON.stringify(X.summary),d8)}`);if(X.orphaned)K.push("its tool call was lost when the turn that started it was cut short");return K.join("; ")}),"</jobs>"].join(`
|
|
3
3
|
`)}function fQ(Q){return new Date(Q).toISOString().replace(/\.\d{3}Z$/,"Z")}function C$(Q,J){return Q.length<=J?Q:`${Q.slice(0,J-1)}\u2026`}var _$=["after_jobs","batch_key","queued","inbox","job_checkpoint"],O$=20;class VJ{table;sql;dialect;connection;later;constructor(Q,J={}){let $=J.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The agent jobs table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=Q.sql,this.dialect=Q.dialect,this.connection=Q.name}async createTable(){for(let Q of o8(this.dialect,this.table))await this.sql.unsafe(Q)}async transaction(Q){if(this.connection===void 0||this.joinable())return Q();return vQ(this.sql,()=>Q(),{connection:this.connection,dialect:this.dialect})}async create(Q){let J=Q.after!==void 0||Q.batch!==void 0||Q.queued!==void 0;if(J)await this.requireLaterColumns("A job with `after` or `batch`");let $=this.q(),Z=this.clock($),W=Q.state??"running";if(J)await $`
|
|
4
4
|
INSERT INTO ${this.name($)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../ai/providers/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AASjF,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhF,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;iDAE6C;IAC7C,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;eAGW;IACX,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IAC3D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,mBAAmB,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,oFAAoF;IACpF,UAAU,EAAE,MAAM,CAAC;IACnB,8EAA8E;IAC9E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iFAAiF;IACjF,EAAE,CAAC,EAAE,SAAS,cAAc,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,oBAAoB,KAAK,OAAO,CAAC,CAAC;CAClG,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,OAAO,CAAC;IAClB,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;CAC7C,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,mBAAmB,EAC3B,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAST;AAED,eAAO,MAAM,+BAA+B,OAAQ,CAAC;AACrD,eAAO,MAAM,2BAA2B,QAAS,CAAC;AAElD,kDAAkD;AAClD,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,mBAAmB,GAAG,SAAS,GAAG,IAAI,CAiB/E;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,MAAM,GACnB,MAAM,GAAG,SAAS,CAUpB;AAMD,eAAO,MAAM,YAAY,QAAS,CAAC;AAEnC;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOjG;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,MAAM,GAAG,MAAM,CAG5E;AA6CD;;;;;;;;;;;GAWG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,KAAK,GAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAgB,GACxE,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,QAAQ,CAAC,CAqHnB;AAgBD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,WAAW,CACzB,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,MAAM,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EACzC,EAAE,EAAE;IAAE,IAAI,EAAE,MAAM,KAAK,CAAC;IAAC,GAAG,EAAE,MAAM,KAAK,CAAA;CAAE,GAC1C,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../ai/providers/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AASjF,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhF,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;iDAE6C;IAC7C,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;eAGW;IACX,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IAC3D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,mBAAmB,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,oFAAoF;IACpF,UAAU,EAAE,MAAM,CAAC;IACnB,8EAA8E;IAC9E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iFAAiF;IACjF,EAAE,CAAC,EAAE,SAAS,cAAc,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,oBAAoB,KAAK,OAAO,CAAC,CAAC;CAClG,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,OAAO,CAAC;IAClB,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;CAC7C,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,mBAAmB,EAC3B,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAST;AAED,eAAO,MAAM,+BAA+B,OAAQ,CAAC;AACrD,eAAO,MAAM,2BAA2B,QAAS,CAAC;AAElD,kDAAkD;AAClD,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,mBAAmB,GAAG,SAAS,GAAG,IAAI,CAiB/E;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,MAAM,GACnB,MAAM,GAAG,SAAS,CAUpB;AAMD,eAAO,MAAM,YAAY,QAAS,CAAC;AAEnC;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOjG;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,MAAM,GAAG,MAAM,CAG5E;AA6CD;;;;;;;;;;;GAWG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,KAAK,GAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAgB,GACxE,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,QAAQ,CAAC,CAqHnB;AAgBD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,WAAW,CACzB,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,MAAM,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EACzC,EAAE,EAAE;IAAE,IAAI,EAAE,MAAM,KAAK,CAAC;IAAC,GAAG,EAAE,MAAM,KAAK,CAAA;CAAE,GAC1C,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,CA4CnC"}
|
|
@@ -39,7 +39,11 @@ export declare function parseResponsesStream(chunks: AsyncIterable<string> | Ite
|
|
|
39
39
|
export declare function emptyUsage(): Usage;
|
|
40
40
|
export declare function toUsage(raw: any): Usage;
|
|
41
41
|
/** A `ReadableStream` of bytes to the string chunks the parser wants. Split out
|
|
42
|
-
* so the parser never has to know it came from a socket.
|
|
42
|
+
* so the parser never has to know it came from a socket.
|
|
43
|
+
*
|
|
44
|
+
* A consumer that stops before the end (an aborted run, a `break`, an error
|
|
45
|
+
* thrown at the `yield`) cancels the body, so the provider's connection goes
|
|
46
|
+
* with it rather than when the fetch is aborted, if it ever is (#1407). */
|
|
43
47
|
export declare function decodeChunks(body: ReadableStream<Uint8Array> | null): AsyncGenerator<string>;
|
|
44
48
|
export {};
|
|
45
49
|
//# sourceMappingURL=stream.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../ai/providers/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAgB,KAAK,EAAE,MAAM,UAAU,CAAC;AAGpD;;;;;;;GAOG;AAEH,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtE;;;;;;;;;GASG;AACH,wBAAuB,WAAW,CAChC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,GAC/C,cAAc,CAAC,UAAU,CAAC,CAwD5B;AAED,KAAK,YAAY,GAAG;IAClB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;gDAC4C;IAC5C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC,CAAC;AAIF,wBAAuB,oBAAoB,CACzC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAChD,OAAO,GAAE,YAAiB,GACzB,cAAc,CAAC,aAAa,CAAC,CAqR/B;AA+HD,wBAAgB,UAAU,IAAI,KAAK,CAElC;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,KAAK,CAcvC;AAED;
|
|
1
|
+
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../ai/providers/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAgB,KAAK,EAAE,MAAM,UAAU,CAAC;AAGpD;;;;;;;GAOG;AAEH,MAAM,MAAM,UAAU,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtE;;;;;;;;;GASG;AACH,wBAAuB,WAAW,CAChC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,GAC/C,cAAc,CAAC,UAAU,CAAC,CAwD5B;AAED,KAAK,YAAY,GAAG;IAClB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;gDAC4C;IAC5C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC,CAAC;AAIF,wBAAuB,oBAAoB,CACzC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAChD,OAAO,GAAE,YAAiB,GACzB,cAAc,CAAC,aAAa,CAAC,CAqR/B;AA+HD,wBAAgB,UAAU,IAAI,KAAK,CAElC;AAED,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,KAAK,CAcvC;AAED;;;;;4EAK4E;AAC5E,wBAAuB,YAAY,CACjC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,GACtC,cAAc,CAAC,MAAM,CAAC,CA6BxB"}
|
package/dist/ai/testing/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{la as b}from"../../chunk-
|
|
2
|
+
import{la as b}from"../../chunk-hn2mm9r6.js";import{be as n}from"../../chunk-hhka8j31.js";import{$j as p,_j as d}from"../../chunk-gx5yhz2m.js";import"../../chunk-vq0gcvcy.js";import"../../chunk-xac2vwtq.js";import"../../chunk-se0tnb9x.js";import"../../chunk-ket76475.js";import"../../chunk-748evey0.js";import{createHash as QD}from"crypto";import{createHash as x}from"crypto";import{existsSync as o,readdirSync as s,readFileSync as t,statSync as r}from"fs";import{join as E,relative as e,sep as DD}from"path";var M="\u241F",u=6,$D=/\{\{>\s*([^}\s]+)\s*\}\}/g,v=(D)=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function m(D){let $=D.filter((Q)=>Q.length>=u),z=D.filter((Q)=>Q.length<u);return(Q)=>{let V=Q;for(let X of $)if(V.includes(X))V=V.split(X).join(M);for(let X of z)V=V.replace(new RegExp(`${v(X)}\\s*${M}`,"g"),M).replace(new RegExp(`${M}\\s*${v(X)}`,"g"),M);return V.replace(new RegExp(`\\s*${M}[\\s${M}]*`,"g"),M)}}function g(D,$=[]){for(let z of s(D)){if(z==="node_modules")continue;let Q=E(D,z);if(r(Q).isDirectory())g(Q,$);else if(z.endsWith(".md"))$.push(Q)}return $}class H{data;root;options;constructor(D,$={}){this.data=D;this.options=$,this.root=$.root??process.cwd()}static blob(D){return x("sha1").update(`blob ${Buffer.byteLength(D)}\x00`).update(D).digest("hex")}static pieces(D){return D.split(/\{\{[^}]*\}\}/).map(($)=>$.trim()).filter(($)=>$.length>0)}static tool(D){return x("sha256").update(JSON.stringify({description:D.description,parameters:D.parameters})).digest("hex")}static prompts(D={}){let $=D.root??process.cwd(),z=new Map;for(let Q of D.dirs??["app/agents"]){if(!o(E($,Q)))continue;for(let V of g(E($,Q)).sort())z.set(e($,V).split(DD).join("/"),t(V,"utf8"))}return z}static of(D,$,z={}){let Q=[...D].join(`
|
|
3
3
|
\x00
|
|
4
4
|
`),V={};for(let[J,Z]of H.prompts(z))if(H.pieces(Z).filter((j)=>j.length>=12).sort((j,Y)=>Y.length-j.length).slice(0,3).some((j)=>Q.includes(j)))V[J]=H.blob(Z);let X=[...$.keys()].sort(),K=z.inputs?.(new Set(X));return new H({prompts:V,tools:Object.fromEntries(X.map((J)=>[J,[...$.get(J)].sort()])),...K&&Object.keys(K).length>0?{inputs:zD(K)}:{}},z)}same(D){let $=D instanceof H?D.data:D;return JSON.stringify(this.data)===JSON.stringify($)}changed(){let D=this.options.inputs?.(new Set(Object.keys(this.data.tools)))??{};return[...this.changedPrompts().map(([$])=>$),...Object.entries(this.data.inputs??{}).filter(([$,z])=>D[$]!==z).map(([$])=>`input ${$}`)]}cutters(){let D=H.prompts(this.options),$=this.changedPrompts(),z=new Map,Q=new Map;for(let[V,X]of $){let K=this.readBlob(X);if(K===void 0)throw Error(`${V} changed since the recording, and the version it was recorded with (${X}) can't be read back from git`);if(z.set(V,K),D.has(V))Q.set(V,D.get(V))}return{changed:$.map(([V])=>V),recorded:m(this.piecesWithPartials(z,(V)=>{let X=this.data.prompts[V];return X&&this.readBlob(X)||D.get(V)})),sent:m(this.piecesWithPartials(Q,(V)=>D.get(V)))}}changedPrompts(){let D=H.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let Q=D.get($);return Q===void 0||H.blob(Q)!==z})}readBlob(D){if(this.options.readBlob)return this.options.readBlob(D);let $=Bun.spawnSync(["git","cat-file","blob",D],{cwd:this.root});return $.exitCode===0?$.stdout.toString():void 0}piecesWithPartials(D,$){let z=this.options.dirs??["app/agents"],Q=this.options.shared??"prompts",V=[...D];while(V.length>0){let[X,K]=V.pop(),J=z.find((Z)=>X.startsWith(`${Z}/`));if(J===void 0)continue;for(let[,Z]of K.matchAll($D)){let B=`${J}/${Z.includes("/")?Z:`${Q}/${Z}`}.md`,j=D.has(B)?void 0:$(B);if(j===void 0)continue;D.set(B,j),V.push([B,j])}}return[...D.values()].flatMap((X)=>H.pieces(X)).sort((X,K)=>K.length-X.length)}}function zD(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class w extends Error{constructor(D){super(`${D} Record again.`);this.name="RecordingMismatchError"}}var VD=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;function T(D,$){if(typeof D==="string")return $(D);if(Array.isArray(D))return D.map((z)=>T(z,$));if(D&&typeof D==="object")return Object.fromEntries(Object.entries(D).map(([z,Q])=>[z,T(Q,$)]));return D}function h(D){return JSON.parse(JSON.stringify(D,function($,z){if($==="nested")return;if($==="output"&&this.type==="tool-result"&&"modelOutput"in this)return;return z}))}function c(){let D;return{promise:new Promise((z)=>D=z),resolve:D}}var XD=(D)=>QD("sha256").update(D).digest("hex"),k=(D)=>D.flatMap(($)=>("tools"in $)?$.tools:[$]);function l(D){return D.map(({role:$,content:z})=>({role:$,parts:(Array.isArray(z)?z:[]).flatMap((Q)=>{if(Q?.type==="tool-call")return[{call:Q.name,input:Q.input??Q.args}];if(Q?.type==="tool-result")return[{result:Q.name,status:Q.status}];if(Q?.type==="file")return[{file:!0}];return[]})}))}class R extends b{live;model;capabilities;recordedAt;calls;recordedNested;children=new Map;parent;key;sent=[];uploads;uploadCount=0;read;shared;options;texts=new Set;toolHashes=new Map;toolLists=new Set;recorded;cuts;constructor(D,$,z,Q){super();this.live=D;if(this.options={...z,match:z.match??"wording",ids:new RegExp(z.ids??VD,"g"),waitMs:z.waitMs??60000},Q){let{parent:V}=Q;this.parent=V,this.key=Q.key,this.model=V.model,this.capabilities=V.capabilities,this.recordedAt=V.recordedAt,this.calls=Q.calls,this.recordedNested={},this.uploads=V.uploads,this.shared=V.shared;return}if(this.shared={ids:new Map,stale:new Set,staleCalls:0,started:0,moved:c()},this.uploads=new Map,D){this.model=D.model,this.capabilities=D.capabilities,this.recordedAt=new Date,this.calls=[],this.recordedNested={};return}if(!$||$.version!==1||!Array.isArray($.calls))throw Error("RecordingProvider.replay needs a recording made by RecordingProvider.");if(this.model=$.model,this.capabilities=$.capabilities,this.recordedAt=new Date($.recordedAt),this.calls=structuredClone($.calls),this.recordedNested=structuredClone($.nested??{}),$.fingerprints)this.recorded=new H($.fingerprints,z.fingerprints)}static record(D,$={}){return new R(D,void 0,$)}static replay(D,$={}){return new R(void 0,D,$)}get isRecording(){return this.live!==void 0}get stale(){return this.shared.stale}get staleCalls(){return this.shared.staleCalls}nested(D){if(this.parent)return this.parent.nested(D);let $=this.children.get(D);if(!$){let z=this.recordedNested[D];if(!this.live&&!z)throw new w(`The recording has no sub-run "${D}".`);$=new R(this.live,void 0,this.options,{parent:this,key:D,calls:z??[]}),this.children.set(D,$)}return $}recording(){if(this.parent)return this.parent.recording();if(!this.live)throw Error("Only a recording provider (`record`) has a recording to save.");return{version:1,model:this.model,capabilities:this.capabilities,recordedAt:this.recordedAt.toISOString(),calls:structuredClone(this.calls),...this.options.fingerprints?{fingerprints:this.fingerprints().data}:{},...this.children.size>0?{nested:Object.fromEntries([...this.children].map(([D,$])=>[D,structuredClone($.calls)]))}:{}}}fingerprints(){let D=this.parent??this;return H.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new H(D.fingerprints,$).changed():[]}replayedInFull(){let D=this.parent??this;return D.calls.length===0&&Object.entries(D.recordedNested).every(([$,z])=>(D.children.get($)?.calls??z).length===0)}async pin(D){if(this.live)return this.read=D,D;let $=this.calls[0]?.read;if($===void 0)return D;return await(this.parent??this).reach($,this.where()),$}async upload(D){let $=++this.uploadCount,z=this.key===void 0?`upload_${$}`:`upload_${this.key}_${$}`;if(this.live)this.uploads.set(z,await this.live.upload(D));return z}async deleteFile(D){let $=this.uploads.get(D);if(this.live&&$!==void 0){if(!this.live.deleteFile)throw Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);await this.live.deleteFile($),this.uploads.delete(D)}}normalizeError(D){return this.live?this.live.normalizeError(D):super.normalizeError(D)}async*stream(D){let $=this.requestOf(D);if(this.live){yield*this.recordCall(D,$);return}yield*this.replayCall(D,$)}async*recordCall(D,$){let z=this.parent??this,Q=z.shared.started++,V=this.read;this.read=void 0;let X=[],K=D.messages.map((Z)=>({...Z,content:Z.content.map((B)=>B.type==="file"&&B.fileId&&this.uploads.has(B.fileId)?{...B,fileId:this.uploads.get(B.fileId)}:B)}));for await(let Z of this.live.stream({...D,messages:K})){let B=X.at(-1);if(Z.type==="tool-call-discard"){let j=new Set(Z.toolCallIds),Y=X.filter((W)=>W.type!=="tool-call-delta"||!j.has(W.toolCallId));X.splice(0,X.length,...Y)}else if(Z.type==="retry");else if(B&&(Z.type==="text-delta"||Z.type==="output-delta")&&B.type===Z.type)B.delta+=Z.delta;else if(B?.type==="tool-call-delta"&&Z.type==="tool-call-delta"&&B.toolCallId===Z.toolCallId)B.argsDelta+=Z.argsDelta;else X.push({...Z});yield Z}let J=this.options.position?await this.options.position():void 0;this.calls.push({request:$,events:X,at:Q,...V!==void 0?{read:V}:{},...J!==void 0?{ended:J}:{}})}async*replayCall(D,$){let z=this.parent??this,Q=this.where(),V=this.calls[0];if(this.options.ordered&&V?.at!==void 0)await z.turn(V.at,Q);let X=this.calls.shift();if(!X)throw new w(`${Q}: call ${this.sentCalls} was not recorded (the recording has no more calls).`);let{promptCacheKey:K,...J}=X.request;if(!z.matches(JSON.stringify(J),$))z.tolerate(Q,{...X,request:J},$,D.tools??[]);if(X.ended!==void 0)await z.reach(X.ended,Q);let Z=z.shared.ids;for(let B of X.events)yield JSON.parse(JSON.stringify(B).replace(this.options.ids,(j)=>Z.get(j)??j))}where(){return this.key===void 0?"the recording":`sub-run "${this.key}"`}sentCalls=0;requestOf(D){this.sentCalls++;let{signal:$,promptCacheKey:z,agent:Q,messages:V,tools:X,...K}=D,J=V.map(({role:W,content:I})=>({role:W,content:h(I)})),Z=this.sent.length>0&&this.sent.length<=J.length&&JSON.stringify(J.slice(0,this.sent.length))===JSON.stringify(this.sent)?this.sent.length:0;this.sent=J;let B=X&&X.length>0?JSON.stringify(X):void 0,j=this.parent??this,Y=(W)=>{return j.texts.add(W),W};if(T([K,J.slice(Z)],Y),B&&!j.toolLists.has(B)){j.toolLists.add(B);for(let W of k(X)){T(W,Y);let I=j.toolHashes.get(W.name)??new Set;I.add(H.tool(W)),j.toolHashes.set(W.name,I)}}return{...h(K),...B?{tools:`sha256:${XD(B)}`,toolNames:k(X).map((W)=>W.name).sort()}:{},...Z>0?{after:Z}:{},messages:J.slice(Z)}}matches(D,$){let z=this.options.ids,Q=JSON.stringify($),V=D.match(z)??[],X=Q.match(z)??[];if(V.length!==X.length)return!1;let K=new Map(this.shared.ids);for(let[J,Z]of V.entries()){let B=K.get(Z)??X[J];if(B!==X[J])return!1;K.set(Z,B)}if(D.replace(z,(J)=>K.get(J))!==Q)return!1;for(let[J,Z]of K)this.shared.ids.set(J,Z);return!0}tolerate(D,$,z,Q){let V=this.options.ids,X=this.options.match,K=$.request,J=(O,_,G)=>{let U=JSON.stringify(O).replace(V,"<id>"),C=JSON.stringify(_).replace(V,"<id>"),L=0;while(L<U.length&&U[L]===C[L])L++;throw new w(`${D}: the request differs from the recorded one${G}. Recorded: \u2026${U.slice(Math.max(0,L-80),L+120)}\u2026 Sent: \u2026${C.slice(Math.max(0,L-80),L+120)}\u2026`)};if(X==="exact")J(K,z,"");let{tools:Z,toolNames:B,...j}=K,{tools:Y,toolNames:W,...I}=z,P=[];if(!this.matches(JSON.stringify(j),I))if(X==="wording"){if(!this.recorded)J(j,I,", and the recording has no fingerprints to tell a reworded prompt by");try{this.cuts??=this.recorded.cutters()}catch(G){throw new w(`${D}: ${G.message}.`)}let O=T(j,this.cuts.recorded),_=T(I,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(O),_))J(O,_,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");P.push(...this.cuts.changed.map((G)=>`${G} changed`))}else{if(!((K.after??0)===(z.after??0)&&this.matches(JSON.stringify(l(K.messages)),l(z.messages))))J(j,I," in the conversation itself");let{messages:_,...G}=j,{messages:U,...C}=I;if(!this.matches(JSON.stringify(_),U))P.push("message text changed");let L=new Set([...Object.keys(G),...Object.keys(C)]);for(let q of[...L].sort()){let A=JSON.stringify(G[q]??null);if(!this.matches(A,C[q]??null))P.push(`${q} changed`)}}if(Z!==Y){let O=k(Q);for(let _ of $.events){if(_.type!=="tool-call")continue;let G=O.find((A)=>A.name===_.name);if(!G)throw new w(`${D}: the recorded answer calls ${_.name}, which is not offered any more.`);let U=Object.fromEntries([...JSON.stringify(G.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,A])=>[A,!0])),C;try{C=JSON.parse(_.args||"{}")}catch{C=void 0}let L;try{L=p.fromJSONSchema(G.parameters,{unknownKeys:"error",formats:U})}catch(A){if(!(A instanceof d))throw A}let q=L?.safeParse(C);if(q&&q.ok===!1)throw new w(`${D}: the recorded call of ${_.name} does not fit its schema any more (${q.errors.join("; ")}).`)}if(this.recorded){let _=O.filter((G)=>!this.recorded.data.tools[G.name]?.includes(H.tool(G))).map((G)=>G.name).sort();P.push(_.length>0?`tools changed: ${_.join(", ")}`:"the tools offered changed")}else{let _=new Set(B??[]),G=new Set(W??[]),U=[...G].filter((L)=>!_.has(L)),C=[..._].filter((L)=>!G.has(L));P.push(U.length>0||C.length>0?`tools offered changed (${[...U.map((L)=>`+${L}`),...C.map((L)=>`-${L}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let O of P)this.shared.stale.add(O)}async turn(D,$){let z=this.shared;z.pending??=[...this.calls,...Object.values(this.recordedNested).flat()].map((Q)=>Q.at).filter((Q)=>Q!==void 0).sort((Q,V)=>Q-V);while(z.pending[0]!==void 0&&z.pending[0]<D){let Q=z.moved.promise;if(!await Promise.race([Q.then(()=>!0),new Promise((X)=>setTimeout(()=>X(!1),this.options.waitMs))]))throw new w(`${$}: call ${D} waits for call ${z.pending[0]}, which the replay does not make.`)}z.pending=z.pending.filter((Q)=>Q!==D),z.moved.resolve(),z.moved=c()}async reach(D,$){let z=this.options.position;if(!z)return;let Q=await z(),V=0;while(Q<D){await new Promise((K)=>setTimeout(K,25));let X=await z();if(V=X===Q?V+25:0,Q=X,V>=this.options.waitMs)throw new w(`${$}: a call waits for the app to reach ${D}; it stays at ${Q}.`)}}}function ZD(D){let $=globalThis.Date,z=new $(D).getTime()-$.now();if(!Number.isFinite(z))throw Error(`pinClock: ${String(D)} is not a date.`);class Q extends ${constructor(...V){if(V.length===0)super($.now()+z);else super(...V)}static now(){return $.now()+z}}return globalThis.Date=Q,()=>{if(globalThis.Date===Q)globalThis.Date=$}}class N extends Error{error;name="ScriptedProviderError";constructor(D,$){super(D);this.error=$}}var F=Symbol("scriptedProvider.NO_AGENT");function a(D){let z=n(D).at(-1),Q=z?.find((X)=>X.role==="user");if(!z||!Q)return;let V=Q.content.map((X)=>X.type==="text"?X.text:"").join("");return{message:Q,text:V,messages:z}}var S=void 0,i=(D)=>D===S?"the script":D===F?"NO_AGENT":`"${D}"`,BD={reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,trailingContext:!0};class f extends b{options;model="scripted";capabilities=BD;calls=[];uploads=[];steps;used=new Map;constructor(D,$={}){super();this.options=$;this.steps=new Map(Array.isArray(D)?[[S,[...D]]]:[...Object.entries(D).map(([z,Q])=>[z,[...Q]]),...D[F]?[[F,[...D[F]]]]:[]])}callsOf(D){return this.calls.filter(($)=>$.agent===D)}assertDone(){let D=[...this.steps].flatMap(([$,z])=>{let Q=z.length-(this.used.get($)??0);return Q>0?[`${i($)}: ${Q} step(s)`]:[]});if(D.length>0)throw new N(`Steps never used: ${D.join(", ")}.`)}stream(D){let $=D.agent?.name,z=this.steps.has(S)?S:$??F,Q=this.used.get(z)??0,V={agent:$,depth:D.agent?.depth??0,index:this.calls.filter((j)=>j.agent===$).length,messages:D.messages,turn:a(D.messages),trailingContext:D.trailingContext,params:D};this.calls.push(V);let X=this.steps.get(z),K=X?.[Q];if(X&&K!==void 0)this.used.set(z,Q+1);let J=()=>{let j=$===void 0?"A call no agent made":`Agent "${$}"`,Y=V.turn?` (turn: ${JSON.stringify(V.turn.text.slice(0,80))})`:"";if(!X){let W=[...this.steps.keys()].map(i).join(", ");return`${j} has no script${Y}. The scripts are for ${W}.${$===void 0?" Script it under [NO_AGENT].":""}`}if(z===S){let W=$===void 0?"":` (${$}'s call ${V.index+1})`;return`The script ran out at step ${Q+1}${W}: it has ${X.length} step(s)${Y}.`}return`${j} made call ${V.index+1}, and its script has ${X.length} step(s)${Y}.`},Z=X?this.options.exhausted??"throw":"throw",B=K??(Z==="throw"||Z==="stop"?void 0:Z);return async function*(){if(B===void 0){if(Z==="throw")throw new N(J());yield y("stop");return}yield*jD(await KD(B,V),V)}()}async upload(D){return this.uploads.push(D),`file_${this.uploads.length}`}normalizeError(D){if(D instanceof N&&D.error)return{...D.error};return{code:"provider_error",message:D instanceof Error?D.message:String(D),retryable:!1}}}function JD(D,$){return new f(D,$)}async function KD(D,$){let z=D;while(typeof z==="function")z=await z($);return z}var y=(D,$)=>({type:"finish",reason:D,usage:$??{inputTokens:1,outputTokens:1,totalTokens:2}});function jD(D,$){if(typeof D==="string")return[{type:"text-delta",delta:D},y("stop")];if("events"in D)return D.events;if("error"in D){let{error:Q}=D;if(typeof Q==="string")throw new N(Q);if(Q instanceof Error)throw Q;throw new N(Q.message,Q)}let z=[];if(D.reasoning)z.push({type:"reasoning-delta",delta:D.reasoning});for(let Q of typeof D.text==="string"?[D.text]:D.text??[])if(Q)z.push({type:"text-delta",delta:Q});if(D.output!==void 0)z.push({type:"output-delta",delta:JSON.stringify(D.output)});return(D.toolCalls??[]).forEach((Q,V)=>{z.push({type:"tool-call",toolCallId:Q.id??`call_${$.agent??"any"}_${$.index}_${V}`,name:Q.name,args:JSON.stringify(Q.input??{})})}),z.push(y(D.finishReason??"stop",D.usage)),z}export{a as turnOf,JD as scriptedProvider,ZD as pinClock,N as ScriptedProviderError,f as ScriptedProvider,R as RecordingProvider,w as RecordingMismatchError,F as NO_AGENT,H as Fingerprints};
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-dxtxvxcz.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{bf as GJ,lh as IJ,mh as g,uh as AJ,vh as RJ,wh as BJ}from"./chunk-t56z2zec.js";import"./chunk-kjzvrx2p.js";import"./chunk-gmkzq212.js";import{Ri as jJ,Si as YJ,Vi as WJ}from"./chunk-dapd4vkd.js";import{Yj as DJ}from"./chunk-2kt5kgaq.js";import"./chunk-gx5yhz2m.js";import"./chunk-vq0gcvcy.js";import"./chunk-cyxsmd4q.js";import"./chunk-qbm49b1t.js";import"./chunk-k5vt2kz6.js";import"./chunk-8vzxnjp4.js";import"./chunk-z5wwhgsg.js";import"./chunk-mbfjxyq0.js";import"./chunk-kss2kkmm.js";import"./chunk-n26d4z3t.js";import"./chunk-5npzvdh9.js";import"./chunk-zez3fjnf.js";import"./chunk-xac2vwtq.js";import"./chunk-se0tnb9x.js";import{Sm as KJ}from"./chunk-dx4h7rap.js";import"./chunk-w31afsrx.js";import{in as PJ}from"./chunk-ket76475.js";import{kn as f}from"./chunk-jzg9zdtj.js";import"./chunk-748evey0.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as B2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:B(J,y,$)}}function B(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(B(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of B(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:B(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
|
|
2
|
+
import{$ as SJ,_ as n,aa as bJ,ba as qJ}from"./chunk-p9trv4kn.js";import{Da as E,Ha as T,Ia as TJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{bf as GJ,lh as IJ,mh as g,uh as AJ,vh as RJ,wh as BJ}from"./chunk-gv7eh0wd.js";import"./chunk-kjzvrx2p.js";import"./chunk-gmkzq212.js";import{Ri as jJ,Si as YJ,Vi as WJ}from"./chunk-pvs5qjs7.js";import{Yj as DJ}from"./chunk-2kt5kgaq.js";import"./chunk-gx5yhz2m.js";import"./chunk-vq0gcvcy.js";import"./chunk-cyxsmd4q.js";import"./chunk-qbm49b1t.js";import"./chunk-k5vt2kz6.js";import"./chunk-8vzxnjp4.js";import"./chunk-z5wwhgsg.js";import"./chunk-mbfjxyq0.js";import"./chunk-kss2kkmm.js";import"./chunk-n26d4z3t.js";import"./chunk-5npzvdh9.js";import"./chunk-zez3fjnf.js";import"./chunk-xac2vwtq.js";import"./chunk-se0tnb9x.js";import{Sm as KJ}from"./chunk-dx4h7rap.js";import"./chunk-w31afsrx.js";import{in as PJ}from"./chunk-ket76475.js";import{kn as f}from"./chunk-jzg9zdtj.js";import"./chunk-748evey0.js";import{createHash as _2}from"crypto";import{join as i,resolve as EJ,sep as vJ}from"path";import{Duplex as cJ}from"stream";import{constants as k,createBrotliCompress as pJ,createGzip as dJ}from"zlib";var lJ=["br","gzip"],oJ=1024,nJ=5,iJ=19,aJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function tJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let V=W.indexOf("=");if(V===-1)continue;if(W.slice(0,V).trim().toLowerCase()==="q"){Y=rJ(W.slice(V+1));break}}$.set(j,Y)}return $}function p(J,$=lJ){let Z=tJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function eJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<oJ)return!1;return!0}function J2(J){let $=J==="br"?pJ({params:{[k.BROTLI_PARAM_QUALITY]:nJ,[k.BROTLI_PARAM_LGWIN]:iJ},flush:k.BROTLI_OPERATION_FLUSH}):dJ({level:aJ,flush:k.Z_SYNC_FLUSH});return cJ.toWeb($)}function $2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function ZJ(J,$){if(!eJ(J.method,$))return $;let Z=new Headers($.headers);$2(Z);let Q=p(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=J2(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as W2,stat as VJ}from"fs/promises";import{join as G2}from"path";import{mkdir as B2,readFile as Z2,stat as T2,writeFile as S2}from"fs/promises";import{dirname as q2,join as Q2}from"path";import{promisify as QJ}from"util";import{brotliCompress as X2,constants as w2,gzip as H2}from"zlib";var j2=".vite/static-assets.json";var XJ={br:".br",gzip:".gz"},Y2=["br","gzip"],k2=QJ(X2),y2=QJ(H2);async function HJ(J){let $;try{$=await Z2(Q2(J,j2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=Y2.filter((Y)=>j.includes(Y))}return Q}function d(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function zJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await W2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=G2(Q,Y.name),V=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await VJ(W);V=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(V&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var V2="public, max-age=31536000, must-revalidate",z2="public, max-age=31536000, immutable";async function U2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=p(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+XJ[Q];try{let j=await VJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function UJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?z2:V2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await U2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${d(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=d(Q.lastModified);let V=jJ(J.headers.get("Range"));if(V){let z=YJ(V,W);if(!z)return GJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":WJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as I2}from"fs/promises";var y="app/client.tsx";function OJ(J,$=E){let Z=J[y]?.file;if(!Z)return;return{module:T(Z,$),preload:B(J,y,$)}}function B(J,$,Z=E){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(T(W.file,Z));for(let V of W.imports??[])j(V)};return j($),Q}function K2(J,$,Z=E){let Q=new Set(B(J,$,Z)),H=[],j=new Set,Y=(V)=>{if(j.has(V))return;j.add(V);let z=J[V];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let V of H)for(let z of B(J,V,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function xJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let V of W.imports??[])j(V);for(let V of W.css??[])if(!Q.has(V))Q.add(V),Z.push(V)};return j($),Z}function CJ(J,$=E){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${KJ}`,j=J[H]?.file;Z.set(Q,j?{src:T(j,$),preload:B(J,H,$),dynamicPreload:K2(J,H,$)}:void 0)}return Z.get(Q)}}var LJ="x-gemi-build";var O2="__gemiReload";function x2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},V=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=V(new URL(window.location.href).origin),I=V(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function _J(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${x2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${O2}}`}var C2=new RegExp(`^${IJ}/.+\\.m?js$`);function l(J){return C2.test(J)}function MJ(J){if(l(J))return new Response(_J(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(g(J))return new Response("Not found",{status:404});return}function NJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function FJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,V)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(V);if(z!==void 0){if(z>H())return;j.delete(V)}let C;try{C=new URL(V.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(V);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(V);return}let L=Bun.file(V).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var L2=`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8" />
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pi as sF}from"./chunk-kjzvrx2p.js";import{Ji as iF}from"./chunk-gmkzq212.js";import{$i as V8,Bj as x6,Hj as A6,Ki as H3,Oi as ZF,Pi as PY,Pj as v1,Qi as NY,Ri as v8,Si as R8,Tj as OZ,Vi as k8,Wi as w8,Xi as tB,Yi as e9,_i as z3,aj as D2,bj as l2,cj as u,ej as g8,fj as f$,gj as jY,hj as i2,ij as s2,jj as U6,kj as S,lj as q9,mj as j5,nj as NZ,oj as y8,pj as C6,rj as g$,sj as j8}from"./chunk-dapd4vkd.js";import{Vj as Z$,Wj as y0,Xj as Y$,Yj as hY}from"./chunk-2kt5kgaq.js";import{bk as h,ek as CQ,fk as DZ}from"./chunk-gx5yhz2m.js";import{gk as QZ,hk as L2,lk as bJ,mk as U8,nk as P}from"./chunk-vq0gcvcy.js";import{qk as DQ,tk as $6}from"./chunk-cyxsmd4q.js";import{Ak as xF,xk as pJ}from"./chunk-qbm49b1t.js";import{Sk as q$,Xk as W$}from"./chunk-k5vt2kz6.js";import{jl as oG}from"./chunk-8vzxnjp4.js";import{kl as LZ,nl as IF,zl as z6}from"./chunk-z5wwhgsg.js";import{Bl as N$}from"./chunk-mbfjxyq0.js";import{Cl as L6,Dl as c$,El as d$,Fl as x8,Gl as pF,Il as aW,Jl as cF,Tl as A8,Vl as dF,Wl as uF,Xl as lF}from"./chunk-kss2kkmm.js";import{nm as u$}from"./chunk-n26d4z3t.js";import{sm as Z2,xm as W2}from"./chunk-5npzvdh9.js";import{Em as $2,Jm as l}from"./chunk-zez3fjnf.js";import{Km as j3,Nm as H}from"./chunk-xac2vwtq.js";import{Vm as s9}from"./chunk-dx4h7rap.js";import{in as p9}from"./chunk-ket76475.js";import{jn as O8,ln as WF}from"./chunk-jzg9zdtj.js";import{qn as J2}from"./chunk-748evey0.js";function V3($){return typeof $==="function"&&$.prototype!==void 0}var f2=Symbol.for("gemi.HttpResponse"),$V=new Set([301,302,303,307,308]);class L1{kind;body;status;headers;[f2]=!0;constructor($,Z,W,Y){this.kind=$;this.body=Z;this.status=W;this.headers=Y}static json($,Z={}){let W=Z.status??200;return w2(W,"json"),new L1("json",$,W,new Headers(Z.headers))}static error($,Z,W={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return L1.json({error:Z},{...W,status:$})}static redirect($,Z={}){let W=Z.status??303;if(!$V.has(W))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${W}.`);let Y=String($);if(Y==="")throw TypeError("HttpResponse.redirect: url is empty.");let J=new Headers(Z.headers);return J.set("Location",Y),new L1("empty",void 0,W,J)}static noContent($={}){return new L1("empty",null,204,new Headers($.headers))}static text($,Z={}){let W=Z.status??200;return w2(W,"text"),new L1("text",$,W,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let W=$,Y=this.serialize(W);for(let J of Z)W.append("Set-Cookie",J);this.headers.forEach((J,j)=>{if(j.toLowerCase()!=="set-cookie")W.set(j,J)});for(let J of this.headers.getSetCookie())W.append("Set-Cookie",J);if(this.status>=400&&!this.headers.has("Cache-Control"))W.set("Cache-Control","no-store");return new Response(Y,{status:this.status,headers:W})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function w2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function r1($){return typeof $==="object"&&$!==null&&$[f2]===!0}function ZV($,Z,W={}){return L1.error($,Z,W)}function v0($){return typeof $==="string"?[$]:$}function F6($,Z){let W=$.split(/[\\/]/).pop()??"",Y=Z?"attachment":"inline",J=W.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${Y}; filename="${J}"; filename*=UTF-8''${encodeURIComponent(W)}`}function WV($){return"total"in $&&"partial"in $&&"body"in $}function q2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function U3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":w8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function YV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(WV($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,W=Z instanceof Blob?Z:null,Y=$.total??W?.size??-1;return{body:Z,start:$.start??0,end:$.end??Y-1,total:Y,partial:$.partial??!1,type:$.type??W?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function f8($,Z){if($ instanceof Response)return $;if(!$)return q2();let W=await YV($),{body:Y,start:J,end:j,total:z,partial:X}=W;if(!X&&Y instanceof Blob&&"exists"in Y&&typeof Y.exists==="function"){if(!await Y.exists())return q2()}let{range:G}=Z;if(G){if(z<=0)return U3(Math.max(z,0));if(!X){if(Y instanceof Blob){let B=R8(G,z);if(!B)return U3(z);Y=Y.slice(B.start,B.end+1),J=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:W.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",W.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",k8(J,j,z)),V.set("Content-Length",String(j-J+1));else if(z>=0)V.set("Content-Length",String(z));if(W.name)V.set("Content-Disposition",F6(W.name,W.download));if(W.etag)V.set("ETag",W.etag);if(W.lastModified)V.set("Last-Modified",W.lastModified.toUTCString());for(let[B,U]of Object.entries(W.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(Y&&"cancel"in Y&&typeof Y.cancel==="function")await Y.cancel();return new Response(null,{status:F,headers:V})}return new Response(Y,{status:F,headers:V})}var JV=["content-type"];var v2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function jV($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function D3($,Z){let W=(J)=>{throw Error(`CORS policy on ${Z}: ${J}`)};if($===null||typeof $!=="object")W('expected an object such as { origins: "*" } or `false`.');let Y=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(Y!=="*"){if(!Array.isArray(Y)||Y.length===0)W('`origins` must be "*", an origin or a non-empty list of origins.');for(let J of Y){if(J==="*")W('"*" goes on its own (`origins: "*"`), not in a list.');if(J!=="null"&&!jV(J))W(`"${J}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(Y==="*")W("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(Y.includes("null"))W('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let J of $.methods??[])if(!v2.test(J))W(`"${J}" is not a method.`);for(let J of[...$.headers??[],...$.exposeHeaders??[]])if(!v2.test(J))W(`"${J}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))W("`maxAge` must be a whole number of seconds.");return{...$,origins:Y}}function y2($,Z){return $.origins==="*"||$.origins.includes(Z)}function zV($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function m2($,Z,W){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":W),zV(Z,W))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function h2($,Z){let W=($.get("Vary")??"").split(",").map((J)=>J.trim()).filter(Boolean);if(W.includes("*"))return;let Y=W.map((J)=>J.toLowerCase());for(let J of Z)if(!Y.includes(J.toLowerCase()))W.push(J);$.set("Vary",W.join(", "))}function g2($,Z,W){if(Z.origins!=="*")h2($,["Origin"]);if(!W||!y2(Z,W))return;if(m2($,Z,W),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function p2($,Z,W){let Y=W.headers.get("Origin");try{return g2($.headers,Z,Y),$}catch{let J=new Headers($.headers);return g2(J,Z,Y),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}function c2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function d2($,Z){let W=new Headers,Y=$.headers.get("Origin"),J=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[J];if(h2(W,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!Y||!y2(j,Y))return new Response(null,{status:204,headers:W});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(J))return new Response(null,{status:204,headers:W});let G=(j.headers??JV).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:W});if(m2(W,j,Y),W.set("Access-Control-Allow-Methods",X.join(", ")),G.length)W.set("Access-Control-Allow-Headers",G.join(", "));return W.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:W})}function XV($){return V3($)}function u2($,Z){if($.length===0)return $();return $(Z??new S)}class d{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,W){this.method=$;this.handler=Z;this.methodName=W;this.handler=Z,this.methodName=W,this.method=$}get source(){if(!XV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return u2(Z[this.methodName].bind(Z),$)}return u2(this.handler,$)}middleware($){return this.middlewares=v0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:D3($,`a ${this.method} route`),this}}class n2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=v0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:D3($,"a proxy route"),this}async run(){let $=new S,Z=$.headers.toJSON();for(let W of l2($.rawRequest))delete Z[W];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(W){if(s2($.rawRequest))throw new g8(i2($.rawRequest));throw W}}}class o2{constructor(...$){return new d(...$)}}class a2 extends d{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),W=Z?.req?.rawRequest,Y=v8(W?.headers.get("Range"));if(Z)Z.rangeRequest=Y;try{let J=await super.run($);if(r1(J))return J;return await f8(J,{range:Y,method:W?.method})}catch(J){if(J instanceof y8)return U3(J.total);throw J}finally{if(Z)Z.rangeRequest=null}}}class t2{constructor(...$){return new a2(...$)}}class r2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new d("GET",$,"list"),post:new d("POST",$,"store")},this.second={get:new d("GET",$,"show"),put:new d("PUT",$,"update"),delete:new d("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class A0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new d("GET",$,Z)}post($,Z){return new d("POST",$,Z)}put($,Z){return new d("PUT",$,Z)}patch($,Z){return new d("PATCH",$,Z)}delete($,Z){return new d("DELETE",$,Z)}resource($){return new r2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${q8($)}.`);return GV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${q8($)}.`);return QV($)}file($,Z){return new o2("GET",$,Z)}stream($,Z){return new t2("GET",$,Z)}proxy($,Z={}){return new n2($,Z)}mcp($){let Z=$.__routes;if($.__brand!=="McpEndpoint"||typeof Z!=="function")throw TypeError(`this.mcp() takes an McpEndpoint class, and got ${q8($)}.`);return Z.call($)}}function q8($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function GV($){let Z={stream:new d("POST",$,"stream"),attach:new d("POST",$,"attach"),watch:new d("POST",$,"watch"),stop:new d("POST",$,"stop"),upload:new d("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends A0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(Y){if(Y.stream)Z.stream.middleware(Y.stream);if(Y.attach)Z.attach.middleware(Y.attach),Z.watch.middleware(Y.attach);if(Y.stop)Z.stop.middleware(Y.stop);if(Y.upload)Z.upload.middleware(Y.upload);return this}}}function QV($){let Z={start:new d("POST",$,"voiceStart"),update:new d("PATCH",$,"voiceUpdate"),end:new d("DELETE",$,"voiceEnd")};return class extends A0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(Y){if(Y.start)Z.start.middleware(Y.start);if(Y.update)Z.update.middleware(Y.update);if(Y.end)Z.end.middleware(Y.end);return this}}}var e1="access_token";function w$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function V6($,Z){let W=w$(Z);if(!W)return null;return(await $.getSession(W,Z.headers.get("User-Agent")))?.user??null}var BV=/^[A-Za-z0-9_-]+$/,FV=/^:[A-Za-z_][A-Za-z0-9_]*$/,e2=/^[A-Za-z0-9_-]{1,128}$/,VV=/^[A-Za-z0-9_.:-]+$/;class s extends Error{constructor($){super($);this.name="InvalidChannelError"}}function $Y($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function TZ($){if(typeof $!=="string"||$.length===0)throw new s("A channel pattern must be a non-empty string.");if($.length>255)throw new s(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),W=new Set;for(let Y of Z){if(FV.test(Y)){let J=Y.slice(1);if(W.has(J))throw new s(`The channel pattern "${$}" names the param "${J}" twice.`);W.add(J);continue}if(Y.startsWith("__"))throw new s(`The channel "${$}" has the segment "${Y}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!BV.test(Y))throw new s(`The channel pattern "${$}" has an invalid segment "${Y}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function O3($,Z={}){let W=TZ($),Y=new Set,J=W.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);Y.add(z);let X=Z[z];if(X===void 0||X===null)throw new s(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!e2.test(G))throw new s(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!Y.has(j))throw new s(`The channel "${$}" has no param "${j}".`);if(J.length>255)throw new s(`The topic built from "${$}" is longer than 255 characters.`);return J}function m8($){if(TZ($).some((W)=>W.startsWith(":")))throw new s(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function ZY($){if(typeof $!=="string"||$.length===0||$.length>64||!VV.test($))throw new s(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function WY($,Z){if($===Z)return!0;if($===O0)return Z.startsWith(`${O0}.`)&&Z.split(".").length===2;let W=$.split("."),Y=Z.split(".");if(W.length!==Y.length)return!1;return W.every((J,j)=>J===Y[j]||J.startsWith(":")&&e2.test(Y[j]))}var O0="user";function KZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return O3(`${O0}.:id`,{id:Z})}class W0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class D6 extends W0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let W=Z==="upload"?this.config.uploadLimit??f$("50mb"):f$(Z);return U6(this.req.rawRequest,W),{}}}function YY($){let Z=new Map;for(let W of $)if(typeof W==="string"){let[Y,J=""]=W.split(":");if(Y.startsWith("-")){if(Z.has(Y.replace("-","")))Z.delete(Y.replace("-",""))}else Z.set(Y,J.split(",").filter(Boolean))}else Z.set(W,[]);return Z}function UV($){return{"body-limit":D6.configure({uploadLimit:$})}}class $${config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:f$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=f$($.uploadBodyLimit??"50mb"),this.builtinAliases=UV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||jY($))return;let W=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;U6($,W,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}resolve($){let Z=this.aliases,W=[];for(let[Y,J]of YY($).entries())if(typeof Y==="string"){if(Z[Y])W.push({Middleware:Z[Y],params:J})}else if(V3(Y))W.push({Middleware:Y,params:[]});return W}runMiddleware($){let Z=new S,W=this.aliases,Y=[];for(let[J,j]of YY($).entries())if(typeof J==="string"){let z=W[J];if(z){let X=new z(Z);Y.push({run:()=>X.run.call(X,...j),runsOnRefusal:JY(z)})}}else if(V3(J)){let z=new J(Z);Y.push({run:z.run.bind(z),runsOnRefusal:JY(J)})}else Y.push({run:J,runsOnRefusal:!1});return(async()=>{let J={};for(let j=0;j<Y.length;j++)try{J={...J,...await Y[j].run()}}catch(z){throw await DV(Y.slice(j+1)),z}return J})()}}function JY($){return $?.runsOnRefusal===!0}async function DV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(W){console.error(W)}}}class O6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...v0($)],this}events(...$){return this}}class QY{static __brand="ChannelRouter";channels={};public(){return new O6("public")}private($){return new O6("private",$)}async authorize($,Z,W={},Y={}){try{HV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let J=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!BY(J))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===O0){if(Object.keys(W??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=O3(Z,W??{})}catch(G){if(G instanceof s)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(W??{}).map(([G,Q])=>[G,String(Q)])),X=new S($,z,"api",Z);return P.exit(()=>L6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(J.middlewares.length>0)await H($$).runMiddleware(J.middlewares);if(Z===O0){let Q=await zY(X);if(!Q)return{ok:!1,code:"denied"};if(j=KZ(Q),J.visibility==="private"&&J.authorizer){if(await XY(J.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(J.visibility==="private"){if((J.authorizer?await XY(J.authorizer,X,z):await zY(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(MV(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},Y.carried)))}}async function OV($,Z,W={},Y={}){let J=typeof $==="function"?new $:$;FY(J);let j=Y.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await J.authorize(z,Z,W,{carried:X})).ok}function BY($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function zY($){if(!P.getStore().user&&w$($)===null)return null;try{return await g0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function XY($,Z,W){if(LV($))return new $().authorize(Z,W);return $(Z,W)}function LV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function MV($){return $?.kind===Z$||W$($)||q$($)}var GY=new WeakSet;function HV($){if(GY.has($))return;FY($),GY.add($)}function FY($){let Z=Object.entries($.channels),W=[];for(let[Y,J]of Z){if(!BY(J))throw new s(`The channel "${Y}" is not declared with this.public() or this.private().`);let j=TZ(Y);if(j[0].startsWith(":"))throw new s(`The channel pattern "${Y}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(Y!==O0&&j.length===2&&j[0]===O0)throw new s(`The channel pattern "${Y}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(Y!==O0&&J.visibility==="private"&&!J.authorizer&&j.some((z)=>z.startsWith(":")))throw new s(`The private channel "${Y}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);W.push({pattern:Y,segments:Y===O0?[O0,":id"]:j})}for(let Y=0;Y<W.length;Y++)for(let J=Y+1;J<W.length;J++)if(TV(W[Y].segments,W[J].segments))throw new s(`The channel patterns "${W[Y].pattern}" and "${W[J].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function TV($,Z){if($.length!==Z.length)return!1;return $.every((W,Y)=>W===Z[Y]||W.startsWith(":")||Z[Y].startsWith(":"))}class h8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,W){this.as=$;this.input=Z;this.bind=W}}class M6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,W){this.method=$;this.url=Z;this.meta=W}}class p8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function KV($){let Z=[],W="";for(let Y of $)if(Y==="_"||Y==="-"||Y===" "){if(W)Z.push(W);W=""}else if(Y===Y.toLowerCase())W+=Y;else{if(W)Z.push(W);W=Y.toLowerCase()}if(W)Z.push(W);return Z}function PV($,Z){let W=KV($);if(Z==="snake")return W.join("_");if(Z==="kebab")return W.join("-");return W.map((Y,J)=>J===0?Y:Y[0].toUpperCase()+Y.slice(1)).join("")}class VY{static __brand="McpRouter";routes={};scopes;param($){return new h8($.as,$.input,$.bind)}fromTool($,Z={}){return new p8($,Z)}fromApiRoute($,Z,W){return new M6($,Z,W)}fromApiRouteFor($,Z,W){let{name:Y,audiences:J,description:j,params:z,files:X,...G}=W,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(J??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...K}=J[U],N=O??(D?PV(Y,D):Y);if(B.has(N))throw Error(`${Q}: the audiences "${B.get(N)}" and "${U}" are both named "${N}". Give one its own name or casing.`);B.set(N,U);let _=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof _!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let x={...G,...K,description:_};if(z||M)x.params={...z,...M};if(X||T)x.files={...X,...T};V[N]=new M6($,Z,x)}return V}}var NV="Rate limit exceeded";class M1 extends y0{result;retryAfter;constructor($,Z=NV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let W={"Content-Type":"application/json",...$?c8($):{}};this.payload={api:{status:429,data:{error:{...Y$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:W},view:{error:{message:Z},status:429,headers:W}}}}function c8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class m0{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let W=Z.limit??this.config.limit,Y=Z.window??this.config.window,J=Z.cost??1;if(UY("window",Y),UY("limit",W),!Number.isFinite(J)||J<0)throw Error(`Rate limiter cost must be zero or greater, got ${J}`);return await this.config.driver.consume({key:$,limit:W,window:Y*1000,cost:J})}async enforce($,Z={},W){let Y=await this.consume($,Z);if(!Y.allowed)throw new M1(Y,typeof W==="function"?W(Y):W);return Y}}function UY($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}async function d8($,Z){let W=_V();if(!W)return null;let Y=await W.consume($,Z);return Y.allowed?null:Math.max(1,Math.ceil(Y.retryAfter/1000))}function _V(){try{let $=H();return $.bound(m0)?$.make(m0):null}catch{return null}}var DY=["2026-07-28"],H6=["2025-11-25","2025-06-18","2025-03-26"],T6=[...DY,...H6],OY="io.modelcontextprotocol/protocolVersion",eT="io.modelcontextprotocol/clientCapabilities";var LY="io.modelcontextprotocol/serverInfo",z0={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class o extends Error{code;data;status;constructor($,Z,W,Y=200){super(Z);this.code=$;this.data=W;this.status=Y;this.name="JsonRpcError"}}function k1($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function MY($){if(Array.isArray($))throw new o(z0.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new o(z0.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,W=Z.id,Y=typeof W==="string"||typeof W==="number"&&Number.isFinite(W);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new o(z0.InvalidRequest,"params must be an object.",void 0,400);if(W===void 0)return{kind:"notification",message:Z};if(!Y)throw new o(z0.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(Y&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new o(z0.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function $K($,Z){let W=$.outputSchema?.toJSONSchema(),Y={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...W&&(Z||W.type==="object")?{outputSchema:W}:{},...Object.keys(Y).length>0?{annotations:Y}:{}}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function IV($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let W=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(W)}catch{return null}}function HY($,Z,W){if(!DY.includes(W))throw new o(z0.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:T6,requested:W},400);let Y=(z)=>new o(z0.HeaderMismatch,`Header mismatch: ${z}`,void 0,400);if($.headers.get("mcp-protocol-version")!==W)throw Y("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw Y("Mcp-Method does not match the method.");let J=Z.params??{},j=Z.method==="tools/call"||Z.method==="prompts/get"?J.name:Z.method==="resources/read"?J.uri:void 0;if(j!==void 0){let z=$.headers.get("mcp-name");if(z===null||IV(z)!==j)throw Y("Mcp-Name does not match the request's name.")}}import{isIP as K6}from"net";function J$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let Y=Z.indexOf("]");if(Y<0)return null;let J=Z.slice(Y+1);if(J!==""&&!/^:\d{1,5}$/.test(J))return null;let j=Z.slice(1,Y);return K6(j)===6?j:null}if(K6(Z))return Z;let W=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return W&&K6(W[1])===4?W[1]:null}function TY($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let W=J$($);if(W===null||K6(W)===4)return W??$;let Y=CV(W);if(Y===null)return $;if(Y.slice(0,5).every((z)=>z===0)&&Y[5]===65535)return`${Y[6]>>8}.${Y[6]&255}.${Y[7]>>8}.${Y[7]&255}`;let J=Y.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=xV(J);return Z===128?j:`${j}/${Z}`}function CV($){let Z=$.split("%")[0].toLowerCase(),W=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(W){let[Q,F,V,B]=W.slice(1).map(Number);Z=`${Z.slice(0,W.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[Y,J]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(Y),X=J===void 0?[]:j(J),G=J===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function xV($){let Z=-1,W=0;for(let J=0;J<8;J++){if($[J]!==0)continue;let j=J;while(j<8&&$[j]===0)j++;if(j-J>W)Z=J,W=j-J;J=j}let Y=$.map((J)=>J.toString(16));if(W<2)return Y.join(":");return`${Y.slice(0,Z).join(":")}::${Y.slice(Z+W).join(":")}`}class _Y extends W0{static isRateLimit=!0;async run($,Z){let W=AV();if(!W)return{};let Y=await W.consume(this.key(),{limit:KY($)??this.config.limit,window:KY(Z)??this.config.window});if(this.config.headers!==!1){let J=this.req.ctx?.();if(J)for(let[j,z]of Object.entries(c8(Y)))J.setHeaders(j,z)}if(!Y.allowed)throw new M1(Y);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=PY(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${v$(this.req)}:${this.req.routePath??"*"}`}}function AV(){try{let $=H();return $.bound(m0)?$.make(m0):null}catch{return null}}function P6($){let Z=NY($.rawRequest);if(Z!==void 0)return Z;let W=$.headers.get("x-forwarded-for");if(W){let[Y]=W.split(",");if(Y?.trim())return J$(Y)??Y.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function v$($,Z){return TY(P6($),Z)}function KY($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}var SV={token:"router.domains"},bV={token:"middleware"},EV={limit:600,window:60},RV=1048576,IY=/^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/,kV=/^[A-Za-z0-9_.-]{1,128}$/;class L3 extends Error{code;status;data;headers;constructor($,Z,W={}){super(Z);this.code=$;this.name="McpEndpointError",this.status=W.status??200,this.data=W.data,this.headers=W.headers}}var AY=Symbol("McpEndpoint.result");class SY{static __brand="McpEndpoint";server;rateLimit;maxBodyBytes;tool($){return $}static result($,Z={}){return{[AY]:!0,body:$,isError:Z.isError===!0,text:Z.text}}static __routes(){let $=new this;return $.check(this.name||"McpEndpoint"),new u8($)}checked;check($){if(this.checked=$,this.caller!=="anonymous")throw Error(`${$}: set \`caller = "anonymous" as const\` to serve this endpoint to anyone. It is required: an endpoint that names no caller would be open without anybody having said so.`);if(!o0(this.tools))throw Error(`${$}: tools must be an object of tools, by name.`);for(let[Z,W]of Object.entries(this.tools)){let Y=`${$}: tool "${Z}"`;if(!kV.test(Z))throw Error(`${Y}: a tool name is 1 to 128 letters, digits, "_", "-" or ".".`);if(!o0(W)||typeof W.run!=="function"||typeof W.description!=="string")throw Error(`${Y} needs a description and a run().`);if(!o0(W.inputSchema))throw Error(`${Y}: inputSchema must be an s schema or a JSON Schema object.`);if(W.offered!==void 0&&typeof W.offered!=="function")throw Error(`${Y}: offered must be a function.`);let J=W.rateLimit;if(typeof J==="string"){if(!IY.test(J))throw Error(`${Y}: rateLimit "${J}" is not "METHOD /path", like "POST /orders".`)}else if(J!==void 0&&!xY(J))throw Error(`${Y}: rateLimit must be "METHOD /path" or { limit, window } in positive numbers.`)}if(this.rateLimit!==void 0&&this.rateLimit!==!1&&!xY(this.rateLimit))throw Error(`${$}: rateLimit must be { limit, window } in positive numbers, or false.`)}async __post($){let Z=$.rawRequest,W=this.rateLimit===!1?null:this.rateLimit??EV;if(W){let G=await d8(`mcp-endpoint:${v$($)}:${$.routePath??"*"}`,W);if(G!==null)return w1(k1(null,new o(z0.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String(G)})}if(!/^application\/json\s*(;|$)/i.test(Z.headers.get("content-type")??""))return new Response("Content-Type must be application/json.",{status:415,headers:{"Cache-Control":"no-store"}});let Y=Z.headers.get("mcp-protocol-version");if(Y!==null&&!T6.includes(Y))return w1(k1(null,new o(z0.InvalidRequest,`Unsupported MCP-Protocol-Version: ${Y.slice(0,40)}`)),400);let J=this.context?await this.context($):void 0;if(J instanceof Response)return J;if(J===null||this.context&&J===void 0)return w1(k1(null,new o(z0.InvalidRequest,"Not found.")),404);let j,z=this.maxBodyBytes??RV;try{j=JSON.parse(await qV(Z,z))}catch(G){if(G instanceof N6)return w1(k1(null,new o(z0.InvalidRequest,`The request is larger than ${z} bytes.`)),413);return w1(k1(null,new o(z0.ParseError,"Parse error.")),400)}let X=o0(j)&&(typeof j.id==="string"||typeof j.id==="number")?j.id:null;try{return await this.dispatch($,J,j)}catch(G){if(G instanceof L3)return w1(k1(X,new o(G.code,G.message,G.data)),G.status,G.headers);if(G instanceof o)return w1(k1(X,G),G.status);return console.error(`[gemi/mcp] ${this.checked} failed:`,G),w1(k1(X,new o(z0.InternalError,"Internal error.")),500)}}async dispatch($,Z,W){let Y=MY(W);if(Y.kind!=="request")return new Response(null,{status:202});let{message:J}=Y,j=J.params??{},z=o0(j._meta)?j._meta:{},X=z[OY],G=typeof X==="string";if(G)HY($.rawRequest,J,X);let Q=await this.answer($,Z,J.method,j,z,G);return w1({jsonrpc:"2.0",id:J.id,result:G?this.complete(Q):Q},200)}async answer($,Z,W,Y,J,j){switch(W){case"initialize":{if(j)break;let z=Y.protocolVersion;return{protocolVersion:H6.includes(z)?z:H6[0],capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo(),...this.server?.instructions?{instructions:this.server.instructions}:{}}}case"server/discover":if(!j)break;return{supportedVersions:T6,capabilities:{tools:{}},...this.server?.instructions?{instructions:this.server.instructions}:{}};case"ping":return{};case"tools/list":{let z=[];for(let[X,G]of Object.entries(this.tools))if(await this.offers(G,Z,$))z.push(wV(X,G));return j?{tools:z,ttlMs:60000,cacheScope:"private"}:{tools:z}}case"tools/call":return await this.call($,Z,Y,J)}throw new o(z0.MethodNotFound,`Method not found: ${W.slice(0,100)}`)}async call($,Z,W,Y){let J=W.name,j=typeof J==="string"&&Object.hasOwn(this.tools,J)?this.tools[J]:void 0;if(!j||!await this.offers(j,Z,$))throw new o(z0.InvalidParams,`Unknown tool: ${String(J).slice(0,100)}`);let z=await this.spend($,J,j);if(z!==null)throw new L3(-32000,"Rate limit exceeded",{status:429,data:{retry_after:z},headers:{"Retry-After":String(z)}});let X=W.arguments===void 0?{}:W.arguments;if(!o0(X))throw new o(z0.InvalidParams,"arguments must be an object.");if(bY(j.inputSchema)){let Q=j.inputSchema.safeParse(X);if(Q.ok===!1)return{content:[{type:"text",text:`Invalid arguments for "${J}": ${Q.errors.join(", ")}`}],isError:!0};X=Q.value}let G;try{G=await j.run(X,{context:Z,req:$,tool:J,meta:Y,signal:$.rawRequest.signal})}catch(Q){if(Q instanceof L3||Q instanceof o)throw Q;return console.error(`[gemi/mcp] ${this.checked}: "${J}" failed:`,Q),{content:[{type:"text",text:`"${J}" failed on the server.`}],isError:!0}}return fV(G)}async offers($,Z,W){return $.offered?await $.offered(Z,W)===!0:!0}async spend($,Z,W){let Y=W.rateLimit;if(Y===void 0)return null;if(typeof Y!=="string")return await d8(`mcp-endpoint-tool:${v$($)}:${$.routePath??"*"}:${Z}`,Y);let[,J,j]=IY.exec(Y),z=this.twinLimits($,Z,J,j);if(z.length===0)return null;let X=new S($.rawRequest,{},"api",j);try{await P.run(X,async()=>{for(let{Middleware:G,params:Q}of z)await new G(X).run(...Q)})}catch(G){if(G instanceof M1||G?.name==="RateLimitExceededError"){let Q=G.retryAfter??1000;return Math.max(1,Math.ceil(Q/1000))}throw G}return null}twinLimits($,Z,W,Y){let j=H(SV).dispatchers($.domain).api.flatRoutes[Y]?.[W];if(!j)throw Error(`${this.checked}: tool "${Z}" spends the rate limits of ${W} ${Y}, and this host's api has no such route. Name the route by its full path, without /api.`);return H(bV).resolve(j.middleware).filter(({Middleware:z})=>z.isRateLimit===!0)}serverInfo(){return{name:this.server?.name??"gemi",version:this.server?.version??"1.0.0"}}complete($){return{resultType:"complete",...$,_meta:{[LY]:this.serverInfo()}}}}class u8{post;get;delete;constructor($){this.post=new d("POST",(W)=>$.__post(W));let Z=(W)=>new Response(null,{status:405,headers:{Allow:"POST","Cache-Control":"no-store"}});this.get=new d("GET",Z),this.delete=new d("DELETE",Z)}middleware($){let Z=v0($);for(let W of[this.post,this.get,this.delete])W.middleware(Z);return this}cors($){for(let Z of[this.post,this.get,this.delete])Z.cors($);return this}}function wV($,Z){return{name:$,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:bY(Z.inputSchema)?Z.inputSchema.toJSONSchema():Z.inputSchema,...Z.outputSchema?{outputSchema:Z.outputSchema}:{},...Z.annotations||Z.title?{annotations:{...Z.title?{title:Z.title}:{},...Z.annotations}}:{}}}function fV($){if(o0($)&&$[AY]===!0){let Z=$;return{content:[{type:"text",text:Z.text??CY(Z.body)}],...o0(Z.body)?{structuredContent:Z.body}:{},isError:Z.isError}}if(typeof $==="string")return{content:[{type:"text",text:$}],isError:!1};return{content:[{type:"text",text:CY($)}],...o0($)?{structuredContent:$}:{},isError:!1}}function CY($){return typeof $==="string"?$:JSON.stringify($??null)}function bY($){return o0($)&&typeof $.safeParse==="function"&&typeof $.toJSONSchema==="function"}function xY($){return o0($)&&typeof $.limit==="number"&&$.limit>0&&Number.isFinite($.limit)&&typeof $.window==="number"&&$.window>0&&Number.isFinite($.window)}class N6 extends Error{}async function qV($,Z){let W=Number($.headers.get("content-length"));if(Number.isFinite(W)&&W>Z)throw new N6;if(!$.body)return"";let Y=$.body.getReader(),J=[],j=0;for(;;){let{done:z,value:X}=await Y.read();if(z)break;if(j+=X.byteLength,j>Z)throw await Y.cancel(),new N6;J.push(X)}return Buffer.concat(J).toString("utf8")}function w1($,Z,W={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...W}})}function L0($,Z){return $.replace(/:([^/]+[*?]?)/g,(W,Y)=>{let J=Y.endsWith("?")||Y.endsWith("*"),j=J?Y.slice(0,-1):Y,z=Z[j];if(z===void 0){if(J)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class l8 extends y0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class f1{static to($,...Z){let[W={}]=Z,{search:Y={},params:J={},permanent:j,status:z}={params:{},status:307,permanent:!1,...W},X=new URLSearchParams(Y).toString();throw new l8([L0($,J)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new l8($,Z)}}class EY{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,W]=$;this.handler=(Y)=>{return new Z()[W](Y)}}}async run($,Z){let{destination:W,permanent:Y=!1,status:J=307}=await this.handler($);if(!W)throw Error(`Redirect destination is required see ${Z}`);return f1.to(W,{permanent:Y,status:J}),{}}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function i8($,Z){if($ instanceof Response)return $;let W=$ instanceof Blob,Y=W?$:$.file,J=W?$.name:$.name??$.file?.name,j=(W?$.type:$.type??$.file?.type)||"",z=W?!1:$.download??!1,X=W?200:$.status??200;if(!W)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(Y instanceof Blob&&"exists"in Y&&typeof Y.exists==="function"){if(!await Y.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),Y instanceof Blob)Z.set("Content-Length",String(Y.size));if(J)Z.set("Content-Disposition",F6(J,z));return new Response(Y instanceof Blob?Y.stream():Y,{status:X,headers:Z})}class RY{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,W]=$;this.handler=(Y)=>{return new Z()[W](Y)}}}async run($,Z){let W=await this.handler($);if(!W)throw Error(`File route handler must return a file see ${Z}`);return{FILE:W}}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function kY($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class wY{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[W,Y]=Z;this.handler=(J)=>{return new W()[Y](J)}}}async run($,Z){let W=kY(await this.handler($),this.viewPath);return{[this.viewPath]:{...W,breadcrumb:{label:W?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=v0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class fY{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,W){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends q1{routes=W??{}};else if(Array.isArray(Z)){let[Y,J]=Z;this.handler=(j)=>{return new Y()[J](j)},this.children=class extends q1{routes=W??{}}}else this.children=class extends q1{routes=Z},this.handler=()=>({})}async run($,Z){let W=kY(await this.handler($),this.viewPath);return{[this.viewPath]:{...W,breadcrumb:{label:W?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class q1{middlewares=[];featureGates=[];routes={};view($,Z){return new wY($,Z)}file($){return new RY($)}redirect($){return new EY($)}layout($,Z,W){return new fY($,Z,W)}}function vV($){return $}function gV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var a0="redirect";function H1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let W=new URL($,"http://gemi.invalid");if(W.origin!=="http://gemi.invalid")return Z;let Y=`${W.search}${W.hash}`.replaceAll("/","%2F"),J=`${W.pathname}${Y}`.replaceAll(":","%3A");return J.startsWith("//")?Z:J}catch{return Z}}function PZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function s8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function yV($,Z=!0){let W=new URL($.rawRequest.url),Y=W.pathname.replace(/\.(json|og)$/,""),[,J,...j]=Y.split("/");if(H(l).supportedLocales.includes(J))Y=`/${j.join("/")}`;return Z?`${Y}${W.search}`:Y}function mV($,Z){let W=(Y)=>Y.replace(/\/+$/,"")||"/";return W($)===W(Z)}function _6($,Z){let W=Z||H(R).config.signInPath,Y=/^[a-z][a-z\d+.-]*:/i.test(W);if(Y?!/^https?:\/\//i.test(W):!W.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${W}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let J=new URL(W,"http://gemi.invalid");if($?.kind==="view"){let j=yV($,!Y);if(Y||!mV(new URL(j,J).pathname,J.pathname))J.searchParams.set(a0,j)}return Y?J.href:`${J.pathname}${J.search}`}class qY extends W0{async run($){let Z=P.getStore(),W=Z.req;if(Z.user)return{};let Y=await V6(H(R),W);if(!Y)throw new g$({redirectTo:_6(W,$)});return Z.setUser(Y),{}}}var o8="gemi_same_site",n8="private, no-cache, no-store, max-age=0, must-revalidate";class I6 extends W0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let W=Z.rawRequest;if(Z.kind!=="view"||W.method!=="GET"&&W.method!=="HEAD")return{};let Y=new URL(W.url);if(/\.(json|og)$/.test(Y.pathname))return{};if(Y.searchParams.has(o8))return{};if(w$(Z))return{};let J=W.headers.get("Sec-Fetch-Site");if(J&&J!=="cross-site")return{};throw Y.searchParams.set(o8,"1"),new vY(`${Y.pathname}${Y.search}`)}}class vY extends y0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=hV($),W={"Content-Type":"text/html; charset=utf-8","Cache-Control":n8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":n8}},viewData:{status:200,data:{},headers:{"Cache-Control":n8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:W,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function hV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class gY extends W0{async run(...$){let[Z="public",W="864000",...Y]=$,J=`${Z}, max-age=${W}${Y.length>0?", ":""}${Y.join(", ")}`;if($.length===0)J="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")J="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")J="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",J);return{}}}var yY={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class mY extends W0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let W={...yY,...this.config.origins[Z]};if(Z==="null")delete W["Access-Control-Allow-Credentials"];for(let[Y,J]of Object.entries(W))$.ctx().setHeaders(Y,J)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let W={...yY,...this.config.origins["*"]};delete W["Access-Control-Allow-Credentials"];for(let[Y,J]of Object.entries(W))$.ctx().setHeaders(Y,J)}return{}}}class pY extends W0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new a8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new a8;return{}}}class a8 extends y0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:hY("csrf","Invalid CSRF token",403)}},view:{}}}class cY{policiesList={};constructor(){let $=this.register();for(let Z of $){let W=new Z;this.policiesList[Z.name]=W}}register(){return[]}}class dY{all($,Z){return!0}}class t8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new NZ:new C6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let W=this.answers.get($.rawRequest);if(!W)W=new Map,this.answers.set($.rawRequest,W);let Y=W.get(Z);if(!Y)Y=this.decide($,Z),W.set(Z,Y);return Y}async allows($,Z){try{return await this.authorize($,Z),!0}catch(W){if(this.isRefusal(W))return!1;throw W}}fromRoute($=new S,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,W)=>this.fromRoute(Z,W||void 0);this.middlewareClass=class extends W0{async run(W){await $(this.req,W)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:W,body:Y})=>{let J;if(W!==void 0){if(J=$.thread?await $.thread(W,Z):null,J===null||J===void 0)throw this.refusal()}if(Y!==void 0){let j=await $.body(Y,Z);if(await this.authorize(Z,j),W!==void 0&&String(J)!==String(j))throw this.refusal();return}if(W!==void 0)await this.authorize(Z,J)}}}async decide($,Z){let W=await this.options.load(Z,$);if(W===null||W===void 0||!await this.options.allow(W,$))throw this.refusal();return W}isRefusal($){return this.refuse==="forbidden"?$ instanceof NZ:$ instanceof C6}}function pV($){return new t8($)}async function S6($,Z,W=!1){if(!$.body)return new Uint8Array;let[Y,J]=await $U($.body),z=Y.length>=2&&Y[0]===31&&Y[1]===139?J.pipeThrough(new DecompressionStream("gzip")):J;return eV(z,Z,W,$.url)}async function eV($,Z,W,Y){let J=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await J.read();if(Q)break;if(z+F.byteLength>Z){if(!W)throw new A6(Y,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{J.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function $U($){let Z=$.getReader(),W=await Z.read(),Y=W.done?new Uint8Array:W.value,J=new ReadableStream({start(j){if(W.done)j.close();else j.enqueue(Y)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[Y,J]}function b6($){return new TextDecoder("utf-8").decode($)}var ZU={"&":"&","<":"<",">":">",'"':""","'":"'"};function y$($){return $.replace(/[&<>"']/g,(Z)=>ZU[Z])}var WU={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function r8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,W)=>{if(W[0]!=="#")return WU[W]??Z;let Y=W[1]==="x"?parseInt(W.slice(2),16):parseInt(W.slice(1),10);return Y>0&&Y<=1114111?String.fromCodePoint(Y):Z})}function e8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function uY($,Z){let W=$.length,Y=0;while(Y<W){if(Z.stopped?.())return;let J=$.indexOf("<",Y);if(J===-1){Z.text(r8($.slice(Y)));return}if(J>Y)Z.text(r8($.slice(Y,J)));if($.startsWith("<!--",J)){let j=$.indexOf("-->",J+4);if(j===-1)return;Y=j+3}else if($.startsWith("<![CDATA[",J)){let j=$.indexOf("]]>",J+9);if(j===-1)return;Z.text($.slice(J+9,j)),Y=j+3}else if($.startsWith("<?",J)){let j=$.indexOf("?>",J+2);if(j===-1)return;Y=j+2}else if($.startsWith("<!",J)){let j=$.indexOf(">",J+2);if(j===-1)return;let z=$.indexOf("[",J+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;Y=G+1}else Y=j+1}else if($[J+1]==="/"){let j=$.indexOf(">",J+2);if(j===-1)return;Z.close(e8($.slice(J+2,j).trim())),Y=j+1}else{let j=YU($,J+1);if(j===-1)return;let z=$.slice(J+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=e8(z.slice(0,G));if(Q){if(Z.open(Q,JU(z.slice(G)),X),X)Z.close(Q)}Y=j+1}}}function YU($,Z){let W=null;for(let Y=Z;Y<$.length;Y++){let J=$[Y];if(W){if(J===W)W=null}else if(J==='"'||J==="'")W=J;else if(J===">")return Y}return-1}function JU($){let Z={},W=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let Y of $.matchAll(W))Z[e8(Y[1])]=r8(Y[2]??Y[3]??"");return Z}class X0 extends Error{url;status;constructor($,Z=null,W=null){super($);this.url=Z;this.status=W;this.name="SitemapError"}}var oY="http://www.sitemaps.org/schemas/sitemap/0.9",jU="http://www.w3.org/1999/xhtml",W5=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
import{pi as sF}from"./chunk-kjzvrx2p.js";import{Ji as iF}from"./chunk-gmkzq212.js";import{$i as V8,Bj as x6,Hj as A6,Ki as H3,Oi as ZF,Pi as PY,Pj as v1,Qi as NY,Ri as v8,Si as R8,Tj as OZ,Vi as k8,Wi as w8,Xi as tB,Yi as e9,_i as z3,aj as D2,bj as l2,cj as u,ej as g8,fj as f$,gj as jY,hj as i2,ij as s2,jj as U6,kj as S,lj as q9,mj as j5,nj as NZ,oj as y8,pj as C6,rj as g$,sj as j8}from"./chunk-pvs5qjs7.js";import{Vj as Z$,Wj as y0,Xj as Y$,Yj as hY}from"./chunk-2kt5kgaq.js";import{bk as h,ek as CQ,fk as DZ}from"./chunk-gx5yhz2m.js";import{gk as QZ,hk as L2,lk as bJ,mk as U8,nk as P}from"./chunk-vq0gcvcy.js";import{qk as DQ,tk as $6}from"./chunk-cyxsmd4q.js";import{Ak as xF,xk as pJ}from"./chunk-qbm49b1t.js";import{Sk as q$,Xk as W$}from"./chunk-k5vt2kz6.js";import{jl as oG}from"./chunk-8vzxnjp4.js";import{kl as LZ,nl as IF,zl as z6}from"./chunk-z5wwhgsg.js";import{Bl as N$}from"./chunk-mbfjxyq0.js";import{Cl as L6,Dl as c$,El as d$,Fl as x8,Gl as pF,Il as aW,Jl as cF,Tl as A8,Vl as dF,Wl as uF,Xl as lF}from"./chunk-kss2kkmm.js";import{nm as u$}from"./chunk-n26d4z3t.js";import{sm as Z2,xm as W2}from"./chunk-5npzvdh9.js";import{Em as $2,Jm as l}from"./chunk-zez3fjnf.js";import{Km as j3,Nm as H}from"./chunk-xac2vwtq.js";import{Vm as s9}from"./chunk-dx4h7rap.js";import{in as p9}from"./chunk-ket76475.js";import{jn as O8,ln as WF}from"./chunk-jzg9zdtj.js";import{qn as J2}from"./chunk-748evey0.js";function V3($){return typeof $==="function"&&$.prototype!==void 0}var f2=Symbol.for("gemi.HttpResponse"),$V=new Set([301,302,303,307,308]);class L1{kind;body;status;headers;[f2]=!0;constructor($,Z,W,Y){this.kind=$;this.body=Z;this.status=W;this.headers=Y}static json($,Z={}){let W=Z.status??200;return w2(W,"json"),new L1("json",$,W,new Headers(Z.headers))}static error($,Z,W={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return L1.json({error:Z},{...W,status:$})}static redirect($,Z={}){let W=Z.status??303;if(!$V.has(W))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${W}.`);let Y=String($);if(Y==="")throw TypeError("HttpResponse.redirect: url is empty.");let J=new Headers(Z.headers);return J.set("Location",Y),new L1("empty",void 0,W,J)}static noContent($={}){return new L1("empty",null,204,new Headers($.headers))}static text($,Z={}){let W=Z.status??200;return w2(W,"text"),new L1("text",$,W,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let W=$,Y=this.serialize(W);for(let J of Z)W.append("Set-Cookie",J);this.headers.forEach((J,j)=>{if(j.toLowerCase()!=="set-cookie")W.set(j,J)});for(let J of this.headers.getSetCookie())W.append("Set-Cookie",J);if(this.status>=400&&!this.headers.has("Cache-Control"))W.set("Cache-Control","no-store");return new Response(Y,{status:this.status,headers:W})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function w2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function r1($){return typeof $==="object"&&$!==null&&$[f2]===!0}function ZV($,Z,W={}){return L1.error($,Z,W)}function v0($){return typeof $==="string"?[$]:$}function F6($,Z){let W=$.split(/[\\/]/).pop()??"",Y=Z?"attachment":"inline",J=W.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${Y}; filename="${J}"; filename*=UTF-8''${encodeURIComponent(W)}`}function WV($){return"total"in $&&"partial"in $&&"body"in $}function q2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function U3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":w8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function YV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(WV($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,W=Z instanceof Blob?Z:null,Y=$.total??W?.size??-1;return{body:Z,start:$.start??0,end:$.end??Y-1,total:Y,partial:$.partial??!1,type:$.type??W?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function f8($,Z){if($ instanceof Response)return $;if(!$)return q2();let W=await YV($),{body:Y,start:J,end:j,total:z,partial:X}=W;if(!X&&Y instanceof Blob&&"exists"in Y&&typeof Y.exists==="function"){if(!await Y.exists())return q2()}let{range:G}=Z;if(G){if(z<=0)return U3(Math.max(z,0));if(!X){if(Y instanceof Blob){let B=R8(G,z);if(!B)return U3(z);Y=Y.slice(B.start,B.end+1),J=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:W.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",W.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",k8(J,j,z)),V.set("Content-Length",String(j-J+1));else if(z>=0)V.set("Content-Length",String(z));if(W.name)V.set("Content-Disposition",F6(W.name,W.download));if(W.etag)V.set("ETag",W.etag);if(W.lastModified)V.set("Last-Modified",W.lastModified.toUTCString());for(let[B,U]of Object.entries(W.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(Y&&"cancel"in Y&&typeof Y.cancel==="function")await Y.cancel();return new Response(null,{status:F,headers:V})}return new Response(Y,{status:F,headers:V})}var JV=["content-type"];var v2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function jV($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function D3($,Z){let W=(J)=>{throw Error(`CORS policy on ${Z}: ${J}`)};if($===null||typeof $!=="object")W('expected an object such as { origins: "*" } or `false`.');let Y=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(Y!=="*"){if(!Array.isArray(Y)||Y.length===0)W('`origins` must be "*", an origin or a non-empty list of origins.');for(let J of Y){if(J==="*")W('"*" goes on its own (`origins: "*"`), not in a list.');if(J!=="null"&&!jV(J))W(`"${J}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(Y==="*")W("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(Y.includes("null"))W('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let J of $.methods??[])if(!v2.test(J))W(`"${J}" is not a method.`);for(let J of[...$.headers??[],...$.exposeHeaders??[]])if(!v2.test(J))W(`"${J}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))W("`maxAge` must be a whole number of seconds.");return{...$,origins:Y}}function y2($,Z){return $.origins==="*"||$.origins.includes(Z)}function zV($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function m2($,Z,W){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":W),zV(Z,W))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function h2($,Z){let W=($.get("Vary")??"").split(",").map((J)=>J.trim()).filter(Boolean);if(W.includes("*"))return;let Y=W.map((J)=>J.toLowerCase());for(let J of Z)if(!Y.includes(J.toLowerCase()))W.push(J);$.set("Vary",W.join(", "))}function g2($,Z,W){if(Z.origins!=="*")h2($,["Origin"]);if(!W||!y2(Z,W))return;if(m2($,Z,W),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function p2($,Z,W){let Y=W.headers.get("Origin");try{return g2($.headers,Z,Y),$}catch{let J=new Headers($.headers);return g2(J,Z,Y),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}function c2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function d2($,Z){let W=new Headers,Y=$.headers.get("Origin"),J=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[J];if(h2(W,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!Y||!y2(j,Y))return new Response(null,{status:204,headers:W});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(J))return new Response(null,{status:204,headers:W});let G=(j.headers??JV).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:W});if(m2(W,j,Y),W.set("Access-Control-Allow-Methods",X.join(", ")),G.length)W.set("Access-Control-Allow-Headers",G.join(", "));return W.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:W})}function XV($){return V3($)}function u2($,Z){if($.length===0)return $();return $(Z??new S)}class d{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,W){this.method=$;this.handler=Z;this.methodName=W;this.handler=Z,this.methodName=W,this.method=$}get source(){if(!XV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return u2(Z[this.methodName].bind(Z),$)}return u2(this.handler,$)}middleware($){return this.middlewares=v0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:D3($,`a ${this.method} route`),this}}class n2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=v0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:D3($,"a proxy route"),this}async run(){let $=new S,Z=$.headers.toJSON();for(let W of l2($.rawRequest))delete Z[W];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(W){if(s2($.rawRequest))throw new g8(i2($.rawRequest));throw W}}}class o2{constructor(...$){return new d(...$)}}class a2 extends d{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),W=Z?.req?.rawRequest,Y=v8(W?.headers.get("Range"));if(Z)Z.rangeRequest=Y;try{let J=await super.run($);if(r1(J))return J;return await f8(J,{range:Y,method:W?.method})}catch(J){if(J instanceof y8)return U3(J.total);throw J}finally{if(Z)Z.rangeRequest=null}}}class t2{constructor(...$){return new a2(...$)}}class r2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new d("GET",$,"list"),post:new d("POST",$,"store")},this.second={get:new d("GET",$,"show"),put:new d("PUT",$,"update"),delete:new d("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class A0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new d("GET",$,Z)}post($,Z){return new d("POST",$,Z)}put($,Z){return new d("PUT",$,Z)}patch($,Z){return new d("PATCH",$,Z)}delete($,Z){return new d("DELETE",$,Z)}resource($){return new r2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${q8($)}.`);return GV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${q8($)}.`);return QV($)}file($,Z){return new o2("GET",$,Z)}stream($,Z){return new t2("GET",$,Z)}proxy($,Z={}){return new n2($,Z)}mcp($){let Z=$.__routes;if($.__brand!=="McpEndpoint"||typeof Z!=="function")throw TypeError(`this.mcp() takes an McpEndpoint class, and got ${q8($)}.`);return Z.call($)}}function q8($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function GV($){let Z={stream:new d("POST",$,"stream"),attach:new d("POST",$,"attach"),watch:new d("POST",$,"watch"),stop:new d("POST",$,"stop"),upload:new d("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends A0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(Y){if(Y.stream)Z.stream.middleware(Y.stream);if(Y.attach)Z.attach.middleware(Y.attach),Z.watch.middleware(Y.attach);if(Y.stop)Z.stop.middleware(Y.stop);if(Y.upload)Z.upload.middleware(Y.upload);return this}}}function QV($){let Z={start:new d("POST",$,"voiceStart"),update:new d("PATCH",$,"voiceUpdate"),end:new d("DELETE",$,"voiceEnd")};return class extends A0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(Y){if(Y.start)Z.start.middleware(Y.start);if(Y.update)Z.update.middleware(Y.update);if(Y.end)Z.end.middleware(Y.end);return this}}}var e1="access_token";function w$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function V6($,Z){let W=w$(Z);if(!W)return null;return(await $.getSession(W,Z.headers.get("User-Agent")))?.user??null}var BV=/^[A-Za-z0-9_-]+$/,FV=/^:[A-Za-z_][A-Za-z0-9_]*$/,e2=/^[A-Za-z0-9_-]{1,128}$/,VV=/^[A-Za-z0-9_.:-]+$/;class s extends Error{constructor($){super($);this.name="InvalidChannelError"}}function $Y($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function TZ($){if(typeof $!=="string"||$.length===0)throw new s("A channel pattern must be a non-empty string.");if($.length>255)throw new s(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),W=new Set;for(let Y of Z){if(FV.test(Y)){let J=Y.slice(1);if(W.has(J))throw new s(`The channel pattern "${$}" names the param "${J}" twice.`);W.add(J);continue}if(Y.startsWith("__"))throw new s(`The channel "${$}" has the segment "${Y}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!BV.test(Y))throw new s(`The channel pattern "${$}" has an invalid segment "${Y}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function O3($,Z={}){let W=TZ($),Y=new Set,J=W.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);Y.add(z);let X=Z[z];if(X===void 0||X===null)throw new s(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!e2.test(G))throw new s(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!Y.has(j))throw new s(`The channel "${$}" has no param "${j}".`);if(J.length>255)throw new s(`The topic built from "${$}" is longer than 255 characters.`);return J}function m8($){if(TZ($).some((W)=>W.startsWith(":")))throw new s(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function ZY($){if(typeof $!=="string"||$.length===0||$.length>64||!VV.test($))throw new s(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function WY($,Z){if($===Z)return!0;if($===O0)return Z.startsWith(`${O0}.`)&&Z.split(".").length===2;let W=$.split("."),Y=Z.split(".");if(W.length!==Y.length)return!1;return W.every((J,j)=>J===Y[j]||J.startsWith(":")&&e2.test(Y[j]))}var O0="user";function KZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return O3(`${O0}.:id`,{id:Z})}class W0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class D6 extends W0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let W=Z==="upload"?this.config.uploadLimit??f$("50mb"):f$(Z);return U6(this.req.rawRequest,W),{}}}function YY($){let Z=new Map;for(let W of $)if(typeof W==="string"){let[Y,J=""]=W.split(":");if(Y.startsWith("-")){if(Z.has(Y.replace("-","")))Z.delete(Y.replace("-",""))}else Z.set(Y,J.split(",").filter(Boolean))}else Z.set(W,[]);return Z}function UV($){return{"body-limit":D6.configure({uploadLimit:$})}}class $${config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:f$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=f$($.uploadBodyLimit??"50mb"),this.builtinAliases=UV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||jY($))return;let W=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;U6($,W,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}resolve($){let Z=this.aliases,W=[];for(let[Y,J]of YY($).entries())if(typeof Y==="string"){if(Z[Y])W.push({Middleware:Z[Y],params:J})}else if(V3(Y))W.push({Middleware:Y,params:[]});return W}runMiddleware($){let Z=new S,W=this.aliases,Y=[];for(let[J,j]of YY($).entries())if(typeof J==="string"){let z=W[J];if(z){let X=new z(Z);Y.push({run:()=>X.run.call(X,...j),runsOnRefusal:JY(z)})}}else if(V3(J)){let z=new J(Z);Y.push({run:z.run.bind(z),runsOnRefusal:JY(J)})}else Y.push({run:J,runsOnRefusal:!1});return(async()=>{let J={};for(let j=0;j<Y.length;j++)try{J={...J,...await Y[j].run()}}catch(z){throw await DV(Y.slice(j+1)),z}return J})()}}function JY($){return $?.runsOnRefusal===!0}async function DV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(W){console.error(W)}}}class O6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...v0($)],this}events(...$){return this}}class QY{static __brand="ChannelRouter";channels={};public(){return new O6("public")}private($){return new O6("private",$)}async authorize($,Z,W={},Y={}){try{HV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let J=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!BY(J))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===O0){if(Object.keys(W??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=O3(Z,W??{})}catch(G){if(G instanceof s)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(W??{}).map(([G,Q])=>[G,String(Q)])),X=new S($,z,"api",Z);return P.exit(()=>L6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(J.middlewares.length>0)await H($$).runMiddleware(J.middlewares);if(Z===O0){let Q=await zY(X);if(!Q)return{ok:!1,code:"denied"};if(j=KZ(Q),J.visibility==="private"&&J.authorizer){if(await XY(J.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(J.visibility==="private"){if((J.authorizer?await XY(J.authorizer,X,z):await zY(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(MV(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},Y.carried)))}}async function OV($,Z,W={},Y={}){let J=typeof $==="function"?new $:$;FY(J);let j=Y.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await J.authorize(z,Z,W,{carried:X})).ok}function BY($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function zY($){if(!P.getStore().user&&w$($)===null)return null;try{return await g0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function XY($,Z,W){if(LV($))return new $().authorize(Z,W);return $(Z,W)}function LV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function MV($){return $?.kind===Z$||W$($)||q$($)}var GY=new WeakSet;function HV($){if(GY.has($))return;FY($),GY.add($)}function FY($){let Z=Object.entries($.channels),W=[];for(let[Y,J]of Z){if(!BY(J))throw new s(`The channel "${Y}" is not declared with this.public() or this.private().`);let j=TZ(Y);if(j[0].startsWith(":"))throw new s(`The channel pattern "${Y}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(Y!==O0&&j.length===2&&j[0]===O0)throw new s(`The channel pattern "${Y}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(Y!==O0&&J.visibility==="private"&&!J.authorizer&&j.some((z)=>z.startsWith(":")))throw new s(`The private channel "${Y}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);W.push({pattern:Y,segments:Y===O0?[O0,":id"]:j})}for(let Y=0;Y<W.length;Y++)for(let J=Y+1;J<W.length;J++)if(TV(W[Y].segments,W[J].segments))throw new s(`The channel patterns "${W[Y].pattern}" and "${W[J].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function TV($,Z){if($.length!==Z.length)return!1;return $.every((W,Y)=>W===Z[Y]||W.startsWith(":")||Z[Y].startsWith(":"))}class h8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,W){this.as=$;this.input=Z;this.bind=W}}class M6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,W){this.method=$;this.url=Z;this.meta=W}}class p8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function KV($){let Z=[],W="";for(let Y of $)if(Y==="_"||Y==="-"||Y===" "){if(W)Z.push(W);W=""}else if(Y===Y.toLowerCase())W+=Y;else{if(W)Z.push(W);W=Y.toLowerCase()}if(W)Z.push(W);return Z}function PV($,Z){let W=KV($);if(Z==="snake")return W.join("_");if(Z==="kebab")return W.join("-");return W.map((Y,J)=>J===0?Y:Y[0].toUpperCase()+Y.slice(1)).join("")}class VY{static __brand="McpRouter";routes={};scopes;param($){return new h8($.as,$.input,$.bind)}fromTool($,Z={}){return new p8($,Z)}fromApiRoute($,Z,W){return new M6($,Z,W)}fromApiRouteFor($,Z,W){let{name:Y,audiences:J,description:j,params:z,files:X,...G}=W,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(J??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...K}=J[U],N=O??(D?PV(Y,D):Y);if(B.has(N))throw Error(`${Q}: the audiences "${B.get(N)}" and "${U}" are both named "${N}". Give one its own name or casing.`);B.set(N,U);let _=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof _!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let x={...G,...K,description:_};if(z||M)x.params={...z,...M};if(X||T)x.files={...X,...T};V[N]=new M6($,Z,x)}return V}}var NV="Rate limit exceeded";class M1 extends y0{result;retryAfter;constructor($,Z=NV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let W={"Content-Type":"application/json",...$?c8($):{}};this.payload={api:{status:429,data:{error:{...Y$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:W},view:{error:{message:Z},status:429,headers:W}}}}function c8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class m0{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let W=Z.limit??this.config.limit,Y=Z.window??this.config.window,J=Z.cost??1;if(UY("window",Y),UY("limit",W),!Number.isFinite(J)||J<0)throw Error(`Rate limiter cost must be zero or greater, got ${J}`);return await this.config.driver.consume({key:$,limit:W,window:Y*1000,cost:J})}async enforce($,Z={},W){let Y=await this.consume($,Z);if(!Y.allowed)throw new M1(Y,typeof W==="function"?W(Y):W);return Y}}function UY($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}async function d8($,Z){let W=_V();if(!W)return null;let Y=await W.consume($,Z);return Y.allowed?null:Math.max(1,Math.ceil(Y.retryAfter/1000))}function _V(){try{let $=H();return $.bound(m0)?$.make(m0):null}catch{return null}}var DY=["2026-07-28"],H6=["2025-11-25","2025-06-18","2025-03-26"],T6=[...DY,...H6],OY="io.modelcontextprotocol/protocolVersion",eT="io.modelcontextprotocol/clientCapabilities";var LY="io.modelcontextprotocol/serverInfo",z0={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class o extends Error{code;data;status;constructor($,Z,W,Y=200){super(Z);this.code=$;this.data=W;this.status=Y;this.name="JsonRpcError"}}function k1($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function MY($){if(Array.isArray($))throw new o(z0.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new o(z0.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,W=Z.id,Y=typeof W==="string"||typeof W==="number"&&Number.isFinite(W);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new o(z0.InvalidRequest,"params must be an object.",void 0,400);if(W===void 0)return{kind:"notification",message:Z};if(!Y)throw new o(z0.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(Y&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new o(z0.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function $K($,Z){let W=$.outputSchema?.toJSONSchema(),Y={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...W&&(Z||W.type==="object")?{outputSchema:W}:{},...Object.keys(Y).length>0?{annotations:Y}:{}}}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function IV($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let W=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(W)}catch{return null}}function HY($,Z,W){if(!DY.includes(W))throw new o(z0.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:T6,requested:W},400);let Y=(z)=>new o(z0.HeaderMismatch,`Header mismatch: ${z}`,void 0,400);if($.headers.get("mcp-protocol-version")!==W)throw Y("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw Y("Mcp-Method does not match the method.");let J=Z.params??{},j=Z.method==="tools/call"||Z.method==="prompts/get"?J.name:Z.method==="resources/read"?J.uri:void 0;if(j!==void 0){let z=$.headers.get("mcp-name");if(z===null||IV(z)!==j)throw Y("Mcp-Name does not match the request's name.")}}import{isIP as K6}from"net";function J$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let Y=Z.indexOf("]");if(Y<0)return null;let J=Z.slice(Y+1);if(J!==""&&!/^:\d{1,5}$/.test(J))return null;let j=Z.slice(1,Y);return K6(j)===6?j:null}if(K6(Z))return Z;let W=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return W&&K6(W[1])===4?W[1]:null}function TY($,{ipv6Prefix:Z=64}={}){if(!Number.isInteger(Z)||Z<0||Z>128)throw RangeError(`ipv6Prefix must be a whole number from 0 to 128, not ${Z}.`);let W=J$($);if(W===null||K6(W)===4)return W??$;let Y=CV(W);if(Y===null)return $;if(Y.slice(0,5).every((z)=>z===0)&&Y[5]===65535)return`${Y[6]>>8}.${Y[6]&255}.${Y[7]>>8}.${Y[7]&255}`;let J=Y.map((z,X)=>{let G=Math.min(Math.max(Z-X*16,0),16);return z&(65535<<16-G&65535)}),j=xV(J);return Z===128?j:`${j}/${Z}`}function CV($){let Z=$.split("%")[0].toLowerCase(),W=/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(Z);if(W){let[Q,F,V,B]=W.slice(1).map(Number);Z=`${Z.slice(0,W.index)}${(Q<<8|F).toString(16)}:${(V<<8|B).toString(16)}`}let[Y,J]=Z.split("::"),j=(Q)=>Q===""?[]:Q.split(":").map((F)=>parseInt(F,16)),z=j(Y),X=J===void 0?[]:j(J),G=J===void 0?z:[...z,...Array.from({length:8-z.length-X.length},()=>0),...X];return G.length===8&&G.every((Q)=>Q>=0&&Q<=65535)?G:null}function xV($){let Z=-1,W=0;for(let J=0;J<8;J++){if($[J]!==0)continue;let j=J;while(j<8&&$[j]===0)j++;if(j-J>W)Z=J,W=j-J;J=j}let Y=$.map((J)=>J.toString(16));if(W<2)return Y.join(":");return`${Y.slice(0,Z).join(":")}::${Y.slice(Z+W).join(":")}`}class _Y extends W0{static isRateLimit=!0;async run($,Z){let W=AV();if(!W)return{};let Y=await W.consume(this.key(),{limit:KY($)??this.config.limit,window:KY(Z)??this.config.window});if(this.config.headers!==!1){let J=this.req.ctx?.();if(J)for(let[j,z]of Object.entries(c8(Y)))J.setHeaders(j,z)}if(!Y.allowed)throw new M1(Y);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=PY(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${v$(this.req)}:${this.req.routePath??"*"}`}}function AV(){try{let $=H();return $.bound(m0)?$.make(m0):null}catch{return null}}function P6($){let Z=NY($.rawRequest);if(Z!==void 0)return Z;let W=$.headers.get("x-forwarded-for");if(W){let[Y]=W.split(",");if(Y?.trim())return J$(Y)??Y.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function v$($,Z){return TY(P6($),Z)}function KY($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}var SV={token:"router.domains"},bV={token:"middleware"},EV={limit:600,window:60},RV=1048576,IY=/^(GET|POST|PUT|PATCH|DELETE) (\/\S*)$/,kV=/^[A-Za-z0-9_.-]{1,128}$/;class L3 extends Error{code;status;data;headers;constructor($,Z,W={}){super(Z);this.code=$;this.name="McpEndpointError",this.status=W.status??200,this.data=W.data,this.headers=W.headers}}var AY=Symbol("McpEndpoint.result");class SY{static __brand="McpEndpoint";server;rateLimit;maxBodyBytes;tool($){return $}static result($,Z={}){return{[AY]:!0,body:$,isError:Z.isError===!0,text:Z.text}}static __routes(){let $=new this;return $.check(this.name||"McpEndpoint"),new u8($)}checked;check($){if(this.checked=$,this.caller!=="anonymous")throw Error(`${$}: set \`caller = "anonymous" as const\` to serve this endpoint to anyone. It is required: an endpoint that names no caller would be open without anybody having said so.`);if(!o0(this.tools))throw Error(`${$}: tools must be an object of tools, by name.`);for(let[Z,W]of Object.entries(this.tools)){let Y=`${$}: tool "${Z}"`;if(!kV.test(Z))throw Error(`${Y}: a tool name is 1 to 128 letters, digits, "_", "-" or ".".`);if(!o0(W)||typeof W.run!=="function"||typeof W.description!=="string")throw Error(`${Y} needs a description and a run().`);if(!o0(W.inputSchema))throw Error(`${Y}: inputSchema must be an s schema or a JSON Schema object.`);if(W.offered!==void 0&&typeof W.offered!=="function")throw Error(`${Y}: offered must be a function.`);let J=W.rateLimit;if(typeof J==="string"){if(!IY.test(J))throw Error(`${Y}: rateLimit "${J}" is not "METHOD /path", like "POST /orders".`)}else if(J!==void 0&&!xY(J))throw Error(`${Y}: rateLimit must be "METHOD /path" or { limit, window } in positive numbers.`)}if(this.rateLimit!==void 0&&this.rateLimit!==!1&&!xY(this.rateLimit))throw Error(`${$}: rateLimit must be { limit, window } in positive numbers, or false.`)}async __post($){let Z=$.rawRequest,W=this.rateLimit===!1?null:this.rateLimit??EV;if(W){let G=await d8(`mcp-endpoint:${v$($)}:${$.routePath??"*"}`,W);if(G!==null)return w1(k1(null,new o(z0.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String(G)})}if(!/^application\/json\s*(;|$)/i.test(Z.headers.get("content-type")??""))return new Response("Content-Type must be application/json.",{status:415,headers:{"Cache-Control":"no-store"}});let Y=Z.headers.get("mcp-protocol-version");if(Y!==null&&!T6.includes(Y))return w1(k1(null,new o(z0.InvalidRequest,`Unsupported MCP-Protocol-Version: ${Y.slice(0,40)}`)),400);let J=this.context?await this.context($):void 0;if(J instanceof Response)return J;if(J===null||this.context&&J===void 0)return w1(k1(null,new o(z0.InvalidRequest,"Not found.")),404);let j,z=this.maxBodyBytes??RV;try{j=JSON.parse(await qV(Z,z))}catch(G){if(G instanceof N6)return w1(k1(null,new o(z0.InvalidRequest,`The request is larger than ${z} bytes.`)),413);return w1(k1(null,new o(z0.ParseError,"Parse error.")),400)}let X=o0(j)&&(typeof j.id==="string"||typeof j.id==="number")?j.id:null;try{return await this.dispatch($,J,j)}catch(G){if(G instanceof L3)return w1(k1(X,new o(G.code,G.message,G.data)),G.status,G.headers);if(G instanceof o)return w1(k1(X,G),G.status);return console.error(`[gemi/mcp] ${this.checked} failed:`,G),w1(k1(X,new o(z0.InternalError,"Internal error.")),500)}}async dispatch($,Z,W){let Y=MY(W);if(Y.kind!=="request")return new Response(null,{status:202});let{message:J}=Y,j=J.params??{},z=o0(j._meta)?j._meta:{},X=z[OY],G=typeof X==="string";if(G)HY($.rawRequest,J,X);let Q=await this.answer($,Z,J.method,j,z,G);return w1({jsonrpc:"2.0",id:J.id,result:G?this.complete(Q):Q},200)}async answer($,Z,W,Y,J,j){switch(W){case"initialize":{if(j)break;let z=Y.protocolVersion;return{protocolVersion:H6.includes(z)?z:H6[0],capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo(),...this.server?.instructions?{instructions:this.server.instructions}:{}}}case"server/discover":if(!j)break;return{supportedVersions:T6,capabilities:{tools:{}},...this.server?.instructions?{instructions:this.server.instructions}:{}};case"ping":return{};case"tools/list":{let z=[];for(let[X,G]of Object.entries(this.tools))if(await this.offers(G,Z,$))z.push(wV(X,G));return j?{tools:z,ttlMs:60000,cacheScope:"private"}:{tools:z}}case"tools/call":return await this.call($,Z,Y,J)}throw new o(z0.MethodNotFound,`Method not found: ${W.slice(0,100)}`)}async call($,Z,W,Y){let J=W.name,j=typeof J==="string"&&Object.hasOwn(this.tools,J)?this.tools[J]:void 0;if(!j||!await this.offers(j,Z,$))throw new o(z0.InvalidParams,`Unknown tool: ${String(J).slice(0,100)}`);let z=await this.spend($,J,j);if(z!==null)throw new L3(-32000,"Rate limit exceeded",{status:429,data:{retry_after:z},headers:{"Retry-After":String(z)}});let X=W.arguments===void 0?{}:W.arguments;if(!o0(X))throw new o(z0.InvalidParams,"arguments must be an object.");if(bY(j.inputSchema)){let Q=j.inputSchema.safeParse(X);if(Q.ok===!1)return{content:[{type:"text",text:`Invalid arguments for "${J}": ${Q.errors.join(", ")}`}],isError:!0};X=Q.value}let G;try{G=await j.run(X,{context:Z,req:$,tool:J,meta:Y,signal:$.rawRequest.signal})}catch(Q){if(Q instanceof L3||Q instanceof o)throw Q;return console.error(`[gemi/mcp] ${this.checked}: "${J}" failed:`,Q),{content:[{type:"text",text:`"${J}" failed on the server.`}],isError:!0}}return fV(G)}async offers($,Z,W){return $.offered?await $.offered(Z,W)===!0:!0}async spend($,Z,W){let Y=W.rateLimit;if(Y===void 0)return null;if(typeof Y!=="string")return await d8(`mcp-endpoint-tool:${v$($)}:${$.routePath??"*"}:${Z}`,Y);let[,J,j]=IY.exec(Y),z=this.twinLimits($,Z,J,j);if(z.length===0)return null;let X=new S($.rawRequest,{},"api",j);try{await P.run(X,async()=>{for(let{Middleware:G,params:Q}of z)await new G(X).run(...Q)})}catch(G){if(G instanceof M1||G?.name==="RateLimitExceededError"){let Q=G.retryAfter??1000;return Math.max(1,Math.ceil(Q/1000))}throw G}return null}twinLimits($,Z,W,Y){let j=H(SV).dispatchers($.domain).api.flatRoutes[Y]?.[W];if(!j)throw Error(`${this.checked}: tool "${Z}" spends the rate limits of ${W} ${Y}, and this host's api has no such route. Name the route by its full path, without /api.`);return H(bV).resolve(j.middleware).filter(({Middleware:z})=>z.isRateLimit===!0)}serverInfo(){return{name:this.server?.name??"gemi",version:this.server?.version??"1.0.0"}}complete($){return{resultType:"complete",...$,_meta:{[LY]:this.serverInfo()}}}}class u8{post;get;delete;constructor($){this.post=new d("POST",(W)=>$.__post(W));let Z=(W)=>new Response(null,{status:405,headers:{Allow:"POST","Cache-Control":"no-store"}});this.get=new d("GET",Z),this.delete=new d("DELETE",Z)}middleware($){let Z=v0($);for(let W of[this.post,this.get,this.delete])W.middleware(Z);return this}cors($){for(let Z of[this.post,this.get,this.delete])Z.cors($);return this}}function wV($,Z){return{name:$,...Z.title?{title:Z.title}:{},description:Z.description,inputSchema:bY(Z.inputSchema)?Z.inputSchema.toJSONSchema():Z.inputSchema,...Z.outputSchema?{outputSchema:Z.outputSchema}:{},...Z.annotations||Z.title?{annotations:{...Z.title?{title:Z.title}:{},...Z.annotations}}:{}}}function fV($){if(o0($)&&$[AY]===!0){let Z=$;return{content:[{type:"text",text:Z.text??CY(Z.body)}],...o0(Z.body)?{structuredContent:Z.body}:{},isError:Z.isError}}if(typeof $==="string")return{content:[{type:"text",text:$}],isError:!1};return{content:[{type:"text",text:CY($)}],...o0($)?{structuredContent:$}:{},isError:!1}}function CY($){return typeof $==="string"?$:JSON.stringify($??null)}function bY($){return o0($)&&typeof $.safeParse==="function"&&typeof $.toJSONSchema==="function"}function xY($){return o0($)&&typeof $.limit==="number"&&$.limit>0&&Number.isFinite($.limit)&&typeof $.window==="number"&&$.window>0&&Number.isFinite($.window)}class N6 extends Error{}async function qV($,Z){let W=Number($.headers.get("content-length"));if(Number.isFinite(W)&&W>Z)throw new N6;if(!$.body)return"";let Y=$.body.getReader(),J=[],j=0;for(;;){let{done:z,value:X}=await Y.read();if(z)break;if(j+=X.byteLength,j>Z)throw await Y.cancel(),new N6;J.push(X)}return Buffer.concat(J).toString("utf8")}function w1($,Z,W={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...W}})}function L0($,Z){return $.replace(/:([^/]+[*?]?)/g,(W,Y)=>{let J=Y.endsWith("?")||Y.endsWith("*"),j=J?Y.slice(0,-1):Y,z=Z[j];if(z===void 0){if(J)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class l8 extends y0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class f1{static to($,...Z){let[W={}]=Z,{search:Y={},params:J={},permanent:j,status:z}={params:{},status:307,permanent:!1,...W},X=new URLSearchParams(Y).toString();throw new l8([L0($,J)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new l8($,Z)}}class EY{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,W]=$;this.handler=(Y)=>{return new Z()[W](Y)}}}async run($,Z){let{destination:W,permanent:Y=!1,status:J=307}=await this.handler($);if(!W)throw Error(`Redirect destination is required see ${Z}`);return f1.to(W,{permanent:Y,status:J}),{}}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function i8($,Z){if($ instanceof Response)return $;let W=$ instanceof Blob,Y=W?$:$.file,J=W?$.name:$.name??$.file?.name,j=(W?$.type:$.type??$.file?.type)||"",z=W?!1:$.download??!1,X=W?200:$.status??200;if(!W)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(Y instanceof Blob&&"exists"in Y&&typeof Y.exists==="function"){if(!await Y.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),Y instanceof Blob)Z.set("Content-Length",String(Y.size));if(J)Z.set("Content-Disposition",F6(J,z));return new Response(Y instanceof Blob?Y.stream():Y,{status:X,headers:Z})}class RY{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,W]=$;this.handler=(Y)=>{return new Z()[W](Y)}}}async run($,Z){let W=await this.handler($);if(!W)throw Error(`File route handler must return a file see ${Z}`);return{FILE:W}}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function kY($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class wY{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[W,Y]=Z;this.handler=(J)=>{return new W()[Y](J)}}}async run($,Z){let W=kY(await this.handler($),this.viewPath);return{[this.viewPath]:{...W,breadcrumb:{label:W?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=v0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class fY{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,W){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends q1{routes=W??{}};else if(Array.isArray(Z)){let[Y,J]=Z;this.handler=(j)=>{return new Y()[J](j)},this.children=class extends q1{routes=W??{}}}else this.children=class extends q1{routes=Z},this.handler=()=>({})}async run($,Z){let W=kY(await this.handler($),this.viewPath);return{[this.viewPath]:{...W,breadcrumb:{label:W?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=v0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class q1{middlewares=[];featureGates=[];routes={};view($,Z){return new wY($,Z)}file($){return new RY($)}redirect($){return new EY($)}layout($,Z,W){return new fY($,Z,W)}}function vV($){return $}function gV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var a0="redirect";function H1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let W=new URL($,"http://gemi.invalid");if(W.origin!=="http://gemi.invalid")return Z;let Y=`${W.search}${W.hash}`.replaceAll("/","%2F"),J=`${W.pathname}${Y}`.replaceAll(":","%3A");return J.startsWith("//")?Z:J}catch{return Z}}function PZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function s8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function yV($,Z=!0){let W=new URL($.rawRequest.url),Y=W.pathname.replace(/\.(json|og)$/,""),[,J,...j]=Y.split("/");if(H(l).supportedLocales.includes(J))Y=`/${j.join("/")}`;return Z?`${Y}${W.search}`:Y}function mV($,Z){let W=(Y)=>Y.replace(/\/+$/,"")||"/";return W($)===W(Z)}function _6($,Z){let W=Z||H(R).config.signInPath,Y=/^[a-z][a-z\d+.-]*:/i.test(W);if(Y?!/^https?:\/\//i.test(W):!W.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${W}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let J=new URL(W,"http://gemi.invalid");if($?.kind==="view"){let j=yV($,!Y);if(Y||!mV(new URL(j,J).pathname,J.pathname))J.searchParams.set(a0,j)}return Y?J.href:`${J.pathname}${J.search}`}class qY extends W0{async run($){let Z=P.getStore(),W=Z.req;if(Z.user)return{};let Y=await V6(H(R),W);if(!Y)throw new g$({redirectTo:_6(W,$)});return Z.setUser(Y),{}}}var o8="gemi_same_site",n8="private, no-cache, no-store, max-age=0, must-revalidate";class I6 extends W0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let W=Z.rawRequest;if(Z.kind!=="view"||W.method!=="GET"&&W.method!=="HEAD")return{};let Y=new URL(W.url);if(/\.(json|og)$/.test(Y.pathname))return{};if(Y.searchParams.has(o8))return{};if(w$(Z))return{};let J=W.headers.get("Sec-Fetch-Site");if(J&&J!=="cross-site")return{};throw Y.searchParams.set(o8,"1"),new vY(`${Y.pathname}${Y.search}`)}}class vY extends y0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=hV($),W={"Content-Type":"text/html; charset=utf-8","Cache-Control":n8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":n8}},viewData:{status:200,data:{},headers:{"Cache-Control":n8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:W,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function hV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class gY extends W0{async run(...$){let[Z="public",W="864000",...Y]=$,J=`${Z}, max-age=${W}${Y.length>0?", ":""}${Y.join(", ")}`;if($.length===0)J="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")J="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")J="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",J);return{}}}var yY={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class mY extends W0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let W={...yY,...this.config.origins[Z]};if(Z==="null")delete W["Access-Control-Allow-Credentials"];for(let[Y,J]of Object.entries(W))$.ctx().setHeaders(Y,J)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let W={...yY,...this.config.origins["*"]};delete W["Access-Control-Allow-Credentials"];for(let[Y,J]of Object.entries(W))$.ctx().setHeaders(Y,J)}return{}}}class pY extends W0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new a8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new a8;return{}}}class a8 extends y0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:hY("csrf","Invalid CSRF token",403)}},view:{}}}class cY{policiesList={};constructor(){let $=this.register();for(let Z of $){let W=new Z;this.policiesList[Z.name]=W}}register(){return[]}}class dY{all($,Z){return!0}}class t8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new NZ:new C6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let W=this.answers.get($.rawRequest);if(!W)W=new Map,this.answers.set($.rawRequest,W);let Y=W.get(Z);if(!Y)Y=this.decide($,Z),W.set(Z,Y);return Y}async allows($,Z){try{return await this.authorize($,Z),!0}catch(W){if(this.isRefusal(W))return!1;throw W}}fromRoute($=new S,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,W)=>this.fromRoute(Z,W||void 0);this.middlewareClass=class extends W0{async run(W){await $(this.req,W)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:W,body:Y})=>{let J;if(W!==void 0){if(J=$.thread?await $.thread(W,Z):null,J===null||J===void 0)throw this.refusal()}if(Y!==void 0){let j=await $.body(Y,Z);if(await this.authorize(Z,j),W!==void 0&&String(J)!==String(j))throw this.refusal();return}if(W!==void 0)await this.authorize(Z,J)}}}async decide($,Z){let W=await this.options.load(Z,$);if(W===null||W===void 0||!await this.options.allow(W,$))throw this.refusal();return W}isRefusal($){return this.refuse==="forbidden"?$ instanceof NZ:$ instanceof C6}}function pV($){return new t8($)}async function S6($,Z,W=!1){if(!$.body)return new Uint8Array;let[Y,J]=await $U($.body),z=Y.length>=2&&Y[0]===31&&Y[1]===139?J.pipeThrough(new DecompressionStream("gzip")):J;return eV(z,Z,W,$.url)}async function eV($,Z,W,Y){let J=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await J.read();if(Q)break;if(z+F.byteLength>Z){if(!W)throw new A6(Y,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{J.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function $U($){let Z=$.getReader(),W=await Z.read(),Y=W.done?new Uint8Array:W.value,J=new ReadableStream({start(j){if(W.done)j.close();else j.enqueue(Y)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[Y,J]}function b6($){return new TextDecoder("utf-8").decode($)}var ZU={"&":"&","<":"<",">":">",'"':""","'":"'"};function y$($){return $.replace(/[&<>"']/g,(Z)=>ZU[Z])}var WU={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function r8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,W)=>{if(W[0]!=="#")return WU[W]??Z;let Y=W[1]==="x"?parseInt(W.slice(2),16):parseInt(W.slice(1),10);return Y>0&&Y<=1114111?String.fromCodePoint(Y):Z})}function e8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function uY($,Z){let W=$.length,Y=0;while(Y<W){if(Z.stopped?.())return;let J=$.indexOf("<",Y);if(J===-1){Z.text(r8($.slice(Y)));return}if(J>Y)Z.text(r8($.slice(Y,J)));if($.startsWith("<!--",J)){let j=$.indexOf("-->",J+4);if(j===-1)return;Y=j+3}else if($.startsWith("<![CDATA[",J)){let j=$.indexOf("]]>",J+9);if(j===-1)return;Z.text($.slice(J+9,j)),Y=j+3}else if($.startsWith("<?",J)){let j=$.indexOf("?>",J+2);if(j===-1)return;Y=j+2}else if($.startsWith("<!",J)){let j=$.indexOf(">",J+2);if(j===-1)return;let z=$.indexOf("[",J+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;Y=G+1}else Y=j+1}else if($[J+1]==="/"){let j=$.indexOf(">",J+2);if(j===-1)return;Z.close(e8($.slice(J+2,j).trim())),Y=j+1}else{let j=YU($,J+1);if(j===-1)return;let z=$.slice(J+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=e8(z.slice(0,G));if(Q){if(Z.open(Q,JU(z.slice(G)),X),X)Z.close(Q)}Y=j+1}}}function YU($,Z){let W=null;for(let Y=Z;Y<$.length;Y++){let J=$[Y];if(W){if(J===W)W=null}else if(J==='"'||J==="'")W=J;else if(J===">")return Y}return-1}function JU($){let Z={},W=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let Y of $.matchAll(W))Z[e8(Y[1])]=r8(Y[2]??Y[3]??"");return Z}class X0 extends Error{url;status;constructor($,Z=null,W=null){super($);this.url=Z;this.status=W;this.name="SitemapError"}}var oY="http://www.sitemaps.org/schemas/sitemap/0.9",jU="http://www.w3.org/1999/xhtml",W5=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`,lY=`<urlset xmlns="${oY}" xmlns:xhtml="${jU}">
|
|
4
4
|
`,iY=`</urlset>
|
|
5
5
|
`,m$=50000,M3=52428800,sY=2048,zU=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),XU=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,GU="application/xml; charset=utf-8",nY=new TextEncoder;function Y5($,Z){let W;try{W=new URL($)}catch{throw new X0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw new X0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let Y=W.href;if(Y.length>sY)throw new X0(`Sitemap: ${Z} is over ${sY} characters: "${Y.slice(0,80)}\u2026".`);return Y}function aY($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new X0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!XU.test($))throw new X0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function QU($){let Z=Y5($.loc,"loc"),W=`<url><loc>${y$(Z)}</loc>`;if($.lastmod!=null)W+=`<lastmod>${y$(aY($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!zU.has($.changefreq))throw new X0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);W+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let Y=$.priority;if(!Number.isFinite(Y)||Y<0||Y>1)throw new X0(`Sitemap: priority ${Y} of ${Z} is not between 0 and 1.`);W+=`<priority>${Number(Y.toFixed(4))}</priority>`}for(let Y of $.alternates??[]){let J=Y.hrefLang?.trim();if(!J)throw new X0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=Y5(Y.href,`alternate href of ${Z}`);W+=`<xhtml:link rel="alternate" hreflang="${y$(J)}" href="${y$(j)}"/>`}return`${W}</url>
|