gemi 0.227.0 → 0.228.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +1 -1
- package/dist/ai/providers/http.d.ts.map +1 -1
- package/dist/ai/providers/live.d.ts +23 -0
- package/dist/ai/providers/live.d.ts.map +1 -0
- package/dist/ai/providers/sideband.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/{chunk-cjj9cryr.js → chunk-hddxvnh7.js} +2 -2
- package/dist/{chunk-cjj9cryr.js.map → chunk-hddxvnh7.js.map} +3 -3
- package/dist/{chunk-xstbj0wa.js → chunk-hhpme9te.js} +1 -1
- package/dist/{chunk-ehjae5fm.js → chunk-wyb6k943.js} +4 -4
- package/dist/{chunk-ehjae5fm.js.map → chunk-wyb6k943.js.map} +2 -2
- package/dist/chunk-z0s09je5.js +12 -0
- package/dist/{chunk-v5b883zc.js.map → chunk-z0s09je5.js.map} +6 -5
- package/dist/{chunk-qjd7pk3n.js → chunk-z6zvemqa.js} +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/cron/ScheduleServiceProvider.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-v5b883zc.js +0 -12
- /package/dist/{chunk-xstbj0wa.js.map → chunk-hhpme9te.js.map} +0 -0
- /package/dist/{chunk-qjd7pk3n.js.map → chunk-z6zvemqa.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ca as aQ,da as JZ,ea as $Z,fa as d6,ga as n6,ha as o6,ia as r$,ja as s6,ka as a6,la as _$,ma as t6,na as r6,oa as e6,pa as J0}from"../chunk-
|
|
2
|
+
import{ca as aQ,da as JZ,ea as $Z,fa as d6,ga as n6,ha as o6,ia as r$,ja as s6,ka as a6,la as _$,ma as t6,na as r6,oa as e6,pa as J0}from"../chunk-z0s09je5.js";import{$c as I6,Ac as xZ,Bc as OQ,Dc as _Q,Ec as RQ,Fc as MQ,Gc as SQ,Hc as AQ,Ic as EQ,Jc as kQ,Kc as TQ,Lc as jQ,Mc as xQ,Nc as wQ,Oc as IQ,Qc as t$,Rc as M6,Sc as S6,Tc as A6,Uc as R6,Vc as E6,Wc as k6,Xc as T6,Yc as j6,Zc as x6,_c as w6,ad as NJ,bd as f6,cd as O8,dd as q6,ed as _8,fd as b6,gd as v6,hd as y6,ic as o$,id as fJ,jc as z8,jd as D$,kc as Y8,kd as h6,lc as s$,ld as g6,md as L8,nd as c6,od as u6,pc as sQ,pd as m6,qc as pQ,qd as p6,rc as YJ,rd as l6,sc as B6,sd as B8,tc as h,td as i6,uc as FQ,ud as z$,vc as UQ,xc as CQ,yc as m,zc as jZ}from"../chunk-9jz5ts7h.js";import{Ad as j,Hd as i,Id as a$,Ld as D8,Md as H8,Nd as P8,Od as mJ,Pd as N8,Qd as oJ,Rd as pJ,Sd as u$,Td as F8,Ud as U8,Vd as sJ,Wd as C8,ae as QJ,ce as $J,yd as ZZ,zd as R}from"../chunk-kx5gycdv.js";import{te as zQ}from"../chunk-a2y481gh.js";import"../chunk-xv46emqt.js";import{Ri as f,pi as Q8,si as W8,xj as X8,yj as T$}from"../chunk-vjqpcet2.js";import{Bj as dJ,Cj as nJ,zj as Z8}from"../chunk-jqqyj6cr.js";import{Fj as O6,Gj as _6,Hj as L6}from"../chunk-30zs008n.js";import{Uj as l}from"../chunk-m4wagwhr.js";import"../chunk-9bjggtdt.js";import{$k as K8,al as G8,bl as V8,cl as c$}from"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import{il as e,jl as JJ,yl as xJ}from"../chunk-qgka1mvf.js";import"../chunk-znh1mbqs.js";import"../chunk-7ka1abkd.js";import{pm as CZ}from"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-0dp6jvrg.js";import{Mm as eJ}from"../chunk-x8by5j7p.js";import"../chunk-30jcs49q.js";import{existsSync as w8,readdirSync as Q0,readFileSync as KQ}from"fs";import{isAbsolute as I8,join as AJ,relative as f8,sep as q8}from"path";var GQ="prompts.json",b8=/\{\{>\s*([\w./-]+)\s*\}\}/g,ZQ=/\{\{(\w+)\}\}/g,v8=/^[\w-]+(\/[\w-]+)*$/,WQ={dir:"app/agents",shared:"prompts"},EJ={},tJ=new Map,RJ;function y8(){if(RJ===void 0){let J=AJ(eJ(),"dist","server",GQ);RJ=w8(J)?JSON.parse(KQ(J,"utf8")):null}return RJ??null}function h8(J){return J.replace(/\r?\n$/,"")}function XQ(){return EJ.cache??Bun.env.NODE_ENV==="production"}function g8(J,$){if(!v8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??EJ.dir??WQ.dir,Z=I8(Q)?Q:AJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:AJ($.shared??EJ.shared??WQ.shared,`${J}.md`);return AJ(Z,W)}function c8(J,$){let Q=g8(J,$),Z=XQ()?tJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let K=y8()?.[f8(eJ(),Q).split(q8).join("/")];if(K!==void 0)return K}let X;try{X=h8(KQ(Q,"utf8"))}catch(K){if(K.code==="ENOENT"){let G=W?` or in dist/server/${GQ}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw K}if(XQ())tJ.set(Q,X);return X}function rJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return c8(J,Q).replace(b8,(Z,W)=>rJ(W,[...$,J],Q))}class VQ{static configure(J){EJ={...J},tJ.clear(),RJ=void 0}static render(J,$={},Q={}){return rJ(J,[],Q).replace(ZQ,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...rJ(J,[],$).matchAll(ZQ)].map((Z)=>Z[1]);return[...new Set(Q)]}}class J$ extends zQ{name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await m.sweep({limit:100})===100);}}var TJ=20,u8=300,m8=200;function DQ(J,$){if($<=0||J.length===0)return null;let Q=(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.",...[...J.filter((X)=>!h(X.state)).sort(Q),...J.filter((X)=>h(X.state)).sort(Q)].slice(0,$).map((X)=>{let K=[`- ${X.id} (${X.toolName})`];if(X.state==="waiting")K.push(`waiting for ${(X.after??[]).join(", ")} since ${kJ(X.createdAt)}`);else if(X.state==="running")K.push(`running since ${kJ(X.createdAt)}`);else if(X.state==="ok")K.push(`finished at ${kJ(X.settledAt??X.updatedAt)}`);else{let G=X.error?`${X.error.code}: ${YQ(X.error.message,m8)}`:"failed";K.push(`failed at ${kJ(X.settledAt??X.updatedAt)} (${G})`)}if(X.summary!==void 0)K.push(`summary: ${YQ(JSON.stringify(X.summary),u8)}`);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 kJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function YQ(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var HQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],PQ=20;class $${table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of p8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return xJ(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
|
|
4
4
|
INSERT INTO ${this.name(Q)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
@@ -1 +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;
|
|
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;;;;;;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B,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,CAyCnC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model calls from a test process (#1342).
|
|
3
|
+
*
|
|
4
|
+
* A test that boots the app with a real provider configured, and the keys in
|
|
5
|
+
* its environment, would otherwise make real, billed calls: a forgotten fake,
|
|
6
|
+
* a background job a test started, a provider picked by config. Under vitest a
|
|
7
|
+
* built-in provider refuses to reach the network unless `GEMI_AI_LIVE=1`.
|
|
8
|
+
*
|
|
9
|
+
* Only the network is refused. A test that passes the provider its own
|
|
10
|
+
* `fetchImpl` (or `webSocket`), that stubs the global `fetch`/`WebSocket`
|
|
11
|
+
* (`vi.stubGlobal`), or whose provider points at this machine (`localhost`,
|
|
12
|
+
* `127.0.0.1`, `::1`: a test server, a local model) is let through.
|
|
13
|
+
*/
|
|
14
|
+
/** A built-in provider refused a network call under vitest without `GEMI_AI_LIVE=1`. */
|
|
15
|
+
export declare class LiveModelCallRefusedError extends Error {
|
|
16
|
+
constructor(url: string);
|
|
17
|
+
}
|
|
18
|
+
export declare function liveCallsAllowed(env?: NodeJS.ProcessEnv): boolean;
|
|
19
|
+
/** Throws unless this process may send a real request with the global `fetch`. */
|
|
20
|
+
export declare function assertLiveFetch(url: string): void;
|
|
21
|
+
/** Throws unless this process may open a real socket with the global `WebSocket`. */
|
|
22
|
+
export declare function assertLiveWebSocket(url: string): void;
|
|
23
|
+
//# sourceMappingURL=live.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live.d.ts","sourceRoot":"","sources":["../../../ai/providers/live.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAOH,wFAAwF;AACxF,qBAAa,yBAA0B,SAAQ,KAAK;gBACtC,GAAG,EAAE,MAAM;CAQxB;AAED,wBAAgB,gBAAgB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAE9E;AAED,kFAAkF;AAClF,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAGjD;AAED,qFAAqF;AACrF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAIrD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sideband.d.ts","sourceRoot":"","sources":["../../../ai/providers/s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AI;IAOtC,aAAa,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAIhD,sEAAsE;IACtE,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAI5C;;;OAGG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAI3B;8EAC0E;IAC1E,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IAQrD,cAAc,CAAC,OAAO,GAAE,uBAA4B,GAAG,IAAI;IAoB3D,cAAc,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IAUzC,4EAA4E;IAC5E,EAAE,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI;IAKxD;;;;OAIG;IACH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,aAAa,CAAC;IA6BtD;6CACyC;IACzC,KAAK,CAAC,IAAI,SAAO,EAAE,MAAM,SAAW,GAAG,IAAI;IAO3C;;;;;;;;OAQG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;YAYf,IAAI;IAkClB,OAAO,CAAC,OAAO;IAaf,OAAO,CAAC,MAAM;IAgBd,OAAO,CAAC,IAAI;CAmBb"}
|
package/dist/ai/testing/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{la as g}from"../../chunk-
|
|
2
|
+
import{la as g}from"../../chunk-z0s09je5.js";import"../../chunk-kx5gycdv.js";import{Fj as v,Gj as m}from"../../chunk-30zs008n.js";import"../../chunk-m4wagwhr.js";import"../../chunk-6fpjc2eg.js";import"../../chunk-dqb257xv.js";import"../../chunk-x8by5j7p.js";import"../../chunk-30jcs49q.js";import{createHash as s}from"crypto";import{createHash as S}from"crypto";import{existsSync as h,readdirSync as c,readFileSync as l,statSync as p}from"fs";import{join as q,relative as d,sep as i}from"path";var P="\u241F",F=6,n=/\{\{>\s*([^}\s]+)\s*\}\}/g,b=(D)=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function R(D){let $=D.filter((B)=>B.length>=F),z=D.filter((B)=>B.length<F);return(B)=>{let C=B;for(let G of $)if(C.includes(G))C=C.split(G).join(P);for(let G of z)C=C.replace(new RegExp(`${b(G)}\\s*${P}`,"g"),P).replace(new RegExp(`${P}\\s*${b(G)}`,"g"),P);return C.replace(new RegExp(`\\s*${P}[\\s${P}]*`,"g"),P)}}function y(D,$=[]){for(let z of c(D)){if(z==="node_modules")continue;let B=q(D,z);if(p(B).isDirectory())y(B,$);else if(z.endsWith(".md"))$.push(B)}return $}class W{data;root;options;constructor(D,$={}){this.data=D;this.options=$,this.root=$.root??process.cwd()}static blob(D){return S("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 S("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 B of D.dirs??["app/agents"]){if(!h(q($,B)))continue;for(let C of y(q($,B)).sort())z.set(d($,C).split(i).join("/"),l(C,"utf8"))}return z}static of(D,$,z={}){let B=[...D].join(`
|
|
3
3
|
\x00
|
|
4
4
|
`),C={};for(let[Y,Q]of W.prompts(z))if(W.pieces(Q).filter((Z)=>Z.length>=12).sort((Z,L)=>L.length-Z.length).slice(0,3).some((Z)=>B.includes(Z)))C[Y]=W.blob(Q);let G=[...$.keys()].sort(),X=z.inputs?.(new Set(G));return new W({prompts:C,tools:Object.fromEntries(G.map((Y)=>[Y,[...$.get(Y)].sort()])),...X&&Object.keys(X).length>0?{inputs:a(X)}:{}},z)}same(D){let $=D instanceof W?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=W.prompts(this.options),$=this.changedPrompts(),z=new Map,B=new Map;for(let[C,G]of $){let X=this.readBlob(G);if(X===void 0)throw Error(`${C} changed since the recording, and the version it was recorded with (${G}) can't be read back from git`);if(z.set(C,X),D.has(C))B.set(C,D.get(C))}return{changed:$.map(([C])=>C),recorded:R(this.piecesWithPartials(z,(C)=>{let G=this.data.prompts[C];return G&&this.readBlob(G)||D.get(C)})),sent:R(this.piecesWithPartials(B,(C)=>D.get(C)))}}changedPrompts(){let D=W.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let B=D.get($);return B===void 0||W.blob(B)!==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"],B=this.options.shared??"prompts",C=[...D];while(C.length>0){let[G,X]=C.pop(),Y=z.find((Q)=>G.startsWith(`${Q}/`));if(Y===void 0)continue;for(let[,Q]of X.matchAll(n)){let V=`${Y}/${Q.includes("/")?Q:`${B}/${Q}`}.md`,Z=D.has(V)?void 0:$(V);if(Z===void 0)continue;D.set(V,Z),C.push([V,Z])}}return[...D.values()].flatMap((G)=>W.pieces(G)).sort((G,X)=>X.length-G.length)}}function a(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class H extends Error{constructor(D){super(`${D} Record again.`);this.name="RecordingMismatchError"}}var o=/[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,B])=>[z,T(B,$)]));return D}function f(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 u(){let D;return{promise:new Promise((z)=>D=z),resolve:D}}var r=(D)=>s("sha256").update(D).digest("hex"),E=(D)=>D.flatMap(($)=>("tools"in $)?$.tools:[$]);function x(D){return D.map(({role:$,content:z})=>({role:$,parts:(Array.isArray(z)?z:[]).flatMap((B)=>{if(B?.type==="tool-call")return[{call:B.name,input:B.input??B.args}];if(B?.type==="tool-result")return[{result:B.name,status:B.status}];if(B?.type==="file")return[{file:!0}];return[]})}))}class M extends g{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,B){super();this.live=D;if(this.options={...z,match:z.match??"wording",ids:new RegExp(z.ids??o,"g"),waitMs:z.waitMs??60000},B){let{parent:C}=B;this.parent=C,this.key=B.key,this.model=C.model,this.capabilities=C.capabilities,this.recordedAt=C.recordedAt,this.calls=B.calls,this.recordedNested={},this.uploads=C.uploads,this.shared=C.shared;return}if(this.shared={ids:new Map,stale:new Set,staleCalls:0,started:0,moved:u()},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 W($.fingerprints,z.fingerprints)}static record(D,$={}){return new M(D,void 0,$)}static replay(D,$={}){return new M(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 H(`The recording has no sub-run "${D}".`);$=new M(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 W.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new W(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,B=z.shared.started++,C=this.read;this.read=void 0;let G=[],X=D.messages.map((Q)=>({...Q,content:Q.content.map((V)=>V.type==="file"&&V.fileId&&this.uploads.has(V.fileId)?{...V,fileId:this.uploads.get(V.fileId)}:V)}));for await(let Q of this.live.stream({...D,messages:X})){let V=G.at(-1);if(Q.type==="tool-call-discard"){let Z=new Set(Q.toolCallIds),L=G.filter((I)=>I.type!=="tool-call-delta"||!Z.has(I.toolCallId));G.splice(0,G.length,...L)}else if(Q.type==="retry");else if(V&&(Q.type==="text-delta"||Q.type==="output-delta")&&V.type===Q.type)V.delta+=Q.delta;else if(V?.type==="tool-call-delta"&&Q.type==="tool-call-delta"&&V.toolCallId===Q.toolCallId)V.argsDelta+=Q.argsDelta;else G.push({...Q});yield Q}let Y=this.options.position?await this.options.position():void 0;this.calls.push({request:$,events:G,at:B,...C!==void 0?{read:C}:{},...Y!==void 0?{ended:Y}:{}})}async*replayCall(D,$){let z=this.parent??this,B=this.where(),C=this.calls[0];if(this.options.ordered&&C?.at!==void 0)await z.turn(C.at,B);let G=this.calls.shift();if(!G)throw new H(`${B}: call ${this.sentCalls} was not recorded (the recording has no more calls).`);let{promptCacheKey:X,...Y}=G.request;if(!z.matches(JSON.stringify(Y),$))z.tolerate(B,{...G,request:Y},$,D.tools??[]);if(G.ended!==void 0)await z.reach(G.ended,B);let Q=z.shared.ids;for(let V of G.events)yield JSON.parse(JSON.stringify(V).replace(this.options.ids,(Z)=>Q.get(Z)??Z))}where(){return this.key===void 0?"the recording":`sub-run "${this.key}"`}sentCalls=0;requestOf(D){this.sentCalls++;let{signal:$,promptCacheKey:z,messages:B,tools:C,...G}=D,X=B.map(({role:L,content:I})=>({role:L,content:f(I)})),Y=this.sent.length>0&&this.sent.length<=X.length&&JSON.stringify(X.slice(0,this.sent.length))===JSON.stringify(this.sent)?this.sent.length:0;this.sent=X;let Q=C&&C.length>0?JSON.stringify(C):void 0,V=this.parent??this,Z=(L)=>{return V.texts.add(L),L};if(T([G,X.slice(Y)],Z),Q&&!V.toolLists.has(Q)){V.toolLists.add(Q);for(let L of E(C)){T(L,Z);let I=V.toolHashes.get(L.name)??new Set;I.add(W.tool(L)),V.toolHashes.set(L.name,I)}}return{...f(G),...Q?{tools:`sha256:${r(Q)}`,toolNames:E(C).map((L)=>L.name).sort()}:{},...Y>0?{after:Y}:{},messages:X.slice(Y)}}matches(D,$){let z=this.options.ids,B=JSON.stringify($),C=D.match(z)??[],G=B.match(z)??[];if(C.length!==G.length)return!1;let X=new Map(this.shared.ids);for(let[Y,Q]of C.entries()){let V=X.get(Q)??G[Y];if(V!==G[Y])return!1;X.set(Q,V)}if(D.replace(z,(Y)=>X.get(Y))!==B)return!1;for(let[Y,Q]of X)this.shared.ids.set(Y,Q);return!0}tolerate(D,$,z,B){let C=this.options.ids,G=this.options.match,X=$.request,Y=(A,K,J)=>{let N=JSON.stringify(A).replace(C,"<id>"),j=JSON.stringify(K).replace(C,"<id>"),_=0;while(_<N.length&&N[_]===j[_])_++;throw new H(`${D}: the request differs from the recorded one${J}. Recorded: \u2026${N.slice(Math.max(0,_-80),_+120)}\u2026 Sent: \u2026${j.slice(Math.max(0,_-80),_+120)}\u2026`)};if(G==="exact")Y(X,z,"");let{tools:Q,toolNames:V,...Z}=X,{tools:L,toolNames:I,...k}=z,w=[];if(!this.matches(JSON.stringify(Z),k))if(G==="wording"){if(!this.recorded)Y(Z,k,", and the recording has no fingerprints to tell a reworded prompt by");try{this.cuts??=this.recorded.cutters()}catch(J){throw new H(`${D}: ${J.message}.`)}let A=T(Z,this.cuts.recorded),K=T(k,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(A),K))Y(A,K,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");w.push(...this.cuts.changed.map((J)=>`${J} changed`))}else{if(!((X.after??0)===(z.after??0)&&this.matches(JSON.stringify(x(X.messages)),x(z.messages))))Y(Z,k," in the conversation itself");let{messages:K,...J}=Z,{messages:N,...j}=k;if(!this.matches(JSON.stringify(K),N))w.push("message text changed");let _=new Set([...Object.keys(J),...Object.keys(j)]);for(let U of[..._].sort()){let O=JSON.stringify(J[U]??null);if(!this.matches(O,j[U]??null))w.push(`${U} changed`)}}if(Q!==L){let A=E(B);for(let K of $.events){if(K.type!=="tool-call")continue;let J=A.find((O)=>O.name===K.name);if(!J)throw new H(`${D}: the recorded answer calls ${K.name}, which is not offered any more.`);let N=Object.fromEntries([...JSON.stringify(J.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,O])=>[O,!0])),j;try{j=JSON.parse(K.args||"{}")}catch{j=void 0}let _;try{_=m.fromJSONSchema(J.parameters,{unknownKeys:"error",formats:N})}catch(O){if(!(O instanceof v))throw O}let U=_?.safeParse(j);if(U&&U.ok===!1)throw new H(`${D}: the recorded call of ${K.name} does not fit its schema any more (${U.errors.join("; ")}).`)}if(this.recorded){let K=A.filter((J)=>!this.recorded.data.tools[J.name]?.includes(W.tool(J))).map((J)=>J.name).sort();w.push(K.length>0?`tools changed: ${K.join(", ")}`:"the tools offered changed")}else{let K=new Set(V??[]),J=new Set(I??[]),N=[...J].filter((_)=>!K.has(_)),j=[...K].filter((_)=>!J.has(_));w.push(N.length>0||j.length>0?`tools offered changed (${[...N.map((_)=>`+${_}`),...j.map((_)=>`-${_}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let A of w)this.shared.stale.add(A)}async turn(D,$){let z=this.shared;z.pending??=[...this.calls,...Object.values(this.recordedNested).flat()].map((B)=>B.at).filter((B)=>B!==void 0).sort((B,C)=>B-C);while(z.pending[0]!==void 0&&z.pending[0]<D){let B=z.moved.promise;if(!await Promise.race([B.then(()=>!0),new Promise((G)=>setTimeout(()=>G(!1),this.options.waitMs))]))throw new H(`${$}: call ${D} waits for call ${z.pending[0]}, which the replay does not make.`)}z.pending=z.pending.filter((B)=>B!==D),z.moved.resolve(),z.moved=u()}async reach(D,$){let z=this.options.position;if(!z)return;let B=await z(),C=0;while(B<D){await new Promise((X)=>setTimeout(X,25));let G=await z();if(C=G===B?C+25:0,B=G,C>=this.options.waitMs)throw new H(`${$}: a call waits for the app to reach ${D}; it stays at ${B}.`)}}}function t(D){let $=globalThis.Date,z=new $(D).getTime()-$.now();if(!Number.isFinite(z))throw Error(`pinClock: ${String(D)} is not a date.`);class B extends ${constructor(...C){if(C.length===0)super($.now()+z);else super(...C)}static now(){return $.now()+z}}return globalThis.Date=B,()=>{if(globalThis.Date===B)globalThis.Date=$}}export{t as pinClock,M as RecordingProvider,H as RecordingMismatchError,W as Fingerprints};
|
|
5
5
|
|
|
@@ -4,7 +4,7 @@ data: ${JSON.stringify($)}
|
|
|
4
4
|
|
|
5
5
|
`))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class V2 extends Error{}async function Y8($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new V2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new V2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function q3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function K8($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function Q8($){let Z;try{Z=new URL($)}catch{throw Error(`route.mcp.remote.url: "${$}" is not a URL.`)}let z=Z.hostname==="localhost"||Z.hostname==="127.0.0.1"||Z.hostname==="[::1]";if(Z.protocol!=="https:"&&!(Z.protocol==="http:"&&z))throw Error("route.mcp.remote.url must be https (http only on localhost): tokens travel to it.");if(Z.search||Z.hash||Z.username||Z.password)throw Error("route.mcp.remote.url must have no query, fragment or credentials.");if(Z.pathname==="/"||Z.pathname.endsWith("/"))throw Error('route.mcp.remote.url needs a path of its own, like "/mcp", without a trailing slash.');return Z}function U2($){return f3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function H8($){return f3("sha256").update(y3($??{})).digest("base64url")}function T3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function M3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function U8($,Z,z){if(Z.method!=="tools/call"||!z.e)return!1;let G=Z.params?.name;return typeof G==="string"&&$.descriptors({names:[G]})[0]?.requiresApproval===!0}function V8($){let z=(M($.params._meta)?$.params._meta:{}).progressToken;if(!$.stream||typeof z!=="string"&&typeof z!=="number")return;let G=-1/0;return(W)=>{if(typeof W?.progress!=="number"||!Number.isFinite(W.progress)||W.progress<=G)return;G=W.progress,$.stream.send({jsonrpc:"2.0",method:"notifications/progress",params:{progressToken:z,progress:W.progress,...typeof W.total==="number"?{total:W.total}:{},...typeof W.message==="string"?{message:W.message.slice(0,1000)}:{}}})}}function J8($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
|
|
6
6
|
|
|
7
|
-
Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function k3($){return M($)&&$.action==="accept"&&M($.content)&&$.content.approve===!0}function R3($){return v(b(null,new L(_.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function N8($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=F8($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y2($);return}let G;try{if(G=Z.locks?.()??B8(),$.onOneServer){let W=Math.floor((Z.now??Date.now())/60000);if(!await G.store.advance(`gemi:cron-tick:${$.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${$.name}; skipped it:`,W);return}if(z===void 0){await y2($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y2($,W))}catch(W){if(W instanceof h3)console.error(`Cron job ${$.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,W);else console.error(`Could not take the withoutOverlapping lock of cron job ${$.name}:`,W)}}var v3=300000;function F8($){if(!$)return;if($===!0)return v3;return $.expiresAfter??v3}var g3;function B8(){return g3??=new d(new m3),g3}async function y2($,Z){try{await $.onTick.call($)}catch(z){console.error(`Error executing cron job ${$.name}:`,z)}try{await $.callback.call($,Z)}catch(z){console.error(`Error in cron job ${$.name}:`,z)}try{await $.onComplete.call($)}catch(z){console.error(`Error completing cron job ${$.name}:`,z)}}class c{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor($){this.resolved=$.jobs}get jobs(){return[...this.resolved]}useJobs($){this.resolved=$}useLocks($){this.locks=$}start($=(Z)=>Z()){if(this.stopped=!1,this.resolved.length===0)return;let Z=globalThis.__gemiCronJobs??=new Map,z=new Map;for(let G of this.resolved){let W=new G;if(!W.name){console.error(`Cron job must have a name \u2014 ${G.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let X=z.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${G.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}z.set(W.name,G.name||"an anonymous class"),Z.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(W.name,()=>$(()=>N8(W,{locks:K})))});Z.set(W.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let $ of this.handles)$.stop();this.handles=[]}async drain($=1/0){this.stop();let Z,z=new Promise((G)=>{if($!==1/0)Z=setTimeout(G,$)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((G)=>G.done)),z]),clearTimeout(Z),{unfinished:[...this.inFlight.values()].map((G)=>({...G.tick}))}}get running(){return this.inFlight.size}track($,Z){let z={},G=Promise.resolve().then(Z).finally(()=>this.inFlight.delete(z));return this.inFlight.set(z,{tick:{name:$,startedAt:new Date},done:G}),G}}import{isMainThread as P8}from"worker_threads";var I8=100,L8=($)=>Math.min(I8,Math.floor($/10));class _8 extends B{register(){this.app.singleton(q,()=>new q(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(d,()=>this.app.make(q).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=S(u3(),$);if($.jobs===void 0)this.app.make(q).useJobs(await l3(Z));if($.workflows===void 0){let G=await n3(z);if(G.length>0)this.app.make(q).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(q))return;let Z=this.app.make(q);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running queued job(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-L8(z)));if(G.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+G.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function s9($){if(O8($),Bun.env.NODE_ENV!=="production")return j8($);if(t3($))return;if(!c3())return;if(!$.bound(q))return;$.make(q).start()}function t3($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof d3}function D8($){if(t3($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(q))return!1;try{return!$.make(q).durable}catch{return!1}}function O8($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||i3())return;if(process.env.ROOT_DIR===void 0||!P8)return;if(p3()){if(!D8($))return;console.warn('[gemi] GEMI_QUEUE_CLAIM=off is ignored: the memory queue driver keeps jobs in the process that dispatched them, so no worker could run them. This server runs its own jobs. Use a driver other processes can read, such as "database", to hand jobs to `gemi queue:work`.')}else if(Z.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${Z}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function j8($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(q))$.make(q).start()}var A8=new Set,x8={refusal:null,apply:($)=>$,carried:null};async function X$($){let Z=E(s);if(Z.config.global.length===0)return x8;let{pathname:z}=new URL($.url),G=r3(z),W=new u($,{},G?"api":"view","");return await m.run(W,async()=>{let X=m.getStore(),{headers:Y,cookies:K}=X,Q=(H)=>{if(!g2(H)){let V=v2(H,Y,K);return G?V:S8(V,z)}let U=new Headers(Y);return U.delete("Set-Cookie"),v2(H,U,A8)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(H){let U=!G&&C8(z);if(H?.kind===s3){let V=G?W$(H.payload.api):U?z$(H.payload.viewData??H.payload.api):w2(H.payload.view);return{refusal:Q(V),apply:Q,carried:null}}if(o3(H)&&(G||U))return{refusal:Q(G$()),apply:Q,carried:null};if(a3(H)){console.error(H);let V=G||U?$$():w2(Z$());return{refusal:Q(V),apply:Q,carried:null}}throw H}finally{X.destroy()}})}function C8($){if(!$.endsWith(".json"))return!1;let Z=E().config;if(!Z.get("route.api")||!Z.get("route.view"))return!0;return E(o).viewDispatchers().every((z)=>e3(z.flatViewRoutes,$))}function S8($,Z){if(!g2($)||$.headers.getSetCookie().length===0)return $;try{return f2($.headers,Z),$}catch{let z=new Headers($.headers);return f2(z,Z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}var q8=120,T8=2000,M8=3;class r{manager;application;static token="broadcast.sockets";server=null;sockets=new Set;byTopic=new Map;topicReady=new Map;perIp=new Map;perUser=new Map;connections=0;revocationSeq=0;revokedAt=new Map;closing=!1;closed=null;onAllClosed=null;startPromise=null;constructor($,Z){this.manager=$;this.application=Z}get config(){return this.manager.config}matches($){try{return new URL($.url).pathname===this.config.path}catch{return!1}}get size(){return this.sockets.size}start($){return this.server=$,this.startPromise??=this.manager.start((Z,z)=>this.deliver(Z,z),{onGap:()=>this.onGap(),onRevoke:(Z)=>this.applyRevocation(Z)}).catch((Z)=>{this.startPromise=null,console.error("[gemi] The broadcast driver could not start; events reach no socket.",Z)}),this.startPromise}upgrade($,Z){return this.run(()=>this.tryUpgrade($,Z))}async tryUpgrade($,Z){if(this.closing||u2())return f(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return f(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(J2))return f(400,`Open the socket with the "${J2}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return f(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return f(503,"Too many connections.",{"Retry-After":"10"});let W=b8($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return f(429,"Too many connections from this address.",{"Retry-After":"30"});let X=this.reserve(W),Y=!1;try{let K=await this.authenticate($,Z,X);return Y=K===void 0,K}finally{if(!Y)this.release(X)}}async authenticate($,Z,z){let G=await X$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||u2())return f(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let U=new u($,{},"api",this.config.path);X=await m.run(U,async()=>{let V=m.getStore();try{return await U$(U)}finally{V.destroy()}},W)}catch(U){return console.error("[gemi] Resolving the session of a socket upgrade failed.",U),f(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=E8(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return f(429,"Too many connections for this user.",{"Retry-After":"30"});if(Y)z.userId=Y,this.perUser.set(Y,(this.perUser.get(Y)??0)+1);let K=H$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:Q$(K),request:{url:$.url,headers:[...$.headers]},carried:W,userId:Y,ip:z.ip,subs:new Map,topics:new Map,rate:{windowStart:Date.now(),subs:0,pings:0},reservation:z,closing:!1,closed:!1};if(!Z.upgrade($,{headers:{"Sec-WebSocket-Protocol":J2},data:Q}))return f(400,"The WebSocket upgrade failed.");return}checkOrigin($){let Z=$.headers.get("origin"),z=Boolean($.headers.get("cookie"));if(!Z)return z?"A socket that carries cookies must send an Origin header.":!0;return this.originAllowed(Z,$)?!0:"This origin may not open a socket."}originAllowed($,Z){let z;try{z=new URL($)}catch{return!1}if(z.protocol!=="https:"&&z.protocol!=="http:")return!1;let G=Z.headers.get("host");if(G&&z.host.toLowerCase()===G.toLowerCase())return!0;for(let W of[process.env.APP_URL,process.env.HOST_NAME,...this.config.allowedOrigins])if(W&&k8(W.trim(),z))return!0;return!1}reserve($){if(this.connections++,$)this.perIp.set($,(this.perIp.get($)??0)+1);return{ip:$,userId:null}}release($){this.connections--,Y$(this.perIp,$.ip),Y$(this.perUser,$.userId)}get websocket(){return{open:($)=>$.data.hub.onOpen($),message:($,Z)=>$.data.hub.onMessage($,Z),close:($)=>$.data.hub.onClose($),...this.socketOptions()}}socketOptions(){return{maxPayloadLength:this.config.maxInboundMessageBytes,idleTimeout:this.config.idleTimeout,backpressureLimit:this.config.backpressureLimit*2,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1}}onOpen($){let Z=$.data;if(this.closing){this.sayBye($);return}this.sockets.add($),a($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(k.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(k.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(k.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))a($,{op:"pong"});return;case"sub":this.subscribe($,z).catch((G)=>{if(console.error("[gemi] A socket subscription failed.",G),typeof z.id==="string"&&$.data.subs.has(z.id)){let W=$.data.subs.get(z.id);if($.data.subs.delete(z.id),W.topic&&!$.data.closed)this.leave($,W.topic);if(!$.data.closed)y($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(k.UnsupportedData,"Unknown op.")}}onClose($){let Z=$.data;if(Z.closed)return;Z.closed=!0;for(let[,z]of Z.subs)if(z.topic)this.leave($,z.topic);if(Z.subs.clear(),this.sockets.delete($),Z.reservation)this.release(Z.reservation),Z.reservation=null;if(this.closing&&this.sockets.size===0)this.onAllClosed?.()}rateWindow($){let Z=$.data.rate,z=Date.now();if(z-Z.windowStart>=this.config.subscribeRate.windowMs)Z.windowStart=z,Z.subs=0,Z.pings=0;return Z}countSub($){let{limit:Z}=this.config.subscribeRate,z=this.rateWindow($);if(z.subs++,z.subs>Z*2)return console.warn("[gemi] Socket closed for sending too many subscribe frames (1008)."),$.close(k.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=q8)return!0;return $.close(k.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!d2.test(G)){$.close(k.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return y($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!R8(Y))return y($,G,"invalid");if(z.subs.has(G))return y($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return y($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),y($,G,"unknown_channel");let Q;for(let H=1;;H++){let U=this.revocationSeq;if(Q=await this.authorize($,K),z.closed||z.subs.get(G)!==K)return;if(Q.ok!==!0)break;if((this.revokedAt.get(Q.topic)??0)<=U)break;if(H>=M8)return z.subs.delete(G),y($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),y($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(H){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,H),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);y($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;a($,{op:"subscribed",id:G,t:Q.topic})}authorize($,Z){let z=$.data,G=this.manager.channels;if(!G)return Promise.resolve({ok:!1,code:"unknown_channel"});return this.run(()=>G.authorize(new Request(z.request.url,{headers:z.request.headers}),Z.pattern,Z.params,{carried:z.carried}))}unsubscribeFrame($,Z){let z=Z.id;if(typeof z!=="string"||!d2.test(z)){$.close(k.UnsupportedData,"An unsub needs an id.");return}let G=$.data.subs.get(z);if(!G)return;if($.data.subs.delete(z),G.topic)this.leave($,G.topic)}join($,Z){let z=$.data,G=z.topics.get(Z)??0;if(z.topics.set(Z,G+1),G===0){$.subscribe(Z);let W=this.byTopic.get(Z);if(!W){W=new Set,this.byTopic.set(Z,W);let X=Promise.resolve().then(()=>this.manager.topicAdded(Z));this.topicReady.set(Z,X),X.catch(()=>{if(this.topicReady.get(Z)===X)this.topicReady.delete(Z)})}W.add($)}return this.topicReady.get(Z)??Promise.resolve()}leave($,Z){let z=$.data,G=z.topics.get(Z)??0;if(G>1){z.topics.set(Z,G-1);return}if(z.topics.delete(Z),!z.closed)$.unsubscribe(Z);let W=this.byTopic.get(Z);if(!W)return;if(W.delete($),W.size>0)return;this.byTopic.delete(Z),this.topicReady.delete(Z),Promise.resolve().then(()=>this.manager.topicRemoved(Z)).catch((X)=>console.error(`[gemi] The broadcast driver could not unsubscribe from "${Z}".`,X))}deliver($,Z){let z=this.byTopic.get($);if(!z||!this.server)return;let G=this.config.backpressureLimit;for(let W of z)if(!W.data.closing&&W.getBufferedAmount()>G)console.warn(`[gemi] Socket closed for backpressure (1013) on "${$}".`),h2(W,k.TryAgainLater,"Too far behind; reconnect.");this.server.publish($,Z)}onGap(){this.sendAll({op:"gap"});for(let $ of this.byTopic.keys()){let Z=Math.floor(Math.random()*T8);setTimeout(()=>{if(!this.closing)this.applyRevocation({topic:$})},Z).unref?.()}}applyRevocation($){if("user"in $){for(let W of this.sockets)if(W.data.userId===$.user&&!W.data.closing)h2(W,k.Revoked,"Revoked.");return}let Z=$.topic,z=++this.revocationSeq;this.revokedAt.set(Z,z);let G=this.byTopic.get(Z);if(!G)return;for(let W of G)this.reauthorize(W,Z,z)}async reauthorize($,Z,z){let G=$.data,W=[...G.subs].filter(([,Y])=>Y.topic===Z);if(W.length===0)return;$.unsubscribe(Z);let X=await Promise.all(W.map(([,Y])=>this.authorize($,Y).catch((K)=>{return console.error(`[gemi] Authorizing "${Z}" again after a revoke failed.`,K),{ok:!1,code:"revoked"}})));if(G.closed)return;if(this.revokedAt.get(Z)!==z)return;if(W.forEach(([Y,K],Q)=>{let H=X[Q];if(G.subs.get(Y)!==K)return;if(H.ok===!0&&H.topic===Z)return;G.subs.delete(Y),this.leave($,Z),y($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)a($,{op:"subscribed",id:Y,t:Z})}sendAll($){let Z=JSON.stringify($);for(let z of this.sockets)z.send(Z)}shutdown($={}){if(this.closed)return this.closed;this.closing=!0,this.closed=new Promise((G)=>{this.onAllClosed=G});let Z=[...this.sockets];if(Z.length===0)this.onAllClosed?.();if(Z.length>0)console.log(`[gemi] Closing ${Z.length} broadcast socket(s) (1012).`);for(let G of Z)this.sayBye(G);return setTimeout(()=>{for(let G of Z)try{G.terminate()}catch{}this.onAllClosed?.()},$.terminateAfterMs??2000).unref?.(),this.closed}get isClosing(){return this.closing}sayBye($){a($,{op:"bye",code:k.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),h2($,k.Restart,"Server restarting.")}run($){return N2.run(this.application,$)}}function k8($,Z){let z=/^(?:(https?):\/\/)?\*\.([^/:]+)(?::(\d+))?\/?$/i.exec($);if(z){let[,G,W,X]=z;if(G&&`${G.toLowerCase()}:`!==Z.protocol)return!1;if((X??"")!==Z.port)return!1;return Z.hostname.toLowerCase().endsWith(`.${W.toLowerCase().replace(/\.$/,"")}`)}if(/^https?:\/\//i.test($))try{return new URL($).origin===Z.origin}catch{return!1}return $.toLowerCase().replace(/\/$/,"")===Z.host.toLowerCase()}function h2($,Z,z){$.data.closing=!0,$.close(Z,z)}function a($,Z){$.send(JSON.stringify(Z))}function y($,Z,z){a($,{op:"denied",id:Z,code:z})}function f($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function R8($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function E8($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function b8($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return m2(K$(z)??z);try{let G=Z.requestIP($)?.address;return G?m2(G):null}catch{return null}}function Y$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class y8 extends B{register(){this.app.singleton(g,()=>new g(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(r,()=>new r(this.app.make(g),this.app))}boot(){let $=this.app.config.get("route.channels");if($)J$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(g).driver:void 0;f8(Z,process.env,z)}async shutdown(){if(this.app.resolved(r))this.app.make(r).shutdown();if(!this.app.resolved(g))return;await this.app.make(g).close()}}function f8($,Z=process.env,z){if(!($.driver==="redis"||z instanceof V$)||Z.SECRET)return;let W=`[gemi] The "redis" broadcast driver needs SECRET set, the same on every instance: Broadcast.toOthers tags the sender's socket with a key derived from it, and every instance must derive the same one.`;if(Z.NODE_ENV==="production")throw Error(W);console.warn(W)}class w8 extends B{register(){this.app.singleton(c2,()=>new c2(this.app.config.get("cache",{}),{application:this.app}))}}class v8 extends B{register(){this.app.singleton(G2,()=>new G2(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(G2))return;await this.app.make(G2).close()}}class g8 extends B{register(){this.app.singleton(i2,()=>new i2(this.app.config.get("auth",{}))),this.app.singleton(p2,()=>{let $=this.app.config.get("auth",{});return new p2({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){let $=this.app.config.get("auth",{});F$($),N$($?.emailCode??{},{warn:!0})}}var h8=100,m8=($)=>Math.min(h8,Math.floor($/10));class u8 extends B{register(){this.app.singleton(c,()=>new c(S(l2(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(c),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=S(l2(),Z);$.useJobs(await B$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let z=this.app;if(z.bound(d))$.useLocks(()=>z.make(d));$.start((G)=>N2.run(z,G))}async shutdown($){if(!this.app.resolved(c))return;let Z=this.app.make(c);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running cron tick(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-m8(z)));if(G.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+G.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class e extends P${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return I$(this.modelName)}async load(){if(!this.available)throw new n2(this.modelName);let $=t2(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new n2(this.modelName);let G=t2(this.modelName),W=this.hasActorColumn(G),X={active:Z};if(W)X.updatedBy=z.actor;return await G.asSystem(()=>G.upsert({where:{key:$},create:{key:$,...X},update:X})),{actorRecorded:W}}hasActorColumn($){let Z=$?.$schema?.fields?.updatedBy;return Z!==void 0&&Z.type==="String"}}function rZ($){return $}function L$(){return{features:void 0,enabled:!0,source:new e,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class d8 extends B{register(){this.app.singleton(F2,()=>{let $=this.app.config.get("features",{}),Z=S(L$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new e($.model);else if($?.model!==void 0&&$.source instanceof e&&$.source.modelName!==$.model)B2.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new F2(Z,(z)=>B2.warning(z))})}async boot(){let $=this.app.make(F2);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){B2.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class c8 extends B{register(){this.app.singleton(s2,()=>new s2(this.app.config.get("mail",{})))}}class p8 extends B{register(){this.app.singleton(P2,()=>new P2(this.app.config.get("encryption",{})))}boot(){if(this.app.make(P2).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new o2(`auth.connections (${z.join(", ")}) keeps OAuth tokens encrypted, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`);let G=_$();if(G.length===0)return;throw new o2(`${G.join(", ")} ${G.length===1?"is an encrypted column":"are encrypted columns"}, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`)}}var i8=Symbol.for("gemi.broadcastEvent");function D$($){return typeof $==="object"&&$!==null&&$[i8]===!0}function l8($){return`listener:${$}`}function j$($,Z){n8($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends O${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,H]=t8(K),U=E(p).rehydrate(Q,H);await new $().handle(U)}onFail(K){console.error(`The listener ${$.name} threw while handling ${X} off the queue. The queue will retry it up to ${z} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${$.name} failed every one of its ${z} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,K)}};return Object.defineProperty(Y,"name",{value:l8($.name),writable:!0}),Y}function n8($){if(Object.getOwnPropertyDescriptor($,"name")?.writable)return;throw Error(`The listener ${$.name} sets \`queued = true\` but does not declare \`static name\`, so it would be registered with the queue `+"under its class name \u2014 which a production build renames while the "+`payload that names it does not. Add: static name = "${$.name}";`)}function t8($){return typeof $[0]==="string"?$:$[0]}class p{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=S(I2(),$),this.useListeners(this.config.listeners)}useListeners($){this.config.listeners=$,this.listeners={},this.events={};let Z=new Set;for(let z of $){if(!z.event){console.error(`Listener ${z.name} does not declare \`static event\`, so there is no event name to register it under and its handle will never run. Add: static event = SomeEvent;`);continue}if(Z.has(z.name)){console.error(`Two event listeners are named "${z.name}" \u2014 the first is `+"registered and this one is not. A listener's name identifies it across the framework, so only one class can hold it. Rename one.");continue}Z.add(z.name);let G=z.event.name,W=new z;this.events[G]??=z.event,(this.listeners[G]??=[]).push({listener:z,job:W.queued?j$(z,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:$})=>$?[$]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch($,Z){if(this.deferToCommit($,Z,!1))return;this.runListeners($,Z)}async dispatchAndWait($,Z){if(this.deferToCommit($,Z,!0))return;return this.runListeners($,Z)}deferToCommit($,Z,z){let{name:G,afterCommit:W}=$.constructor;if(!W)return!1;let X=A$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=D$($);if(G.length===0&&!W){this.warnNothingIsListening(z);return}for(let{listener:X,job:Y}of G){if(Y){this.enqueue(Y,X,z,Z);continue}try{await new X().handle($)}catch(K){console.error(`The listener ${X.name} threw while handling ${z}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",K)}}if(W)this.broadcast($,z)}broadcast($,Z){try{E(g).broadcastEvent($)}catch(z){console.error(`The event ${Z} could not be broadcast.`,z)}}rehydrate($,Z=[]){let z=this.events[$];if(!z)throw Error(`Cannot rebuild the event "${$}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${$}"\`.`);return new z(...Z)}enqueue($,Z,z,G){if(G===void 0){console.error(`The listener ${Z.name} is queued, but ${z} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${z}.dispatch(...) or ${z}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${Z.name} could not be queued for ${z}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{E(q).push($,JSON.stringify([z,G]),{reportFailure:!1}).catch(W)}catch(X){W(X)}}warnNothingIsWaitedFor($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has($))return;this.warnedAboutWaiting.add($),console.warn(`[gemi] ${$}.dispatchAndWait() was called inside a transaction and ${$} declares \`static afterCommit = true\`, so it resolved `+"immediately with no listener having run \u2014 they run when the "+"transaction commits. Await the transaction instead, or drop afterCommit if the caller needs the side effects first. Development only.")}warnNothingIsListening($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has($))return;this.warnedFor.add($),console.warn(`[gemi] ${$} was dispatched and nothing is listening for it. A listener registers under the name its event declares, so check that app/listeners holds a Listener with \`static event = ${$}\` and that ${$} declares \`static name = "${$}"\`. Development only.`)}}class s8 extends B{register(){this.app.singleton(p,()=>new p(this.app.config.get("events",{})))}async boot(){let $=this.app.make(p),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=S(I2(),Z);$.useListeners(await x$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(q);for(let W of z)G.registerJob(W)}}class o8 extends B{register(){this.app.singleton(a2,()=>new a2(this.app.config.get("filesystem",{})))}}class a8 extends B{register(){this.app.singleton(r2,()=>new r2(this.app.config.get("image",{})))}}class r8 extends B{register(){this.app.instance(e2,new e2)}}class e8 extends B{register(){this.app.singleton(L2,()=>new L2(S(C$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(L2).boot()}}class $9 extends B{register(){this.app.singleton(s,()=>new s(S(S$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(s).assertGlobalMiddleware()}}function z7($){return $}function T$(){return{driver:new q$,limit:1000,window:60}}class Z9 extends B{register(){this.app.singleton(t,()=>new t(S(T$(),this.app.config.get("ratelimiter",{}))))}}function H7($){return $}function M$(){return{url:process.env.REDIS_URL,options:void 0}}class z9 extends B{register(){this.app.singleton(W2,()=>new W2(S(M$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(W2))return;this.app.make(W2).close()}}function _2($,Z){let z=$.get(Z);if(!z)throw Error(`Missing "${Z}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return z}class G9 extends B{register(){this.app.singleton($2,()=>new $2(_2(this.app.config,"route.api"))),this.app.singleton(X2,()=>new X2(_2(this.app.config,"route.view"),this.app.config.get("auth",{}))),this.app.singleton(o,()=>new o({api:this.app.make($2),view:this.app.make(X2)},{api:_2(this.app.config,"route.api"),view:_2(this.app.config,"route.view"),auth:this.app.config.get("auth",{}),domains:this.app.config.get("route.domains"),clientIpTrust:k$(process.env)})),this.app.singleton(n,()=>{let $=this.app.config.get("route.mcp");if(!$?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new n(new $.router,this.app.make($2),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton(z2,()=>{let $=this.app.config.get("route.mcp");if(!$?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new z2(this.app.make(n),$.remote)})}boot(){if(this.app.make($2),this.app.make(X2),this.app.make(o),this.app.config.get("route.mcp"))this.app.make(n);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make(z2);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class W9 extends B{register(){this.app.singleton($3,()=>new $3(this.app.config.get("runs",{}),{application:this.app}))}}
|
|
7
|
+
Arguments: ${G}`,requestedSchema:{type:"object",properties:{approve:{type:"boolean",title:"Approve",description:`Run "${$.title??$.name}" with these arguments.`}},required:["approve"]}}}function k3($){return M($)&&$.action==="accept"&&M($.content)&&$.content.approve===!0}function R3($){return v(b(null,new L(_.InvalidRequest,"Rate limit exceeded.")),429,{"Retry-After":String($)})}async function N8($,Z={}){try{if(!await $.shouldRun.call($))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${$.name}:`,W);return}let z=F8($.withoutOverlapping);if(!$.onOneServer&&z===void 0){await y2($);return}let G;try{if(G=Z.locks?.()??B8(),$.onOneServer){let W=Math.floor((Z.now??Date.now())/60000);if(!await G.store.advance(`gemi:cron-tick:${$.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${$.name}; skipped it:`,W);return}if(z===void 0){await y2($);return}try{await G.run(`gemi:cron:${$.name}`,{ttl:z},(W)=>y2($,W))}catch(W){if(W instanceof h3)console.error(`Cron job ${$.name} lost its withoutOverlapping lock while running: another tick may have started alongside it.`,W);else console.error(`Could not take the withoutOverlapping lock of cron job ${$.name}:`,W)}}var v3=300000;function F8($){if(!$)return;if($===!0)return v3;return $.expiresAfter??v3}var g3;function B8(){return g3??=new d(new m3),g3}async function y2($,Z){try{await $.onTick.call($)}catch(z){console.error(`Error executing cron job ${$.name}:`,z)}try{await $.callback.call($,Z)}catch(z){console.error(`Error in cron job ${$.name}:`,z)}try{await $.onComplete.call($)}catch(z){console.error(`Error completing cron job ${$.name}:`,z)}}class c{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor($){this.resolved=$.jobs}get jobs(){return[...this.resolved]}useJobs($){this.resolved=$}useLocks($){this.locks=$}start($=(Z)=>Z()){if(this.stopped=!1,this.resolved.length===0)return;let Z=globalThis.__gemiCronJobs??=new Map,z=new Map;for(let G of this.resolved){let W=new G;if(!W.name){console.error(`Cron job must have a name \u2014 ${G.name||"an anonymous class"} has none, so it is not scheduled. If this is a base class that other jobs extend, move it out of the discovered directory: \`abstract\` does not survive to runtime, so a class under app/cron is indistinguishable from a job.`);continue}if(!W.cron){console.error(`Cron job must have an expression. Job: ${W.name}`);continue}let X=z.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${G.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}z.set(W.name,G.name||"an anonymous class"),Z.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let K=this.locks;return this.track(W.name,()=>$(()=>N8(W,{locks:K})))});Z.set(W.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let $ of this.handles)$.stop();this.handles=[]}async drain($=1/0){this.stop();let Z,z=new Promise((G)=>{if($!==1/0)Z=setTimeout(G,$)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((G)=>G.done)),z]),clearTimeout(Z),{unfinished:[...this.inFlight.values()].map((G)=>({...G.tick}))}}get running(){return this.inFlight.size}track($,Z){let z={},G=Promise.resolve().then(Z).finally(()=>this.inFlight.delete(z));return this.inFlight.set(z,{tick:{name:$,startedAt:new Date},done:G}),G}}import{isMainThread as P8}from"worker_threads";var I8=100,L8=($)=>Math.min(I8,Math.floor($/10));class _8 extends B{register(){this.app.singleton(q,()=>new q(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(d,()=>this.app.make(q).locks)}async boot(){let $=this.app.config.get("queue",{}),{jobsDir:Z,workflowsDir:z}=S(u3(),$);if($.jobs===void 0)this.app.make(q).useJobs(await l3(Z));if($.workflows===void 0){let G=await n3(z);if(G.length>0)this.app.make(q).useWorkflows(G)}}async shutdown($){if(!this.app.resolved(q))return;let Z=this.app.make(q);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running queued job(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-L8(z)));if(G.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+G.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function s9($){if(O8($),Bun.env.NODE_ENV!=="production")return j8($);if(t3($))return;if(!c3())return;if(!$.bound(q))return;$.make(q).start()}function t3($){let Z=$.config.get("queue",{}).driver??"memory";return Z==="memory"||Z instanceof d3}function D8($){if(t3($))return!0;if(typeof $.config.get("queue",{}).driver!=="function"||!$.bound(q))return!1;try{return!$.make(q).durable}catch{return!1}}function O8($){let Z=process.env.GEMI_QUEUE_CLAIM;if(Z===void 0||i3())return;if(process.env.ROOT_DIR===void 0||!P8)return;if(p3()){if(!D8($))return;console.warn('[gemi] GEMI_QUEUE_CLAIM=off is ignored: the memory queue driver keeps jobs in the process that dispatched them, so no worker could run them. This server runs its own jobs. Use a driver other processes can read, such as "database", to hand jobs to `gemi queue:work`.')}else if(Z.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${Z}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function j8($){let Z=globalThis.__gemiDevQueue;if(!Z)return;if(globalThis.__gemiDevQueue=void 0,Z.stop(),$.bound(q))$.make(q).start()}var A8=new Set,x8={refusal:null,apply:($)=>$,carried:null};async function X$($){let Z=E(s);if(Z.config.global.length===0)return x8;let{pathname:z}=new URL($.url),G=r3(z),W=new u($,{},G?"api":"view","");return await m.run(W,async()=>{let X=m.getStore(),{headers:Y,cookies:K}=X,Q=(H)=>{if(!g2(H)){let V=v2(H,Y,K);return G?V:S8(V,z)}let U=new Headers(Y);return U.delete("Set-Cookie"),v2(H,U,A8)};try{return await Z.runGlobalMiddleware(),{refusal:null,apply:Q,carried:{user:X.user,state:W.state}}}catch(H){let U=!G&&C8(z);if(H?.kind===s3){let V=G?W$(H.payload.api):U?z$(H.payload.viewData??H.payload.api):w2(H.payload.view);return{refusal:Q(V),apply:Q,carried:null}}if(o3(H)&&(G||U))return{refusal:Q(G$()),apply:Q,carried:null};if(a3(H)){console.error(H);let V=G||U?$$():w2(Z$());return{refusal:Q(V),apply:Q,carried:null}}throw H}finally{X.destroy()}})}function C8($){if(!$.endsWith(".json"))return!1;let Z=E().config;if(!Z.get("route.api")||!Z.get("route.view"))return!0;return E(o).viewDispatchers().every((z)=>e3(z.flatViewRoutes,$))}function S8($,Z){if(!g2($)||$.headers.getSetCookie().length===0)return $;try{return f2($.headers,Z),$}catch{let z=new Headers($.headers);return f2(z,Z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}var q8=120,T8=2000,M8=3;class r{manager;application;static token="broadcast.sockets";server=null;sockets=new Set;byTopic=new Map;topicReady=new Map;perIp=new Map;perUser=new Map;connections=0;revocationSeq=0;revokedAt=new Map;closing=!1;closed=null;onAllClosed=null;startPromise=null;constructor($,Z){this.manager=$;this.application=Z}get config(){return this.manager.config}matches($){try{return new URL($.url).pathname===this.config.path}catch{return!1}}get size(){return this.sockets.size}start($){return this.server=$,this.startPromise??=this.manager.start((Z,z)=>this.deliver(Z,z),{onGap:()=>this.onGap(),onRevoke:(Z)=>this.applyRevocation(Z)}).catch((Z)=>{this.startPromise=null,console.error("[gemi] The broadcast driver could not start; events reach no socket.",Z)}),this.startPromise}upgrade($,Z){return this.run(()=>this.tryUpgrade($,Z))}async tryUpgrade($,Z){if(this.closing||u2())return f(503,"The server is restarting.",{"Retry-After":"5"});if($.method!=="GET"||$.headers.get("upgrade")?.toLowerCase()!=="websocket")return f(426,"This endpoint only accepts WebSocket upgrades.",{Upgrade:"websocket"});if(!($.headers.get("sec-websocket-protocol")??"").split(",").map((K)=>K.trim()).includes(J2))return f(400,`Open the socket with the "${J2}" subprotocol.`);let G=this.checkOrigin($);if(G!==!0)return f(403,G);if(this.connections>=this.config.maxConnectionsPerProcess)return f(503,"Too many connections.",{"Retry-After":"10"});let W=b8($,Z);if(W&&(this.perIp.get(W)??0)>=this.config.maxConnectionsPerIp)return f(429,"Too many connections from this address.",{"Retry-After":"30"});let X=this.reserve(W),Y=!1;try{let K=await this.authenticate($,Z,X);return Y=K===void 0,K}finally{if(!Y)this.release(X)}}async authenticate($,Z,z){let G=await X$($);if(G.refusal)return G.refusal;let W=G.carried;if(this.closing||u2())return f(503,"The server is restarting.",{"Retry-After":"5"});let X;try{let U=new u($,{},"api",this.config.path);X=await m.run(U,async()=>{let V=m.getStore();try{return await U$(U)}finally{V.destroy()}},W)}catch(U){return console.error("[gemi] Resolving the session of a socket upgrade failed.",U),f(503,"The session could not be checked.",{"Retry-After":"5"})}let Y=E8(X);if(Y&&(this.perUser.get(Y)??0)>=this.config.maxConnectionsPerUser)return f(429,"Too many connections for this user.",{"Retry-After":"30"});if(Y)z.userId=Y,this.perUser.set(Y,(this.perUser.get(Y)??0)+1);let K=H$(),Q={gemiSocket:!0,hub:this,socketId:K,tag:Q$(K),request:{url:$.url,headers:[...$.headers]},carried:W,userId:Y,ip:z.ip,subs:new Map,topics:new Map,rate:{windowStart:Date.now(),subs:0,pings:0},reservation:z,closing:!1,closed:!1};if(!Z.upgrade($,{headers:{"Sec-WebSocket-Protocol":J2},data:Q}))return f(400,"The WebSocket upgrade failed.");return}checkOrigin($){let Z=$.headers.get("origin"),z=Boolean($.headers.get("cookie"));if(!Z)return z?"A socket that carries cookies must send an Origin header.":!0;return this.originAllowed(Z,$)?!0:"This origin may not open a socket."}originAllowed($,Z){let z;try{z=new URL($)}catch{return!1}if(z.protocol!=="https:"&&z.protocol!=="http:")return!1;let G=Z.headers.get("host");if(G&&z.host.toLowerCase()===G.toLowerCase())return!0;for(let W of[process.env.APP_URL,process.env.HOST_NAME,...this.config.allowedOrigins])if(W&&k8(W.trim(),z))return!0;return!1}reserve($){if(this.connections++,$)this.perIp.set($,(this.perIp.get($)??0)+1);return{ip:$,userId:null}}release($){this.connections--,Y$(this.perIp,$.ip),Y$(this.perUser,$.userId)}get websocket(){return{open:($)=>$.data.hub.onOpen($),message:($,Z)=>$.data.hub.onMessage($,Z),close:($)=>$.data.hub.onClose($),...this.socketOptions()}}socketOptions(){return{maxPayloadLength:this.config.maxInboundMessageBytes,idleTimeout:this.config.idleTimeout,backpressureLimit:this.config.backpressureLimit*2,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1}}onOpen($){let Z=$.data;if(this.closing){this.sayBye($);return}this.sockets.add($),a($,{op:"hello",socketId:Z.socketId,tag:Z.tag,heartbeatMs:this.config.heartbeatMs})}onMessage($,Z){if(typeof Z!=="string"){$.close(k.UnsupportedData,"Frames are JSON text.");return}if(Z.length>this.config.maxInboundMessageBytes){$.close(k.PolicyViolation,"Frame too large.");return}let z;try{z=JSON.parse(Z)}catch{$.close(k.UnsupportedData,"Frames are JSON text.");return}switch(z?.op){case"ping":if(this.countPing($))a($,{op:"pong"});return;case"sub":this.subscribe($,z).catch((G)=>{if(console.error("[gemi] A socket subscription failed.",G),typeof z.id==="string"&&$.data.subs.has(z.id)){let W=$.data.subs.get(z.id);if($.data.subs.delete(z.id),W.topic&&!$.data.closed)this.leave($,W.topic);if(!$.data.closed)y($,z.id,"error")}});return;case"unsub":this.unsubscribeFrame($,z);return;default:$.close(k.UnsupportedData,"Unknown op.")}}onClose($){let Z=$.data;if(Z.closed)return;Z.closed=!0;for(let[,z]of Z.subs)if(z.topic)this.leave($,z.topic);if(Z.subs.clear(),this.sockets.delete($),Z.reservation)this.release(Z.reservation),Z.reservation=null;if(this.closing&&this.sockets.size===0)this.onAllClosed?.()}rateWindow($){let Z=$.data.rate,z=Date.now();if(z-Z.windowStart>=this.config.subscribeRate.windowMs)Z.windowStart=z,Z.subs=0,Z.pings=0;return Z}countSub($){let{limit:Z}=this.config.subscribeRate,z=this.rateWindow($);if(z.subs++,z.subs>Z*2)return console.warn("[gemi] Socket closed for sending too many subscribe frames (1008)."),$.close(k.PolicyViolation,"Too many subscribe frames."),"closed";return z.subs>Z?"limited":"ok"}countPing($){let Z=this.rateWindow($);if(Z.pings++,Z.pings<=q8)return!0;return $.close(k.PolicyViolation,"Too many pings."),!1}async subscribe($,Z){let z=$.data,G=Z.id;if(typeof G!=="string"||!d2.test(G)){$.close(k.UnsupportedData,"A sub needs an id.");return}let W=this.countSub($);if(W==="closed")return;if(W==="limited")return y($,G,"rate_limited");let X=Z.ch,Y=Z.p??{};if(typeof X!=="string"||!R8(Y))return y($,G,"invalid");if(z.subs.has(G))return y($,G,"invalid");if(z.subs.size>=this.config.maxChannelsPerSocket)return y($,G,"limit");let K={pattern:X,params:Y,topic:null};if(z.subs.set(G,K),!this.manager.channels)return z.subs.delete(G),y($,G,"unknown_channel");let Q;for(let H=1;;H++){let U=this.revocationSeq;if(Q=await this.authorize($,K),z.closed||z.subs.get(G)!==K)return;if(Q.ok!==!0)break;if((this.revokedAt.get(Q.topic)??0)<=U)break;if(H>=M8)return z.subs.delete(G),y($,G,"error")}if(Q.ok!==!0)return z.subs.delete(G),y($,G,Q.code);K.topic=Q.topic;try{await this.join($,Q.topic)}catch(H){if(console.error(`[gemi] The broadcast driver could not subscribe to "${Q.topic}".`,H),z.subs.get(G)===K){if(z.subs.delete(G),!z.closed)this.leave($,Q.topic);y($,G,"error")}return}if(z.closed||z.subs.get(G)!==K)return;a($,{op:"subscribed",id:G,t:Q.topic})}authorize($,Z){let z=$.data,G=this.manager.channels;if(!G)return Promise.resolve({ok:!1,code:"unknown_channel"});return this.run(()=>G.authorize(new Request(z.request.url,{headers:z.request.headers}),Z.pattern,Z.params,{carried:z.carried}))}unsubscribeFrame($,Z){let z=Z.id;if(typeof z!=="string"||!d2.test(z)){$.close(k.UnsupportedData,"An unsub needs an id.");return}let G=$.data.subs.get(z);if(!G)return;if($.data.subs.delete(z),G.topic)this.leave($,G.topic)}join($,Z){let z=$.data,G=z.topics.get(Z)??0;if(z.topics.set(Z,G+1),G===0){$.subscribe(Z);let W=this.byTopic.get(Z);if(!W){W=new Set,this.byTopic.set(Z,W);let X=Promise.resolve().then(()=>this.manager.topicAdded(Z));this.topicReady.set(Z,X),X.catch(()=>{if(this.topicReady.get(Z)===X)this.topicReady.delete(Z)})}W.add($)}return this.topicReady.get(Z)??Promise.resolve()}leave($,Z){let z=$.data,G=z.topics.get(Z)??0;if(G>1){z.topics.set(Z,G-1);return}if(z.topics.delete(Z),!z.closed)$.unsubscribe(Z);let W=this.byTopic.get(Z);if(!W)return;if(W.delete($),W.size>0)return;this.byTopic.delete(Z),this.topicReady.delete(Z),Promise.resolve().then(()=>this.manager.topicRemoved(Z)).catch((X)=>console.error(`[gemi] The broadcast driver could not unsubscribe from "${Z}".`,X))}deliver($,Z){let z=this.byTopic.get($);if(!z||!this.server)return;let G=this.config.backpressureLimit;for(let W of z)if(!W.data.closing&&W.getBufferedAmount()>G)console.warn(`[gemi] Socket closed for backpressure (1013) on "${$}".`),h2(W,k.TryAgainLater,"Too far behind; reconnect.");this.server.publish($,Z)}onGap(){this.sendAll({op:"gap"});for(let $ of this.byTopic.keys()){let Z=Math.floor(Math.random()*T8);setTimeout(()=>{if(!this.closing)this.applyRevocation({topic:$})},Z).unref?.()}}applyRevocation($){if("user"in $){for(let W of this.sockets)if(W.data.userId===$.user&&!W.data.closing)h2(W,k.Revoked,"Revoked.");return}let Z=$.topic,z=++this.revocationSeq;this.revokedAt.set(Z,z);let G=this.byTopic.get(Z);if(!G)return;for(let W of G)this.reauthorize(W,Z,z)}async reauthorize($,Z,z){let G=$.data,W=[...G.subs].filter(([,Y])=>Y.topic===Z);if(W.length===0)return;$.unsubscribe(Z);let X=await Promise.all(W.map(([,Y])=>this.authorize($,Y).catch((K)=>{return console.error(`[gemi] Authorizing "${Z}" again after a revoke failed.`,K),{ok:!1,code:"revoked"}})));if(G.closed)return;if(this.revokedAt.get(Z)!==z)return;if(W.forEach(([Y,K],Q)=>{let H=X[Q];if(G.subs.get(Y)!==K)return;if(H.ok===!0&&H.topic===Z)return;G.subs.delete(Y),this.leave($,Z),y($,Y,"revoked")}),!G.topics.has(Z))return;$.subscribe(Z);for(let[Y,K]of G.subs)if(K.topic===Z)a($,{op:"subscribed",id:Y,t:Z})}sendAll($){let Z=JSON.stringify($);for(let z of this.sockets)z.send(Z)}shutdown($={}){if(this.closed)return this.closed;this.closing=!0,this.closed=new Promise((G)=>{this.onAllClosed=G});let Z=[...this.sockets];if(Z.length===0)this.onAllClosed?.();if(Z.length>0)console.log(`[gemi] Closing ${Z.length} broadcast socket(s) (1012).`);for(let G of Z)this.sayBye(G);return setTimeout(()=>{for(let G of Z)try{G.terminate()}catch{}this.onAllClosed?.()},$.terminateAfterMs??2000).unref?.(),this.closed}get isClosing(){return this.closing}sayBye($){a($,{op:"bye",code:k.Restart,retryAfter:1000+Math.floor(Math.random()*4000)}),h2($,k.Restart,"Server restarting.")}run($){return N2.run(this.application,$)}}function k8($,Z){let z=/^(?:(https?):\/\/)?\*\.([^/:]+)(?::(\d+))?\/?$/i.exec($);if(z){let[,G,W,X]=z;if(G&&`${G.toLowerCase()}:`!==Z.protocol)return!1;if((X??"")!==Z.port)return!1;return Z.hostname.toLowerCase().endsWith(`.${W.toLowerCase().replace(/\.$/,"")}`)}if(/^https?:\/\//i.test($))try{return new URL($).origin===Z.origin}catch{return!1}return $.toLowerCase().replace(/\/$/,"")===Z.host.toLowerCase()}function h2($,Z,z){$.data.closing=!0,$.close(Z,z)}function a($,Z){$.send(JSON.stringify(Z))}function y($,Z,z){a($,{op:"denied",id:Z,code:z})}function f($,Z,z={}){return new Response(Z,{status:$,headers:{"Content-Type":"text/plain; charset=utf-8",...z}})}function R8($){if(typeof $!=="object"||$===null||Array.isArray($))return!1;return Object.values($).every((Z)=>typeof Z==="string"||typeof Z==="number")}function E8($){let Z=$?.id;return typeof Z==="string"||typeof Z==="number"?String(Z):null}function b8($,Z){let z=$.headers.get("x-forwarded-for")?.split(",")[0]?.trim();if(z)return m2(K$(z)??z);try{let G=Z.requestIP($)?.address;return G?m2(G):null}catch{return null}}function Y$($,Z){if(!Z)return;let z=($.get(Z)??0)-1;if(z<=0)$.delete(Z);else $.set(Z,z)}class y8 extends B{register(){this.app.singleton(g,()=>new g(this.app.config.get("broadcast",{}),{application:this.app,channels:this.app.config.get("route.channels")})),this.app.singleton(r,()=>new r(this.app.make(g),this.app))}boot(){let $=this.app.config.get("route.channels");if($)J$(new $);let Z=this.app.config.get("broadcast",{}),z=typeof Z.driver==="function"||typeof Z.driver==="object"?this.app.make(g).driver:void 0;f8(Z,process.env,z)}async shutdown(){if(this.app.resolved(r))this.app.make(r).shutdown();if(!this.app.resolved(g))return;await this.app.make(g).close()}}function f8($,Z=process.env,z){if(!($.driver==="redis"||z instanceof V$)||Z.SECRET)return;let W=`[gemi] The "redis" broadcast driver needs SECRET set, the same on every instance: Broadcast.toOthers tags the sender's socket with a key derived from it, and every instance must derive the same one.`;if(Z.NODE_ENV==="production")throw Error(W);console.warn(W)}class w8 extends B{register(){this.app.singleton(c2,()=>new c2(this.app.config.get("cache",{}),{application:this.app}))}}class v8 extends B{register(){this.app.singleton(G2,()=>new G2(this.app.config.get("changeFeed",{}),{application:this.app}))}async shutdown(){if(!this.app.resolved(G2))return;await this.app.make(G2).close()}}class g8 extends B{register(){this.app.singleton(i2,()=>new i2(this.app.config.get("auth",{}))),this.app.singleton(p2,()=>{let $=this.app.config.get("auth",{});return new p2({providers:$.connections??{},store:$.connectionStore??void 0})})}boot(){let $=this.app.config.get("auth",{});F$($),N$($?.emailCode??{},{warn:!0})}}var h8=100,m8=($)=>Math.min(h8,Math.floor($/10));class u8 extends B{register(){this.app.singleton(c,()=>new c(S(l2(),this.app.config.get("schedule",{}))))}async boot(){let $=this.app.make(c),Z=this.app.config.get("schedule",{});if(Z.jobs===void 0){let{jobsDir:G}=S(l2(),Z);$.useJobs(await B$(G))}if(process.env.GEMI_NO_SCHEDULE==="1")return;if(process.env.VITEST&&process.env.GEMI_SCHEDULE!=="1")return;let z=this.app;if(z.bound(d))$.useLocks(()=>z.make(d));$.start((G)=>N2.run(z,G))}async shutdown($){if(!this.app.resolved(c))return;let Z=this.app.make(c);if(Z.running>0)console.log(`[gemi] Shutting down: waiting for ${Z.running} running cron tick(s).`);let z=$?.timeoutMs,{unfinished:G}=await Z.drain(z===void 0?1/0:Math.max(0,z-m8(z)));if(G.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+G.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class e extends P${modelName;constructor($="FeatureFlag"){super();this.modelName=$}get available(){return I$(this.modelName)}async load(){if(!this.available)throw new n2(this.modelName);let $=t2(this.modelName);return await $.asSystem(()=>$.findMany())}async write($,Z,z){if(!this.available)throw new n2(this.modelName);let G=t2(this.modelName),W=this.hasActorColumn(G),X={active:Z};if(W)X.updatedBy=z.actor;return await G.asSystem(()=>G.upsert({where:{key:$},create:{key:$,...X},update:X})),{actorRecorded:W}}hasActorColumn($){let Z=$?.$schema?.fields?.updatedBy;return Z!==void 0&&Z.type==="String"}}function rZ($){return $}function L$(){return{features:void 0,enabled:!0,source:new e,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class d8 extends B{register(){this.app.singleton(F2,()=>{let $=this.app.config.get("features",{}),Z=S(L$(),$);if($?.model!==void 0&&$?.source===void 0)Z.source=new e($.model);else if($?.model!==void 0&&$.source instanceof e&&$.source.modelName!==$.model)B2.warning(`app/config/features.ts sets \`model: "${$.model}"\` and a source reading "${$.source.modelName}". The source wins; drop \`model\` to silence this.`);return new F2(Z,(z)=>B2.warning(z))})}async boot(){let $=this.app.make(F2);if(!$.config.enabled)return;try{await $.refresh()}catch(Z){B2.error(`Could not warm the feature flag cache at boot. ${Z instanceof Error?Z.message:String(Z)}`)}}}class c8 extends B{register(){this.app.singleton(s2,()=>new s2(this.app.config.get("mail",{})))}}class p8 extends B{register(){this.app.singleton(P2,()=>new P2(this.app.config.get("encryption",{})))}boot(){if(this.app.make(P2).configured)return;let Z=this.app.config.get("auth",{}),z=Object.keys(Z?.connections??{});if(z.length>0&&!Z?.connectionStore)throw new o2(`auth.connections (${z.join(", ")}) keeps OAuth tokens encrypted, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`);let G=_$();if(G.length===0)return;throw new o2(`${G.join(", ")} ${G.length===1?"is an encrypted column":"are encrypted columns"}, but no encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as \`encryption\` in your Kernel's config. Generate a key with \`openssl rand -base64 32\`.`)}}var i8=Symbol.for("gemi.broadcastEvent");function D$($){return typeof $==="object"&&$!==null&&$[i8]===!0}function l8($){return`listener:${$}`}function j$($,Z){n8($);let{maxAttempts:z,backoff:G,worker:W}=Z,X=$.event.name,Y=class extends O${maxAttempts=z;backoff=G;worker=W;async run(...K){let[Q,H]=t8(K),U=E(p).rehydrate(Q,H);await new $().handle(U)}onFail(K){console.error(`The listener ${$.name} threw while handling ${X} off the queue. The queue will retry it up to ${z} times in total; nothing the dispatcher did is waiting on it.`,K)}onDeadletter(K){console.error(`The listener ${$.name} failed every one of its ${z} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,K)}};return Object.defineProperty(Y,"name",{value:l8($.name),writable:!0}),Y}function n8($){if(Object.getOwnPropertyDescriptor($,"name")?.writable)return;throw Error(`The listener ${$.name} sets \`queued = true\` but does not declare \`static name\`, so it would be registered with the queue `+"under its class name \u2014 which a production build renames while the "+`payload that names it does not. Add: static name = "${$.name}";`)}function t8($){return typeof $[0]==="string"?$:$[0]}class p{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor($={}){this.config=S(I2(),$),this.useListeners(this.config.listeners)}useListeners($){this.config.listeners=$,this.listeners={},this.events={};let Z=new Set;for(let z of $){if(!z.event){console.error(`Listener ${z.name} does not declare \`static event\`, so there is no event name to register it under and its handle will never run. Add: static event = SomeEvent;`);continue}if(Z.has(z.name)){console.error(`Two event listeners are named "${z.name}" \u2014 the first is `+"registered and this one is not. A listener's name identifies it across the framework, so only one class can hold it. Rename one.");continue}Z.add(z.name);let G=z.event.name,W=new z;this.events[G]??=z.event,(this.listeners[G]??=[]).push({listener:z,job:W.queued?j$(z,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:$})=>$?[$]:[])}get registeredListeners(){return[...this.config.listeners]}dispatch($,Z){if(this.deferToCommit($,Z,!1))return;this.runListeners($,Z)}async dispatchAndWait($,Z){if(this.deferToCommit($,Z,!0))return;return this.runListeners($,Z)}deferToCommit($,Z,z){let{name:G,afterCommit:W}=$.constructor;if(!W)return!1;let X=A$(()=>this.runListeners($,Z));if(X&&z)this.warnNothingIsWaitedFor(G);return X}async runListeners($,Z){let z=$.constructor.name,G=this.listeners[z]??[],W=D$($);if(G.length===0&&!W){this.warnNothingIsListening(z);return}for(let{listener:X,job:Y}of G){if(Y){this.enqueue(Y,X,z,Z);continue}try{await new X().handle($)}catch(K){console.error(`The listener ${X.name} threw while handling ${z}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",K)}}if(W)this.broadcast($,z)}broadcast($,Z){try{E(g).broadcastEvent($)}catch(z){console.error(`The event ${Z} could not be broadcast.`,z)}}rehydrate($,Z=[]){let z=this.events[$];if(!z)throw Error(`Cannot rebuild the event "${$}" that came off the queue: no registered listener binds to an event of that name, so there is no class to construct. A queued listener runs in an application that `+"discovered its own listeners \u2014 check that this process sees the "+`same app/listeners as the one that dispatched, and that the event declares \`static name = "${$}"\`.`);return new z(...Z)}enqueue($,Z,z,G){if(G===void 0){console.error(`The listener ${Z.name} is queued, but ${z} reached the dispatcher without its constructor arguments, so there is nothing for the queue to rebuild it from and the listener was skipped. Dispatch through ${z}.dispatch(...) or ${z}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${Z.name} could not be queued for ${z}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{E(q).push($,JSON.stringify([z,G]),{reportFailure:!1}).catch(W)}catch(X){W(X)}}warnNothingIsWaitedFor($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has($))return;this.warnedAboutWaiting.add($),console.warn(`[gemi] ${$}.dispatchAndWait() was called inside a transaction and ${$} declares \`static afterCommit = true\`, so it resolved `+"immediately with no listener having run \u2014 they run when the "+"transaction commits. Await the transaction instead, or drop afterCommit if the caller needs the side effects first. Development only.")}warnNothingIsListening($){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has($))return;this.warnedFor.add($),console.warn(`[gemi] ${$} was dispatched and nothing is listening for it. A listener registers under the name its event declares, so check that app/listeners holds a Listener with \`static event = ${$}\` and that ${$} declares \`static name = "${$}"\`. Development only.`)}}class s8 extends B{register(){this.app.singleton(p,()=>new p(this.app.config.get("events",{})))}async boot(){let $=this.app.make(p),Z=this.app.config.get("events",{});if(Z.listeners===void 0){let{listenersDir:W}=S(I2(),Z);$.useListeners(await x$(W))}let z=$.queuedListenerJobs;if(z.length===0)return;let G=this.app.make(q);for(let W of z)G.registerJob(W)}}class o8 extends B{register(){this.app.singleton(a2,()=>new a2(this.app.config.get("filesystem",{})))}}class a8 extends B{register(){this.app.singleton(r2,()=>new r2(this.app.config.get("image",{})))}}class r8 extends B{register(){this.app.instance(e2,new e2)}}class e8 extends B{register(){this.app.singleton(L2,()=>new L2(S(C$(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(L2).boot()}}class $9 extends B{register(){this.app.singleton(s,()=>new s(S(S$(),this.app.config.get("middleware",{}))))}boot(){this.app.make(s).assertGlobalMiddleware()}}function z7($){return $}function T$(){return{driver:new q$,limit:1000,window:60}}class Z9 extends B{register(){this.app.singleton(t,()=>new t(S(T$(),this.app.config.get("ratelimiter",{}))))}}function H7($){return $}function M$(){return{url:process.env.REDIS_URL,options:void 0}}class z9 extends B{register(){this.app.singleton(W2,()=>new W2(S(M$(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(W2))return;this.app.make(W2).close()}}function _2($,Z){let z=$.get(Z);if(!z)throw Error(`Missing "${Z}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return z}class G9 extends B{register(){this.app.singleton($2,()=>new $2(_2(this.app.config,"route.api"))),this.app.singleton(X2,()=>new X2(_2(this.app.config,"route.view"),this.app.config.get("auth",{}))),this.app.singleton(o,()=>new o({api:this.app.make($2),view:this.app.make(X2)},{api:_2(this.app.config,"route.api"),view:_2(this.app.config,"route.view"),auth:this.app.config.get("auth",{}),domains:this.app.config.get("route.domains"),clientIpTrust:k$(process.env)})),this.app.singleton(n,()=>{let $=this.app.config.get("route.mcp");if(!$?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new n(new $.router,this.app.make($2),{files:$.remote?.files})}),this.registerMcpHttp()}registerMcpHttp(){this.app.singleton(z2,()=>{let $=this.app.config.get("route.mcp");if(!$?.remote?.enabled)throw Error("The MCP endpoint is not enabled: set route.mcp.remote.enabled.");return new z2(this.app.make(n),$.remote)})}boot(){if(this.app.make($2),this.app.make(X2),this.app.make(o),this.app.config.get("route.mcp"))this.app.make(n);let $=this.app.config.get("route.mcp.remote");if($?.enabled===!0)this.app.make(z2);else if($?.enabled!==void 0&&$.enabled!==!1)throw Error("route.mcp.remote.enabled must be true or false.")}}class W9 extends B{register(){this.app.singleton($3,()=>new $3(this.app.config.get("runs",{}),{application:this.app}))}}
|
|
8
8
|
export{R$ as sb,D as tb,h as ub,N9 as vb,n as wb,j2 as xb,e$ as yb,A2 as zb,k2 as Ab,R2 as Bb,z2 as Cb,c as Db,_8 as Eb,s9 as Fb,X$ as Gb,r as Hb,y8 as Ib,w8 as Jb,v8 as Kb,g8 as Lb,u8 as Mb,e as Nb,rZ as Ob,L$ as Pb,d8 as Qb,c8 as Rb,p8 as Sb,i8 as Tb,D$ as Ub,p as Vb,s8 as Wb,o8 as Xb,a8 as Yb,r8 as Zb,e8 as _b,$9 as $b,z7 as ac,T$ as bc,Z9 as cc,H7 as dc,M$ as ec,z9 as fc,G9 as gc,W9 as hc};
|
|
9
9
|
|
|
10
|
-
//# debugId=
|
|
10
|
+
//# debugId=85F1823E7D4EB9B464756E2164756E21
|