gemi 0.100.0 → 0.101.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/Schema.d.ts +59 -5
- package/dist/ai/Schema.d.ts.map +1 -1
- package/dist/ai/index.js +1 -1
- package/dist/chunk-4x41cmg3.js +9 -0
- package/dist/chunk-4x41cmg3.js.map +31 -0
- package/dist/{chunk-jv38q9n7.js → chunk-8v5z6646.js} +1 -1
- package/dist/{chunk-rc4z7ykq.js → chunk-d6prwkff.js} +1 -1
- package/dist/{chunk-kgckt396.js → chunk-jyswmx60.js} +2 -2
- package/dist/{chunk-kgckt396.js.map → chunk-jyswmx60.js.map} +1 -1
- package/dist/{chunk-q2r6b35k.js → chunk-pdvsc6jd.js} +1 -1
- package/dist/{chunk-vdynb16s.js → chunk-ztcsyeg7.js} +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-h15bd9vn.js +0 -9
- package/dist/chunk-h15bd9vn.js.map +0 -31
- /package/dist/{chunk-jv38q9n7.js.map → chunk-8v5z6646.js.map} +0 -0
- /package/dist/{chunk-rc4z7ykq.js.map → chunk-d6prwkff.js.map} +0 -0
- /package/dist/{chunk-q2r6b35k.js.map → chunk-pdvsc6jd.js.map} +0 -0
- /package/dist/{chunk-vdynb16s.js.map → chunk-ztcsyeg7.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{zb as SZ}from"./chunk-wc46df4w.js";import{Lb as c,Nb as y,Pb as XZ,Qb as VZ,Sb as qZ}from"./chunk-3tn480wt.js";import{$b as GZ,Tb as e,Wb as JZ,Yb as ZZ,Zb as $Z,_b as U,ac as WZ,cc as HZ}from"./chunk-z8jf7jwg.js";import{fc as K}from"./chunk-7kedxtbp.js";import{$c as IZ,Cd as S,Dd as v,Ec as _Z,Ed as h,ad as u,ed as j,md as i,nd as f,rd as s,tc as OZ,xc as n,yd as R}from"./chunk-rc4z7ykq.js";import{Md as KZ,Nd as p}from"./chunk-bf1q3m7a.js";import{df as b,sf as l,uf as w,vf as k,wf as T}from"./chunk-h15bd9vn.js";import{Ff as a,Hf as Q}from"./chunk-br9p390p.js";import{Nf as BZ}from"./chunk-n4807648.js";import{vg as I}from"./chunk-3fr22rtg.js";import{Bg as d}from"./chunk-77kw61f4.js";import{Hg as zZ,Kg as M}from"./chunk-48dek9s7.js";async function TZ(Z,$={}){try{if(!await Z.shouldRun.call(Z))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${Z.name}:`,W);return}let G=EZ(Z.withoutOverlapping);if(!Z.onOneServer&&G===void 0){await m(Z);return}let H;try{if(H=$.locks?.()??RZ(),Z.onOneServer){let W=Math.floor(($.now??Date.now())/60000);if(!await H.store.advance(`gemi:cron-tick:${Z.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${Z.name}; skipped it:`,W);return}if(G===void 0){await m(Z);return}try{await H.run(`gemi:cron:${Z.name}`,{ttl:G},(W)=>m(Z,W))}catch(W){if(W instanceof a)console.error(`Cron job ${Z.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 ${Z.name}:`,W)}}var o=300000;function EZ(Z){if(!Z)return;if(Z===!0)return o;return Z.expiresAfter??o}var r;function RZ(){return r??=new Q(new e),r}async function m(Z,$){try{await Z.onTick.call(Z)}catch(G){console.error(`Error executing cron job ${Z.name}:`,G)}try{await Z.callback.call(Z,$)}catch(G){console.error(`Error in cron job ${Z.name}:`,G)}try{await Z.onComplete.call(Z)}catch(G){console.error(`Error completing cron job ${Z.name}:`,G)}}class A{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor(Z){this.resolved=Z.jobs}get jobs(){return[...this.resolved]}useJobs(Z){this.resolved=Z}useLocks(Z){this.locks=Z}start(Z=($)=>$()){if(this.stopped=!1,this.resolved.length===0)return;let $=globalThis.__gemiCronJobs??=new Map,G=new Map;for(let H of this.resolved){let W=new H;if(!W.name){console.error(`Cron job must have a name \u2014 ${H.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=G.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${H.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}G.set(W.name,H.name||"an anonymous class"),$.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let z=this.locks;return this.track(W.name,()=>Z(()=>TZ(W,{locks:z})))});$.set(W.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let Z of this.handles)Z.stop();this.handles=[]}async drain(Z=1/0){this.stop();let $,G=new Promise((H)=>{if(Z!==1/0)$=setTimeout(H,Z)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((H)=>H.done)),G]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((H)=>({...H.tick}))}}get running(){return this.inFlight.size}track(Z,$){let G={},H=Promise.resolve().then($).finally(()=>this.inFlight.delete(G));return this.inFlight.set(G,{tick:{name:Z,startedAt:new Date},done:H}),H}}import{isMainThread as DZ}from"worker_threads";var kZ=100,jZ=(Z)=>Math.min(kZ,Math.floor(Z/10));class MZ extends K{register(){this.app.singleton(U,()=>new U(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(Q,()=>this.app.make(U).locks)}async boot(){let Z=this.app.config.get("queue",{});if(Z.jobs!==void 0)return;let{jobsDir:$}=I(ZZ(),Z);this.app.make(U).useJobs(await XZ($))}async shutdown(Z){if(!this.app.resolved(U))return;let $=this.app.make(U);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running queued job(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-jZ(G)));if(H.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+H.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function Q3(Z){if(wZ(Z),Bun.env.NODE_ENV!=="production")return fZ(Z);if(YZ(Z))return;if(!GZ())return;if(!Z.bound(U))return;Z.make(U).start()}function YZ(Z){let $=Z.config.get("queue",{}).driver??"memory";return $==="memory"||$ instanceof $Z}function yZ(Z){if(YZ(Z))return!0;if(typeof Z.config.get("queue",{}).driver!=="function"||!Z.bound(U))return!1;try{return!Z.make(U).durable}catch{return!1}}function wZ(Z){let $=process.env.GEMI_QUEUE_CLAIM;if($===void 0||HZ())return;if(process.env.ROOT_DIR===void 0||!DZ)return;if(WZ()){if(!yZ(Z))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($.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${$}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function fZ(Z){let $=globalThis.__gemiDevQueue;if(!$)return;if(globalThis.__gemiDevQueue=void 0,$.stop(),Z.bound(U))Z.make(U).start()}class bZ extends K{register(){this.app.singleton(h,()=>new h(this.app.config.get("auth",{})))}}var gZ=100,vZ=(Z)=>Math.min(gZ,Math.floor(Z/10));class mZ extends K{register(){this.app.singleton(A,()=>new A(I(c(),this.app.config.get("schedule",{}))))}async boot(){let Z=this.app.make(A),$=this.app.config.get("schedule",{});if($.jobs===void 0){let{jobsDir:H}=I(c(),$);Z.useJobs(await VZ(H))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let G=this.app;if(G.bound(Q))Z.useLocks(()=>G.make(Q));Z.start((H)=>zZ.run(G,H))}async shutdown(Z){if(!this.app.resolved(A))return;let $=this.app.make(A);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running cron tick(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-vZ(G)));if(H.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+H.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class F extends IZ{modelName;constructor(Z="FeatureFlag"){super();this.modelName=Z}get available(){return KZ(this.modelName)}async load(){if(!this.available)throw new u(this.modelName);let Z=p(this.modelName);return await Z.asSystem(()=>Z.findMany())}async write(Z,$,G){if(!this.available)throw new u(this.modelName);let H=p(this.modelName),W=this.hasActorColumn(H),X={active:$};if(W)X.updatedBy=G.actor;return await H.asSystem(()=>H.upsert({where:{key:Z},create:{key:Z,...X},update:X})),{actorRecorded:W}}hasActorColumn(Z){let $=Z?.$schema?.fields?.updatedBy;return $!==void 0&&$.type==="String"}}function g3(Z){return Z}function UZ(){return{features:void 0,enabled:!0,source:new F,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class hZ extends K{register(){this.app.singleton(j,()=>{let Z=this.app.config.get("features",{}),$=I(UZ(),Z);if(Z?.model!==void 0&&Z?.source===void 0)$.source=new F(Z.model);else if(Z?.model!==void 0&&Z.source instanceof F&&Z.source.modelName!==Z.model)k.warning(`app/config/features.ts sets \`model: "${Z.model}"\` and a source reading "${Z.source.modelName}". The source wins; drop \`model\` to silence this.`);return new j($,(G)=>k.warning(G))})}async boot(){let Z=this.app.make(j);if(!Z.config.enabled)return;try{await Z.refresh()}catch($){k.error(`Could not warm the feature flag cache at boot. ${$ instanceof Error?$.message:String($)}`)}}}class cZ extends K{register(){this.app.singleton(d,()=>new d(this.app.config.get("mail",{})))}}function pZ(Z){return`listener:${Z}`}function CZ(Z,$){uZ(Z);let{maxAttempts:G,backoff:H,worker:W}=$,X=Z.event.name,Y=class extends JZ{maxAttempts=G;backoff=H;worker=W;async run(...z){let[C,B]=dZ(z),J=M(x).rehydrate(C,B);await new Z().handle(J)}onFail(z){console.error(`The listener ${Z.name} threw while handling ${X} off the queue. The queue will retry it up to ${G} times in total; nothing the dispatcher did is waiting on it.`,z)}onDeadletter(z){console.error(`The listener ${Z.name} failed every one of its ${G} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,z)}};return Object.defineProperty(Y,"name",{value:pZ(Z.name),writable:!0}),Y}function uZ(Z){if(Object.getOwnPropertyDescriptor(Z,"name")?.writable)return;throw Error(`The listener ${Z.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 = "${Z.name}";`)}function dZ(Z){return typeof Z[0]==="string"?Z:Z[0]}class x{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(Z={}){this.config=I(y(),Z),this.useListeners(this.config.listeners)}useListeners(Z){this.config.listeners=Z,this.listeners={},this.events={};let $=new Set;for(let G of Z){if(!G.event){console.error(`Listener ${G.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($.has(G.name)){console.error(`Two event listeners are named "${G.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}$.add(G.name);let H=G.event.name,W=new G;this.events[H]??=G.event,(this.listeners[H]??=[]).push({listener:G,job:W.queued?CZ(G,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:Z})=>Z?[Z]:[])}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,$,G){let{name:H,afterCommit:W}=Z.constructor;if(!W)return!1;let X=BZ(()=>this.runListeners(Z,$));if(X&&G)this.warnNothingIsWaitedFor(H);return X}async runListeners(Z,$){let G=Z.constructor.name,H=this.listeners[G];if(!H?.length){this.warnNothingIsListening(G);return}for(let{listener:W,job:X}of H){if(X){this.enqueue(X,W,G,$);continue}try{await new W().handle(Z)}catch(Y){console.error(`The listener ${W.name} threw while handling ${G}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",Y)}}}rehydrate(Z,$=[]){let G=this.events[Z];if(!G)throw Error(`Cannot rebuild the event "${Z}" 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 = "${Z}"\`.`);return new G(...$)}enqueue(Z,$,G,H){if(H===void 0){console.error(`The listener ${$.name} is queued, but ${G} 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 ${G}.dispatch(...) or ${G}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${$.name} could not be queued for ${G}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{M(U).push(Z,JSON.stringify([G,H]),{reportFailure:!1}).catch(W)}catch(X){W(X)}}warnNothingIsWaitedFor(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has(Z))return;this.warnedAboutWaiting.add(Z),console.warn(`[gemi] ${Z}.dispatchAndWait() was called inside a transaction and ${Z} 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(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has(Z))return;this.warnedFor.add(Z),console.warn(`[gemi] ${Z} 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 = ${Z}\` and that ${Z} declares \`static name = "${Z}"\`. Development only.`)}}class lZ extends K{register(){this.app.singleton(x,()=>new x(this.app.config.get("events",{})))}async boot(){let Z=this.app.make(x),$=this.app.config.get("events",{});if($.listeners===void 0){let{listenersDir:W}=I(y(),$);Z.useListeners(await qZ(W))}let G=Z.queuedListenerJobs;if(G.length===0)return;let H=this.app.make(U);for(let W of G)H.registerJob(W)}}class iZ extends K{register(){this.app.singleton(l,()=>new l(this.app.config.get("filesystem",{})))}}class sZ extends K{register(){this.app.singleton(i,()=>new i(this.app.config.get("image",{})))}}class nZ extends K{register(){this.app.instance(s,new s)}}function F4(Z){return Z}function PZ(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class tZ extends K{register(){this.app.singleton(w,()=>new w(I(PZ(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(w).boot()}}class oZ extends K{register(){this.app.singleton(f,()=>new f(I(OZ(),this.app.config.get("middleware",{}))))}boot(){this.app.make(f).assertGlobalMiddleware()}}function b4(Z){return Z}function NZ(){return{driver:new _Z,limit:1000,window:60}}class rZ extends K{register(){this.app.singleton(n,()=>new n(I(NZ(),this.app.config.get("ratelimiter",{}))))}}function u4(Z){return Z}function QZ(){return{url:process.env.REDIS_URL,options:void 0}}class aZ extends K{register(){this.app.singleton(T,()=>new T(I(QZ(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(T))return;this.app.make(T).close()}}class q extends SZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}var eZ=/^[A-Za-z0-9_-]{1,64}$/,Z3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,AZ=4000,t=1e5,$3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class E{dispatcher;static token="router.mcp";plans=new Map;constructor(Z,$){this.dispatcher=$;for(let[G,H]of Object.entries(Z.routes??{}))this.plans.set(G,this.plan(G,H))}list(Z,$){return xZ(Z),this.descriptors($)}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values()){if(Z?.names&&!Z.names.includes(G.name))continue;if(Z?.tags&&!G.tags.some((H)=>Z.tags.includes(H)))continue;$.push(G)}return $}async execute(Z,$,G,H){xZ(Z);let W=this.plans.get($);if(!W)throw Error(`McpRegistry: there is no tool named "${$}".`);let{descriptor:X}=W,Y=X.inputSchema.safeParse(G);if(Y.ok===!1)throw new q(`Invalid arguments for "${$}": ${Y.errors.join(", ")}`);let z=Y.value,C=await this.fillPath(W,z,Z.req),{path:B}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${C}`));if(B!==X.url)throw new q(`"${$}" has nothing at ${C}.`,404);let J={};for(let N of W.jsonKeys)if(z[N]!==void 0)J[N]=z[N];let P,O="";if(W.fileFields.length>0)P=await this.formData(W,z,J,H);else if(X.method==="GET")O=X3(J);else if(W.jsonKeys.length>0)P=J;let L;try{L=await this.dispatcher.dispatchAs(Z.req,X.method,O?`${C}?${O}`:C,P)}catch(N){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,N),new q(`"${$}" failed on the server.`,500)}return await Y3($,L)}plan(Z,$){if(!eZ.test(Z))throw Error(`McpRouter: "${Z}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:H,url:W,meta:X}=$;if(W.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[H];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let z=[...W.matchAll(Z3)].map(([,V,_])=>({name:V,modifier:_})),C=X.params??{};for(let V of z)if(!(V.name in C))throw Error(`${G}: the path param "${V.name}" must be bound or declared "input".`);for(let[V,_]of Object.entries(C)){if(!z.some((D)=>D.name===V))throw Error(`${G}: "${V}" in params is not a param of the url.`);FZ(G,`params.${V}`,_)}let B=[],J;if(X.input){if(J=X.input.toJSONSchema(),J.type!=="object"||!J.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);B=Object.keys(J.properties)}let P=Object.entries(X.files??{}).map(([V,_])=>({name:V,binder:_}));for(let V of P)FZ(G,`files.${V.name}`,V.binder);if(P.length>0&&H==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let O={},L=new Map;for(let V of z){let _=C[V.name];if(_==="input"){let D=b.string().describe(`The ":${V.name}" segment of the url.`);O[V.name]=V.modifier==="?"||V.modifier==="*"?D.optional():D}else L.set(V.name,_)}for(let V of P)if(V.binder==="input")O[V.name]=b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.");let N=[...Object.keys(O),...P.map((V)=>V.name)];for(let V of new Set(N))if(B.includes(V))throw Error(`${G}: "${V}" is both an input field and a param or file, and the model can only send one.`);return{descriptor:Object.freeze({name:Z,description:X.description,method:H,url:W,inputSchema:W3(X.input,J,b.object(O)),annotations:G3(H),tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),params:z,paramBinders:L,fileFields:P,jsonKeys:B}}async fillPath(Z,$,G){let H=Z.descriptor.url;for(let W of Z.params){let X=Z.paramBinders.get(W.name),Y;if(X){if(Y=await this.bind(Z,`the param "${W.name}"`,()=>X(G)),Y===void 0||Y===null||Y==="")throw console.error(`[gemi/mcp] The binder for "${W.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(Y)}.`),new q(`"${Z.descriptor.name}" failed on the server.`,500)}else Y=$[W.name];let z=`:${W.name}${W.modifier}`;if(Y===void 0||Y===null||Y===""){if(W.modifier!=="?"&&W.modifier!=="*")throw new q(`"${W.name}" of "${Z.descriptor.name}" must not be empty.`);H=H.replace(`/${z}`,"");continue}H=H.replace(z,H3(Z.descriptor.name,W,String(Y)))}return H}async formData(Z,$,G,H){let W=Z.descriptor.name;if(!H)throw Error(`McpRegistry: "${W}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let X=new FormData;for(let[Y,z]of Object.entries(G))LZ(X,Y,z);for(let Y of Z.fileFields){let z=Y.binder==="input"?$[Y.name]:await this.bind(Z,`the file "${Y.name}"`,()=>Y.binder(H));if(typeof z!=="string"||z==="")throw new q(`"${W}" needs a file for "${Y.name}", and this turn has none. Ask the user to attach one.`);X.append(Y.name,await H.attachments.file(z))}return X}async bind(Z,$,G){try{return await G()}catch(H){throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,H),new q(`"${Z.descriptor.name}" failed on the server.`,500)}}}function xZ(Z){if(Z?.kind!=="local")throw Error("McpRegistry: only local callers are implemented. A remote caller needs a bearer-token resolver, which v1 does not have \u2014 and until it does there is no remote surface to call from.")}function FZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function G3(Z){switch(Z){case"GET":return Object.freeze({readOnlyHint:!0});case"DELETE":return Object.freeze({destructiveHint:!0});case"PUT":return Object.freeze({idempotentHint:!0});default:return Object.freeze({})}}function W3(Z,$,G){let H=G.toJSONSchema(),W={...$??{},type:"object",properties:{...$?.properties??{},...H.properties},required:[...$?.required??[],...H.required??[]],additionalProperties:!1},X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["expected an object"]};let z=[],C={};if(Z){let J=Z.safeParse(Y);if(J.ok===!1)z.push(...J.errors);else C={...J.value}}let B=G.safeParse(Y);if(B.ok===!1)z.push(...B.errors);else C={...C,...B.value};return z.length>0?{ok:!1,errors:z}:{ok:!0,value:C}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let z=X(Y);if(z.ok===!1)throw Error(z.errors.join(", "));return z.value}}}function H3(Z,$,G){let H=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(H.some((W)=>W==="."||W===".."))throw new q(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return H.map(encodeURIComponent).join("/")}function LZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let H of G)LZ(Z,$,H);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function X3(Z){let $=new URLSearchParams,G=(H,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)G(H,X);return}$.append(H,typeof W==="object"?JSON.stringify(W):String(W))};for(let[H,W]of Object.entries(Z))G(H,W);return $.toString()}async function Y3(Z,$){if($.status>=200&&$.status<300){let H=$.headers.get("Content-Type");if(H&&!$3.test(H)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${H}, which is not shown.`}let W=await $.text();if(W==="")return null;if(W.length>t)return`${W.slice(0,t)}\u2026 [cut at ${t} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let G=await $.text();if($.status>=400&&$.status<500){let H=G.length>AZ?`${G.slice(0,AZ)}\u2026`:G;throw new q(`"${Z}" was refused with ${$.status}${H?`: ${H}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new q(`"${Z}" failed on the server.`,$.status)}function g(Z,$){let G=Z.get($);if(!G)throw Error(`Missing "${$}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return G}class z3 extends K{register(){this.app.singleton(S,()=>new S(g(this.app.config,"route.api"))),this.app.singleton(R,()=>new R(g(this.app.config,"route.view"))),this.app.singleton(v,()=>new v({api:this.app.make(S),view:this.app.make(R)},{api:g(this.app.config,"route.api"),view:g(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(E,()=>{let Z=this.app.config.get("route.mcp");if(!Z?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new E(new Z.router,this.app.make(S))})}boot(){if(this.app.make(S),this.app.make(R),this.app.make(v),this.app.config.get("route.mcp"))this.app.make(E)}}
|
|
2
|
+
import{zb as SZ}from"./chunk-wc46df4w.js";import{Lb as c,Nb as y,Pb as XZ,Qb as VZ,Sb as qZ}from"./chunk-3tn480wt.js";import{$b as GZ,Tb as e,Wb as JZ,Yb as ZZ,Zb as $Z,_b as U,ac as WZ,cc as HZ}from"./chunk-z8jf7jwg.js";import{fc as K}from"./chunk-7kedxtbp.js";import{$c as IZ,Cd as S,Dd as v,Ec as _Z,Ed as h,ad as u,ed as j,md as i,nd as f,rd as s,tc as OZ,xc as n,yd as R}from"./chunk-d6prwkff.js";import{Md as KZ,Nd as p}from"./chunk-bf1q3m7a.js";import{df as b,sf as l,uf as w,vf as k,wf as T}from"./chunk-4x41cmg3.js";import{Ff as a,Hf as Q}from"./chunk-br9p390p.js";import{Nf as BZ}from"./chunk-n4807648.js";import{vg as I}from"./chunk-3fr22rtg.js";import{Bg as d}from"./chunk-77kw61f4.js";import{Hg as zZ,Kg as M}from"./chunk-48dek9s7.js";async function TZ(Z,$={}){try{if(!await Z.shouldRun.call(Z))return}catch(W){console.error(`Error evaluating shouldRun for cron job ${Z.name}:`,W);return}let G=EZ(Z.withoutOverlapping);if(!Z.onOneServer&&G===void 0){await m(Z);return}let H;try{if(H=$.locks?.()??RZ(),Z.onOneServer){let W=Math.floor(($.now??Date.now())/60000);if(!await H.store.advance(`gemi:cron-tick:${Z.name}`,W))return}}catch(W){console.error(`Could not claim the tick of cron job ${Z.name}; skipped it:`,W);return}if(G===void 0){await m(Z);return}try{await H.run(`gemi:cron:${Z.name}`,{ttl:G},(W)=>m(Z,W))}catch(W){if(W instanceof a)console.error(`Cron job ${Z.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 ${Z.name}:`,W)}}var o=300000;function EZ(Z){if(!Z)return;if(Z===!0)return o;return Z.expiresAfter??o}var r;function RZ(){return r??=new Q(new e),r}async function m(Z,$){try{await Z.onTick.call(Z)}catch(G){console.error(`Error executing cron job ${Z.name}:`,G)}try{await Z.callback.call(Z,$)}catch(G){console.error(`Error in cron job ${Z.name}:`,G)}try{await Z.onComplete.call(Z)}catch(G){console.error(`Error completing cron job ${Z.name}:`,G)}}class A{static token="scheduler";handles=[];resolved;inFlight=new Map;stopped=!1;locks;constructor(Z){this.resolved=Z.jobs}get jobs(){return[...this.resolved]}useJobs(Z){this.resolved=Z}useLocks(Z){this.locks=Z}start(Z=($)=>$()){if(this.stopped=!1,this.resolved.length===0)return;let $=globalThis.__gemiCronJobs??=new Map,G=new Map;for(let H of this.resolved){let W=new H;if(!W.name){console.error(`Cron job must have a name \u2014 ${H.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=G.get(W.name);if(X!==void 0){console.error(`Two cron jobs claim the name "${W.name}" \u2014 ${X} is scheduled and ${H.name||"an anonymous class"} is not. A name is the scheduler's key, so only one job can hold it. Rename one.`);continue}G.set(W.name,H.name||"an anonymous class"),$.get(W.name)?.stop();let Y=Bun.cron(W.cron,()=>{if(this.stopped)return;let z=this.locks;return this.track(W.name,()=>Z(()=>TZ(W,{locks:z})))});$.set(W.name,Y),this.handles.push(Y)}}stop(){this.stopped=!0;for(let Z of this.handles)Z.stop();this.handles=[]}async drain(Z=1/0){this.stop();let $,G=new Promise((H)=>{if(Z!==1/0)$=setTimeout(H,Z)});return await Promise.race([Promise.allSettled([...this.inFlight.values()].map((H)=>H.done)),G]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((H)=>({...H.tick}))}}get running(){return this.inFlight.size}track(Z,$){let G={},H=Promise.resolve().then($).finally(()=>this.inFlight.delete(G));return this.inFlight.set(G,{tick:{name:Z,startedAt:new Date},done:H}),H}}import{isMainThread as DZ}from"worker_threads";var kZ=100,jZ=(Z)=>Math.min(kZ,Math.floor(Z/10));class MZ extends K{register(){this.app.singleton(U,()=>new U(this.app.config.get("queue",{}),{application:this.app})),this.app.singleton(Q,()=>this.app.make(U).locks)}async boot(){let Z=this.app.config.get("queue",{});if(Z.jobs!==void 0)return;let{jobsDir:$}=I(ZZ(),Z);this.app.make(U).useJobs(await XZ($))}async shutdown(Z){if(!this.app.resolved(U))return;let $=this.app.make(U);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running queued job(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-jZ(G)));if(H.length>0)return console.error("[gemi] Queued jobs still running at shutdown: "+H.map((W)=>`${W.name} (${W.id})`).join(", ")),{abandoned:!0}}}function Q3(Z){if(wZ(Z),Bun.env.NODE_ENV!=="production")return fZ(Z);if(YZ(Z))return;if(!GZ())return;if(!Z.bound(U))return;Z.make(U).start()}function YZ(Z){let $=Z.config.get("queue",{}).driver??"memory";return $==="memory"||$ instanceof $Z}function yZ(Z){if(YZ(Z))return!0;if(typeof Z.config.get("queue",{}).driver!=="function"||!Z.bound(U))return!1;try{return!Z.make(U).durable}catch{return!1}}function wZ(Z){let $=process.env.GEMI_QUEUE_CLAIM;if($===void 0||HZ())return;if(process.env.ROOT_DIR===void 0||!DZ)return;if(WZ()){if(!yZ(Z))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($.trim().toLowerCase()!=="on")console.warn(`[gemi] GEMI_QUEUE_CLAIM="${$}" is not "off" or "on", so this server claims jobs. Set it to "off" to leave them to \`gemi queue:work\`.`)}function fZ(Z){let $=globalThis.__gemiDevQueue;if(!$)return;if(globalThis.__gemiDevQueue=void 0,$.stop(),Z.bound(U))Z.make(U).start()}class bZ extends K{register(){this.app.singleton(h,()=>new h(this.app.config.get("auth",{})))}}var gZ=100,vZ=(Z)=>Math.min(gZ,Math.floor(Z/10));class mZ extends K{register(){this.app.singleton(A,()=>new A(I(c(),this.app.config.get("schedule",{}))))}async boot(){let Z=this.app.make(A),$=this.app.config.get("schedule",{});if($.jobs===void 0){let{jobsDir:H}=I(c(),$);Z.useJobs(await VZ(H))}if(process.env.GEMI_NO_SCHEDULE==="1")return;let G=this.app;if(G.bound(Q))Z.useLocks(()=>G.make(Q));Z.start((H)=>zZ.run(G,H))}async shutdown(Z){if(!this.app.resolved(A))return;let $=this.app.make(A);if($.running>0)console.log(`[gemi] Shutting down: waiting for ${$.running} running cron tick(s).`);let G=Z?.timeoutMs,{unfinished:H}=await $.drain(G===void 0?1/0:Math.max(0,G-vZ(G)));if(H.length>0)return console.error("[gemi] Cron jobs still running at shutdown: "+H.map((W)=>`${W.name} (started ${W.startedAt.toISOString()})`).join(", ")),{abandoned:!0}}}class F extends IZ{modelName;constructor(Z="FeatureFlag"){super();this.modelName=Z}get available(){return KZ(this.modelName)}async load(){if(!this.available)throw new u(this.modelName);let Z=p(this.modelName);return await Z.asSystem(()=>Z.findMany())}async write(Z,$,G){if(!this.available)throw new u(this.modelName);let H=p(this.modelName),W=this.hasActorColumn(H),X={active:$};if(W)X.updatedBy=G.actor;return await H.asSystem(()=>H.upsert({where:{key:Z},create:{key:Z,...X},update:X})),{actorRecorded:W}}hasActorColumn(Z){let $=Z?.$schema?.fields?.updatedBy;return $!==void 0&&$.type==="String"}}function g3(Z){return Z}function UZ(){return{features:void 0,enabled:!0,source:new F,model:"FeatureFlag",ttl:30,context:void 0,onEvaluate:void 0,maxClientFlags:200}}class hZ extends K{register(){this.app.singleton(j,()=>{let Z=this.app.config.get("features",{}),$=I(UZ(),Z);if(Z?.model!==void 0&&Z?.source===void 0)$.source=new F(Z.model);else if(Z?.model!==void 0&&Z.source instanceof F&&Z.source.modelName!==Z.model)k.warning(`app/config/features.ts sets \`model: "${Z.model}"\` and a source reading "${Z.source.modelName}". The source wins; drop \`model\` to silence this.`);return new j($,(G)=>k.warning(G))})}async boot(){let Z=this.app.make(j);if(!Z.config.enabled)return;try{await Z.refresh()}catch($){k.error(`Could not warm the feature flag cache at boot. ${$ instanceof Error?$.message:String($)}`)}}}class cZ extends K{register(){this.app.singleton(d,()=>new d(this.app.config.get("mail",{})))}}function pZ(Z){return`listener:${Z}`}function CZ(Z,$){uZ(Z);let{maxAttempts:G,backoff:H,worker:W}=$,X=Z.event.name,Y=class extends JZ{maxAttempts=G;backoff=H;worker=W;async run(...z){let[C,B]=dZ(z),J=M(x).rehydrate(C,B);await new Z().handle(J)}onFail(z){console.error(`The listener ${Z.name} threw while handling ${X} off the queue. The queue will retry it up to ${G} times in total; nothing the dispatcher did is waiting on it.`,z)}onDeadletter(z){console.error(`The listener ${Z.name} failed every one of its ${G} attempts at ${X} and has been dead-lettered, so this side effect did not happen and will not be retried.`,z)}};return Object.defineProperty(Y,"name",{value:pZ(Z.name),writable:!0}),Y}function uZ(Z){if(Object.getOwnPropertyDescriptor(Z,"name")?.writable)return;throw Error(`The listener ${Z.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 = "${Z.name}";`)}function dZ(Z){return typeof Z[0]==="string"?Z:Z[0]}class x{static token="events";listeners={};events={};warnedFor=new Set;warnedAboutWaiting=new Set;config;constructor(Z={}){this.config=I(y(),Z),this.useListeners(this.config.listeners)}useListeners(Z){this.config.listeners=Z,this.listeners={},this.events={};let $=new Set;for(let G of Z){if(!G.event){console.error(`Listener ${G.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($.has(G.name)){console.error(`Two event listeners are named "${G.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}$.add(G.name);let H=G.event.name,W=new G;this.events[H]??=G.event,(this.listeners[H]??=[]).push({listener:G,job:W.queued?CZ(G,W):null})}}get queuedListenerJobs(){return Object.values(this.listeners).flat().flatMap(({job:Z})=>Z?[Z]:[])}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,$,G){let{name:H,afterCommit:W}=Z.constructor;if(!W)return!1;let X=BZ(()=>this.runListeners(Z,$));if(X&&G)this.warnNothingIsWaitedFor(H);return X}async runListeners(Z,$){let G=Z.constructor.name,H=this.listeners[G];if(!H?.length){this.warnNothingIsListening(G);return}for(let{listener:W,job:X}of H){if(X){this.enqueue(X,W,G,$);continue}try{await new W().handle(Z)}catch(Y){console.error(`The listener ${W.name} threw while handling ${G}. The `+"listeners after it still ran \u2014 a listener's failure is its own.",Y)}}}rehydrate(Z,$=[]){let G=this.events[Z];if(!G)throw Error(`Cannot rebuild the event "${Z}" 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 = "${Z}"\`.`);return new G(...$)}enqueue(Z,$,G,H){if(H===void 0){console.error(`The listener ${$.name} is queued, but ${G} 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 ${G}.dispatch(...) or ${G}.dispatchAndWait(...), which carry them.`);return}let W=(X)=>console.error(`The listener ${$.name} could not be queued for ${G}, so it did not run and will not be retried. The listeners after it still ran.`,X);try{M(U).push(Z,JSON.stringify([G,H]),{reportFailure:!1}).catch(W)}catch(X){W(X)}}warnNothingIsWaitedFor(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedAboutWaiting.has(Z))return;this.warnedAboutWaiting.add(Z),console.warn(`[gemi] ${Z}.dispatchAndWait() was called inside a transaction and ${Z} 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(Z){if(Bun.env.NODE_ENV==="production")return;if(this.warnedFor.has(Z))return;this.warnedFor.add(Z),console.warn(`[gemi] ${Z} 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 = ${Z}\` and that ${Z} declares \`static name = "${Z}"\`. Development only.`)}}class lZ extends K{register(){this.app.singleton(x,()=>new x(this.app.config.get("events",{})))}async boot(){let Z=this.app.make(x),$=this.app.config.get("events",{});if($.listeners===void 0){let{listenersDir:W}=I(y(),$);Z.useListeners(await qZ(W))}let G=Z.queuedListenerJobs;if(G.length===0)return;let H=this.app.make(U);for(let W of G)H.registerJob(W)}}class iZ extends K{register(){this.app.singleton(l,()=>new l(this.app.config.get("filesystem",{})))}}class sZ extends K{register(){this.app.singleton(i,()=>new i(this.app.config.get("image",{})))}}class nZ extends K{register(){this.app.instance(s,new s)}}function F4(Z){return Z}function PZ(){return{maxFileSize:10485760,onLogFileClosed:()=>{},onLogCreated:()=>{}}}class tZ extends K{register(){this.app.singleton(w,()=>new w(I(PZ(),this.app.config.get("log",{}))))}async boot(){if(!process.env.ROOT_DIR)return;await this.app.make(w).boot()}}class oZ extends K{register(){this.app.singleton(f,()=>new f(I(OZ(),this.app.config.get("middleware",{}))))}boot(){this.app.make(f).assertGlobalMiddleware()}}function b4(Z){return Z}function NZ(){return{driver:new _Z,limit:1000,window:60}}class rZ extends K{register(){this.app.singleton(n,()=>new n(I(NZ(),this.app.config.get("ratelimiter",{}))))}}function u4(Z){return Z}function QZ(){return{url:process.env.REDIS_URL,options:void 0}}class aZ extends K{register(){this.app.singleton(T,()=>new T(I(QZ(),this.app.config.get("redis",{}))))}shutdown(){if(!this.app.resolved(T))return;this.app.make(T).close()}}class q extends SZ{status;constructor(Z,$){super(Z);this.status=$;this.name="McpToolError"}}var eZ=/^[A-Za-z0-9_-]{1,64}$/,Z3=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,AZ=4000,t=1e5,$3=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i;class E{dispatcher;static token="router.mcp";plans=new Map;constructor(Z,$){this.dispatcher=$;for(let[G,H]of Object.entries(Z.routes??{}))this.plans.set(G,this.plan(G,H))}list(Z,$){return xZ(Z),this.descriptors($)}descriptors(Z){let $=[];for(let{descriptor:G}of this.plans.values()){if(Z?.names&&!Z.names.includes(G.name))continue;if(Z?.tags&&!G.tags.some((H)=>Z.tags.includes(H)))continue;$.push(G)}return $}async execute(Z,$,G,H){xZ(Z);let W=this.plans.get($);if(!W)throw Error(`McpRegistry: there is no tool named "${$}".`);let{descriptor:X}=W,Y=X.inputSchema.safeParse(G);if(Y.ok===!1)throw new q(`Invalid arguments for "${$}": ${Y.errors.join(", ")}`);let z=Y.value,C=await this.fillPath(W,z,Z.req),{path:B}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${C}`));if(B!==X.url)throw new q(`"${$}" has nothing at ${C}.`,404);let J={};for(let N of W.jsonKeys)if(z[N]!==void 0)J[N]=z[N];let P,O="";if(W.fileFields.length>0)P=await this.formData(W,z,J,H);else if(X.method==="GET")O=X3(J);else if(W.jsonKeys.length>0)P=J;let L;try{L=await this.dispatcher.dispatchAs(Z.req,X.method,O?`${C}?${O}`:C,P)}catch(N){throw console.error(`[gemi/mcp] Dispatching "${$}" failed:`,N),new q(`"${$}" failed on the server.`,500)}return await Y3($,L)}plan(Z,$){if(!eZ.test(Z))throw Error(`McpRouter: "${Z}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let G=`McpRouter: "${Z}" (${$?.method} ${$?.url})`;if(!($ instanceof Object)||$.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${Z}" is not a route. Declare it with this.fromApiRoute(...).`);let{method:H,url:W,meta:X}=$;if(W.startsWith("/__gemi__"))throw Error(`${G} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[H];if(!Y)throw Error(`${G} names no route of this app. Expose a route by the path and verb it is mounted at.`);let z=[...W.matchAll(Z3)].map(([,V,_])=>({name:V,modifier:_})),C=X.params??{};for(let V of z)if(!(V.name in C))throw Error(`${G}: the path param "${V.name}" must be bound or declared "input".`);for(let[V,_]of Object.entries(C)){if(!z.some((D)=>D.name===V))throw Error(`${G}: "${V}" in params is not a param of the url.`);FZ(G,`params.${V}`,_)}let B=[],J;if(X.input){if(J=X.input.toJSONSchema(),J.type!=="object"||!J.properties)throw Error(`${G}: input must be an s.object(...), the fields of the request body.`);B=Object.keys(J.properties)}let P=Object.entries(X.files??{}).map(([V,_])=>({name:V,binder:_}));for(let V of P)FZ(G,`files.${V.name}`,V.binder);if(P.length>0&&H==="GET")throw Error(`${G}: a GET has no body to carry a file.`);let O={},L=new Map;for(let V of z){let _=C[V.name];if(_==="input"){let D=b.string().describe(`The ":${V.name}" segment of the url.`);O[V.name]=V.modifier==="?"||V.modifier==="*"?D.optional():D}else L.set(V.name,_)}for(let V of P)if(V.binder==="input")O[V.name]=b.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.");let N=[...Object.keys(O),...P.map((V)=>V.name)];for(let V of new Set(N))if(B.includes(V))throw Error(`${G}: "${V}" is both an input field and a param or file, and the model can only send one.`);return{descriptor:Object.freeze({name:Z,description:X.description,method:H,url:W,inputSchema:W3(X.input,J,b.object(O)),annotations:G3(H),tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...Y.source?{source:Y.source}:{}}),params:z,paramBinders:L,fileFields:P,jsonKeys:B}}async fillPath(Z,$,G){let H=Z.descriptor.url;for(let W of Z.params){let X=Z.paramBinders.get(W.name),Y;if(X){if(Y=await this.bind(Z,`the param "${W.name}"`,()=>X(G)),Y===void 0||Y===null||Y==="")throw console.error(`[gemi/mcp] The binder for "${W.name}" of "${Z.descriptor.name}" returned ${JSON.stringify(Y)}.`),new q(`"${Z.descriptor.name}" failed on the server.`,500)}else Y=$[W.name];let z=`:${W.name}${W.modifier}`;if(Y===void 0||Y===null||Y===""){if(W.modifier!=="?"&&W.modifier!=="*")throw new q(`"${W.name}" of "${Z.descriptor.name}" must not be empty.`);H=H.replace(`/${z}`,"");continue}H=H.replace(z,H3(Z.descriptor.name,W,String(Y)))}return H}async formData(Z,$,G,H){let W=Z.descriptor.name;if(!H)throw Error(`McpRegistry: "${W}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let X=new FormData;for(let[Y,z]of Object.entries(G))LZ(X,Y,z);for(let Y of Z.fileFields){let z=Y.binder==="input"?$[Y.name]:await this.bind(Z,`the file "${Y.name}"`,()=>Y.binder(H));if(typeof z!=="string"||z==="")throw new q(`"${W}" needs a file for "${Y.name}", and this turn has none. Ask the user to attach one.`);X.append(Y.name,await H.attachments.file(z))}return X}async bind(Z,$,G){try{return await G()}catch(H){throw console.error(`[gemi/mcp] Binding ${$} of "${Z.descriptor.name}" failed:`,H),new q(`"${Z.descriptor.name}" failed on the server.`,500)}}}function xZ(Z){if(Z?.kind!=="local")throw Error("McpRegistry: only local callers are implemented. A remote caller needs a bearer-token resolver, which v1 does not have \u2014 and until it does there is no remote surface to call from.")}function FZ(Z,$,G){if(G!=="input"&&typeof G!=="function")throw Error(`${Z}: ${$} must be a function or "input".`)}function G3(Z){switch(Z){case"GET":return Object.freeze({readOnlyHint:!0});case"DELETE":return Object.freeze({destructiveHint:!0});case"PUT":return Object.freeze({idempotentHint:!0});default:return Object.freeze({})}}function W3(Z,$,G){let H=G.toJSONSchema(),W={...$??{},type:"object",properties:{...$?.properties??{},...H.properties},required:[...$?.required??[],...H.required??[]],additionalProperties:!1},X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["expected an object"]};let z=[],C={};if(Z){let J=Z.safeParse(Y);if(J.ok===!1)z.push(...J.errors);else C={...J.value}}let B=G.safeParse(Y);if(B.ok===!1)z.push(...B.errors);else C={...C,...B.value};return z.length>0?{ok:!1,errors:z}:{ok:!0,value:C}};return{toJSONSchema:()=>W,safeParse:X,parse(Y){let z=X(Y);if(z.ok===!1)throw Error(z.errors.join(", "));return z.value}}}function H3(Z,$,G){let H=$.modifier==="*"||$.modifier==="+"?G.split("/"):[G];if(H.some((W)=>W==="."||W===".."))throw new q(`"${G}" is not a valid value for "${$.name}" of "${Z}".`);return H.map(encodeURIComponent).join("/")}function LZ(Z,$,G){if(G===void 0||G===null)return;if(Array.isArray(G)){for(let H of G)LZ(Z,$,H);return}Z.append($,typeof G==="object"?JSON.stringify(G):String(G))}function X3(Z){let $=new URLSearchParams,G=(H,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)G(H,X);return}$.append(H,typeof W==="object"?JSON.stringify(W):String(W))};for(let[H,W]of Object.entries(Z))G(H,W);return $.toString()}async function Y3(Z,$){if($.status>=200&&$.status<300){let H=$.headers.get("Content-Type");if(H&&!$3.test(H)){let X=(await $.arrayBuffer()).byteLength;return`"${Z}" answered with ${X} bytes of ${H}, which is not shown.`}let W=await $.text();if(W==="")return null;if(W.length>t)return`${W.slice(0,t)}\u2026 [cut at ${t} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let G=await $.text();if($.status>=400&&$.status<500){let H=G.length>AZ?`${G.slice(0,AZ)}\u2026`:G;throw new q(`"${Z}" was refused with ${$.status}${H?`: ${H}`:"."}`,$.status)}if($.status<500)console.error(`[gemi/mcp] "${Z}" answered ${$.status}${$.headers.get("Location")?` to ${$.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new q(`"${Z}" failed on the server.`,$.status)}function g(Z,$){let G=Z.get($);if(!G)throw Error(`Missing "${$}" configuration. Route dispatching needs a root router \u2014 declare it in "app/config/route.ts".`);return G}class z3 extends K{register(){this.app.singleton(S,()=>new S(g(this.app.config,"route.api"))),this.app.singleton(R,()=>new R(g(this.app.config,"route.view"))),this.app.singleton(v,()=>new v({api:this.app.make(S),view:this.app.make(R)},{api:g(this.app.config,"route.api"),view:g(this.app.config,"route.view"),domains:this.app.config.get("route.domains")})),this.app.singleton(E,()=>{let Z=this.app.config.get("route.mcp");if(!Z?.router)throw Error('No MCP router is configured. Declare one as `mcp: { router }` in "app/config/route.ts".');return new E(new Z.router,this.app.make(S))})}boot(){if(this.app.make(S),this.app.make(R),this.app.make(v),this.app.config.get("route.mcp"))this.app.make(E)}}
|
|
3
3
|
export{A as Za,MZ as _a,Q3 as $a,bZ as ab,mZ as bb,F as cb,g3 as db,UZ as eb,hZ as fb,cZ as gb,x as hb,lZ as ib,iZ as jb,sZ as kb,nZ as lb,F4 as mb,PZ as nb,tZ as ob,oZ as pb,b4 as qb,NZ as rb,rZ as sb,u4 as tb,QZ as ub,aZ as vb,q as wb,E as xb,z3 as yb};
|
|
4
4
|
|
|
5
5
|
//# debugId=C0398D840F2B9D2C64756E2164756E21
|