gemi 0.239.0 → 0.240.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/Agent.d.ts +3 -3
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/client/conformance.d.ts.map +1 -1
- package/dist/ai/client/index.js +88 -40
- package/dist/ai/client/index.js.map +1 -1
- package/dist/ai/client/reducer.d.ts +6 -6
- package/dist/ai/client/reducer.d.ts.map +1 -1
- package/dist/ai/index.js +12 -12
- package/dist/ai/index.js.map +3 -3
- package/dist/ai/providers/anthropicRequest.d.ts +2 -1
- package/dist/ai/providers/anthropicRequest.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts +11 -0
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/ai/useChat.d.ts.map +1 -1
- package/dist/{chunk-mmc5bbf4.js → chunk-58xb0s71.js} +27 -27
- package/dist/{chunk-mmc5bbf4.js.map → chunk-58xb0s71.js.map} +3 -3
- package/dist/{chunk-7axcthef.js → chunk-7azdbwdc.js} +1 -1
- package/dist/{chunk-92zmwb33.js → chunk-gjpwvet7.js} +2 -2
- package/dist/{chunk-92zmwb33.js.map → chunk-gjpwvet7.js.map} +1 -1
- package/dist/chunk-gpngw61t.js +12 -0
- package/dist/{chunk-m0n0ddd2.js.map → chunk-gpngw61t.js.map} +4 -4
- package/dist/{chunk-pkew0k7c.js → chunk-rftxm3ny.js} +1 -1
- package/dist/{chunk-sx2gadhs.js → chunk-wefcda84.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-m0n0ddd2.js +0 -12
- /package/dist/{chunk-7axcthef.js.map → chunk-7azdbwdc.js.map} +0 -0
- /package/dist/{chunk-pkew0k7c.js.map → chunk-rftxm3ny.js.map} +0 -0
- /package/dist/{chunk-sx2gadhs.js.map → chunk-wefcda84.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ec as _3,Rc as L3,jc as f3,nc as V2,oc as w3,pc as I3,qd as O3,yc as P3}from"./chunk-mmc5bbf4.js";import{Ed as n}from"./chunk-samm4h7d.js";import{ne as l2,pe as P2,se as s3,te as t3,ue as _$,we as q$}from"./chunk-51mz612v.js";import{Ce as Z3,Ee as c3,Ge as p3,Qe as C,Re as i3,Se as l3,Ue as n3,Ve as A$,ye as E$,ze as d3}from"./chunk-6gek696n.js";import{Ye as B}from"./chunk-bhycdjcv.js";import{Ch as J$,Dh as N$,If as L$,Jf as n2,Jh as M$,Lg as z3,Nf as B2,Of as Q2,Wg as r2,Yg as o,ah as Z$,bh as e2,ch as z$,dh as G$,eg as c2,hh as g2,if as t,ih as f2,jf as U$,kf as m2,mh as w2,nh as W$,of as y3,oh as Y2,pg as F2,ph as X$,qg as d2,qh as Y$,rf as k$,rg as R,rh as v2,sf as b$,sh as Z2,ug as F$,vf as B$,vg as V$,vh as w$,wg as H$,wh as a,xh as i2,yf as I$,yg as g}from"./chunk-q8pr18w6.js";import{Cj as X2,Vi as d,ij as a2,yj as B3}from"./chunk-j3zz8046.js";import{Ej as a3}from"./chunk-2g1h9ktj.js";import{Kj as l,Oj as T$,Pj as _2,Qj as h}from"./chunk-e4adgvd6.js";import{Yj as u}from"./chunk-0xmk4jyj.js";import{ck as p2}from"./chunk-8wvh099n.js";import{fk as O$,gk as s2,jk as I2,kk as o2,nk as D$}from"./chunk-4sv5vkab.js";import{Bk as r3,Gk as e3}from"./chunk-768yza4f.js";import{Wk as u3,Yk as c,il as W2}from"./chunk-0wa8ztk5.js";import{kl as q}from"./chunk-6wv3k8ap.js";import{ql as S$}from"./chunk-ccymw1ed.js";import{Yl as R$}from"./chunk-aczp96k5.js";import{mm as t2}from"./chunk-rc86ewq1.js";import{tm as N2,wm as k}from"./chunk-3mq0wmq7.js";import{Fm as u2}from"./chunk-vqmy8jfr.js";import{Vm as $$}from"./chunk-4mysb5ej.js";var v$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var G3=/^[A-Za-z0-9_-]{1,64}$/,h$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,W3=4000,E=1e5,m$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,j3=new WeakMap;function D9($){return j3.get($)}class s{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=i$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,u$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(U3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(U3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new m(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let U=Q.value,V={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,V),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${H}.`,404);let P={};for(let x of Y.jsonKeys)if(U[x]!==void 0)P[x]=U[x];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,V);else if(K.method==="GET")J=Z8(P);else if(Y.jsonKeys.length>0)I=P;let D=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(V)):void 0,j={...D?{credentials:D}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let x=J?`${H}?${J}`:H;T=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,x,I,j):await this.dispatcher.dispatchAs($.req,K.method,x,I)}catch(x){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,x),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await N3(Z,T);return await this.project(Y,V,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(h$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(H3(S))o$(z,`params.${N}`,S);else V3(z,`params.${N}`,S)}let U=[],V;if(X.input){if(V=X.input.toJSONSchema(),V.type!=="object"||!V.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(V.properties)}let H=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of H)V3(z,`files.${N.name}`,N.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=J3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,D=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=l.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(H3(S)){let w=S.as??N.name;I(w,S.input),D.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let j={};for(let N of H)if(N.binder==="input")I(N.name,l.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let T=[...Object.keys(P),...H.map((N)=>N.name)];for(let N of new Set(T))if(U.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let x=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:F3(X.input,V,l.object(P)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),A=!H.every((N)=>N.binder==="input")?null:H.length===0?x:Object.freeze({...x,inputSchema:F3(X.input,V,l.object(e$(P,Object.keys(j))),j)});return{kind:"route",descriptor:x,remote:A,params:K,paramBinders:J,modelParams:D,fileFields:H,jsonKeys:U,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let V=Y[U];if(V===void 0||V===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof V!=="string")K.push(`a file's "${U}" must be a string`);else Q[U]=V}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:J3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!K2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let U=G.signal??new AbortController().signal;return Q3(X,Y.value,K3(Y3(X,Q,U,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(O2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return j3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(A,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(A,N):c$(A,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await X3(this.runNative($,{...K,ctx:G},G),Q)}let U=$.meta.remote,V=await this.bind($,"the remote context",()=>U.context(K));if(typeof V!=="object"||V===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,V),new O(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=Y3($,V,P,I);if(!W.approved&&K2($)&&await Q3($,K.input,K3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let D;try{D=await X3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(A){if(P.aborted&&A===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${H} ms.`,504)}if(A instanceof O)throw A;if(A instanceof n||A instanceof m)throw new O(A.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,A),new O(`"${X}" failed on the server.`,500)}let j=(A)=>{return console.error(`[gemi/mcp] "${X}" ${A}`),new O(`"${X}" failed on the server.`,500)};if(P3(D))throw j("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(A){throw j(`could not read an image it showed: ${A}`)}let x=D;if($.descriptor.outputSchema){let A=$.descriptor.outputSchema.safeParse(x);if(A.ok===!1)throw j(`answered what its output schema refuses: ${A.errors.join(", ")}`);x=A.value}for(let A of T)W.images?.(A);if(x===void 0)return null;if(typeof x==="string")return x.length>E?`${x.slice(0,E)}\u2026 [cut at ${E} of ${x.length} characters]`:x;let z2=JSON.stringify(x);if(z2!==void 0&&z2.length>E)return`${z2.slice(0,E)}\u2026 [cut at ${E} of ${z2.length} characters]`;return x}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let U=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${U}`,"");continue}W=W.replace(U,$8($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,U]of Object.entries(Z))j2(K,Q,U);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))j2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(V)=>new O(`"${Z}" of "${$}" ${V}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!l$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!n$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let V=W.data.replace(/\s+/g,"");if(Math.floor(V.length*3/4)-t$(V)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(V.length%4!==0||!s$.test(V))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(V,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let V=await B3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!V.ok)throw G(`could not be fetched: ${U.host} answered ${V.status}.`);let H=await V.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(V){if(V instanceof O)throw V;throw G(`could not be fetched from ${U.host}: ${V instanceof Error?V.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(v$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!g$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await N3(G,z);let X=(H,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,F);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let U=Q;if($.result)try{U=await $.result(Q,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let V=JSON.stringify(U);if(V!==void 0&&V.length>E)return`${V.slice(0,E)}\u2026 [cut at ${E} of ${V.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function u$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function d$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function X3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!d$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function c$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function Y3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(V)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${V}.`,{retryable:!1})},U={put:async(V,H={})=>{if(!H.showModel)return K("attachment store")();let F=H.mimeType||V.type;if(!/^image\//i.test(F))throw new n(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=V.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(V instanceof File?V.name:"image"),mimeType:F,size:V.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(V)=>O3({...V,signal:V.signal?AbortSignal.any([z,V.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:_3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:L3(),meter:I3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function K3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Q3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function O2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function U3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var p$=10485760;function i$($){let Z=$?.maxBytes??p$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function l$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var n$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function t$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function H3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function o$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var a$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function r$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function J3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?r$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!a$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function F3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,U])=>[Q,U.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let U=[],V={};if($){let F=$.safeParse(Q);if(F.ok===!1)U.push(...F.errors);else V={...F.value}}let H=z.safeParse(Q);if(H.ok===!1)U.push(...H.errors);else V={...V,...H.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){U.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((D)=>`${F}: ${D}`));else V[F]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:V}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let U=K(Q);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function e$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function $8($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function j2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)j2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function Z8($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function N3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!m$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>E)return`${W.slice(0,E)}\u2026 [cut at ${E} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>W3?`${z.slice(0,W3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as z8,randomBytes as G8,timingSafeEqual as W8}from"crypto";function D2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class X8{options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${G8(32).toString("base64url")}`}static hash($){return z8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&W8(z,G)}async resolve($){let Z=D2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as v3,randomBytes as C3}from"crypto";async function x2($,Z){let z=Y8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function Y8(){try{let $=k();return $.bound(t)?$.make(t):null}catch{return null}}var A2=["2026-07-28"],U2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...A2,...U2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function x3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as K8,timingSafeEqual as Q8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!Q8(K,Q))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function A3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",S3="gemi.mcp.session.v1",U8=86400000,q3=600000,T3="gemi_approval",b2=2000,V8={limit:600,window:60},H8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=N8(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,V2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??V8,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new f3,this.approvalTimeoutMs=Z.approvalTimeoutMs??q3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?F8(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return M3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return M3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(D2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),R3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),V=$.headers.get("mcp-protocol-version");if(V!==null&&V!==U.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${V} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(H,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),R3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=U2.includes(G)?G:U2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:k3(X.elicitation),p:H2(z),exp:Date.now()+U8},K=k2(S3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(S3,"gms1",z);if(!G||G.p!==H2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||x3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,D)=>{G.outcome="denied",G.reason=J,G.message=D},K=(J,D,j)=>{if(G.outcome="error",G.message=J,D!==void 0)G.status=D;if(j!==void 0)G.error=j},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let j=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(j),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let j=await this.approval($,Q,z,Y,G);if(j.kind==="answer")return j.result;G.approved=!0}}let U=P8($),V=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>V.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let j=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,j),new _(L.InvalidParams,j)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let D=`"${Z}" failed on the server.`;return K(D,void 0,J),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}let F=typeof H==="string"?H:JSON.stringify(H??null),P=Q.outputSchema&&($.era.modern||M(H))?{structuredContent:H}:{},I=[...V.length>0&&H===null?[]:[{type:"text",text:F}],...V];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,D=B8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==H2($.principal)||T.t!==Z.name||T.a!==D)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return E3(I[T3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!k3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:H2($.principal),t:Z.name,a:D,n:C3(16).toString("base64url"),exp:Date.now()+q3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[T3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",j),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${C3(12).toString("base64url")}`,V=Q.sessionId,H=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(U),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(U,{session:V,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&E3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new g3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=y3(new d($,{},"api",this.endpoint.pathname)),z=await x2(`mcp-auth-failed:${Z}`,H8);return z===null?null:b3(z)}async spend($){if(!this.rateLimit)return null;let Z=await x2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:b3(Z)}}class g3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
2
|
+
import{Ec as _3,Rc as L3,jc as f3,nc as V2,oc as w3,pc as I3,qd as O3,yc as P3}from"./chunk-58xb0s71.js";import{Ed as n}from"./chunk-samm4h7d.js";import{ne as l2,pe as P2,se as s3,te as t3,ue as _$,we as q$}from"./chunk-51mz612v.js";import{Ce as Z3,Ee as c3,Ge as p3,Qe as C,Re as i3,Se as l3,Ue as n3,Ve as A$,ye as E$,ze as d3}from"./chunk-6gek696n.js";import{Ye as B}from"./chunk-bhycdjcv.js";import{Ch as J$,Dh as N$,If as L$,Jf as n2,Jh as M$,Lg as z3,Nf as B2,Of as Q2,Wg as r2,Yg as o,ah as Z$,bh as e2,ch as z$,dh as G$,eg as c2,hh as g2,if as t,ih as f2,jf as U$,kf as m2,mh as w2,nh as W$,of as y3,oh as Y2,pg as F2,ph as X$,qg as d2,qh as Y$,rf as k$,rg as R,rh as v2,sf as b$,sh as Z2,ug as F$,vf as B$,vg as V$,vh as w$,wg as H$,wh as a,xh as i2,yf as I$,yg as g}from"./chunk-q8pr18w6.js";import{Cj as X2,Vi as d,ij as a2,yj as B3}from"./chunk-j3zz8046.js";import{Ej as a3}from"./chunk-2g1h9ktj.js";import{Kj as l,Oj as T$,Pj as _2,Qj as h}from"./chunk-e4adgvd6.js";import{Yj as u}from"./chunk-0xmk4jyj.js";import{ck as p2}from"./chunk-8wvh099n.js";import{fk as O$,gk as s2,jk as I2,kk as o2,nk as D$}from"./chunk-4sv5vkab.js";import{Bk as r3,Gk as e3}from"./chunk-768yza4f.js";import{Wk as u3,Yk as c,il as W2}from"./chunk-0wa8ztk5.js";import{kl as q}from"./chunk-6wv3k8ap.js";import{ql as S$}from"./chunk-ccymw1ed.js";import{Yl as R$}from"./chunk-aczp96k5.js";import{mm as t2}from"./chunk-rc86ewq1.js";import{tm as N2,wm as k}from"./chunk-3mq0wmq7.js";import{Fm as u2}from"./chunk-vqmy8jfr.js";import{Vm as $$}from"./chunk-4mysb5ej.js";var v$="mcp",g$=/^[\x21\x23-\x5B\x5D-\x7E]+$/;class O extends n{status;constructor($,Z){super($);this.status=Z;this.name="McpToolError"}}class m extends Error{reason;constructor($,Z){super($);this.reason=Z;this.name="McpCallRefusedError"}}var G3=/^[A-Za-z0-9_-]{1,64}$/,h$=/:([A-Za-z_][A-Za-z0-9_]*)([?*+]?)/g,W3=4000,E=1e5,m$=/^(text\/|application\/([\w.+-]*\+)?(json|xml))/i,j3=new WeakMap;function D9($){return j3.get($)}class s{router;dispatcher;static token="router.mcp";plans=new Map;scopeTools=new Map;files;featureOn;constructor($,Z,z={}){this.router=$;this.dispatcher=Z;this.files=i$(z.files),this.featureOn=z.featureOn??Q2;for(let[G,W]of Object.entries($.routes??{}))this.plans.set(G,u$(W)?this.planNative(G,W):this.plan(G,W));this.resolveScopes()}list($,Z){if(O2($),$.kind==="local")return this.descriptors(Z);let z=[];for(let[G,W]of this.plans){if(!W.remote||!this.grants($.principal,G))continue;if(U3(W.remote,Z))z.push(W.remote)}return z}async available($,Z){let z=[];for(let G of this.list($,Z))if(await this.isOn(G))z.push(G);return z}descriptors($){let Z=[];for(let{descriptor:z}of this.plans.values())if(U3(z,$))Z.push(z);return Z}get maxFileBytes(){return this.files.maxBytes}scopes(){return[...this.scopeTools].map(([$,{description:Z}])=>({name:$,description:Z}))}scopesFor($){return[...this.scopeTools].filter(([,{tools:Z}])=>Z.has($)).map(([Z])=>Z)}async execute($,Z,z,G,W={}){O2($);let X=this.plans.get(Z);if(X&&!await this.isOn(X.descriptor)){if($.kind==="remote")throw new m(`There is no tool named "${Z}".`,"unknown-tool");throw new O(`There is no tool named "${Z}".`,404)}if($.kind==="remote"){if(!X?.remote||!this.grants($.principal,Z))throw new m(`There is no tool named "${Z}".`,"unknown-tool");if(X.descriptor.requiresApproval&&W.approved!==!0&&!K2(X))throw new m(`"${Z}" needs the user's approval, and this call does not have it.`,"approval-required");G=void 0}if(!X)throw Error(`McpRegistry: there is no tool named "${Z}".`);if(X.kind==="tool")return await this.executeNative(X,$,z,G,W);let Y=X,K=$.kind==="remote"?Y.remote:Y.descriptor,Q=K.inputSchema.safeParse(z);if(Q.ok===!1)throw new O(`Invalid arguments for "${Z}": ${Q.errors.join(", ")}`);let U=Q.value,V={caller:$,req:$.req,tool:K,input:U,ctx:G},H=await this.fillPath(Y,V),{path:F}=this.dispatcher.getRouteHandlerAndParams(new Request(`http://gemi.internal/api${H}`));if(F!==K.url)throw new O(`"${Z}" has nothing at ${H}.`,404);let P={};for(let x of Y.jsonKeys)if(U[x]!==void 0)P[x]=U[x];let I,J="";if(Y.fileFields.length>0)I=await this.formData(Y,P,V);else if(K.method==="GET")J=Z8(P);else if(Y.jsonKeys.length>0)I=P;let D=this.router.credentials?await this.bind(Y,"the credentials",()=>this.router.credentials(V)):void 0,j={...D?{credentials:D}:{},...W.signal?{signal:W.signal}:{},...W.progress?{progress:W.progress}:{},...$.kind==="remote"?{identity:{user:$.principal.user,grant:{via:$.principal.via,id:$.principal.id,scopes:$.principal.scopes,...$.principal.clientId?{clientId:$.principal.clientId}:{}}}}:{}},T;try{let x=J?`${H}?${J}`:H;T=Object.keys(j).length>0?await this.dispatcher.dispatchAs($.req,K.method,x,I,j):await this.dispatcher.dispatchAs($.req,K.method,x,I)}catch(x){throw console.error(`[gemi/mcp] Dispatching "${Z}" failed:`,x),new O(`"${Z}" failed on the server.`,500)}if(!Y.result&&!K.outputSchema)return await N3(Z,T);return await this.project(Y,V,T)}async isOn($){return $.feature===void 0||await this.featureOn($.feature)===!0}plan($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (${Z?.method} ${Z?.url})`;if(!(Z instanceof Object)||Z.__internal_brand!=="McpRoute")throw Error(`McpRouter: "${$}" is not a route or a tool. Declare it with this.fromApiRoute(...) or this.fromTool(...).`);let{method:G,url:W,meta:X}=Z;if(X.feature!==void 0&&(typeof X.feature!=="string"||X.feature===""))throw Error(`${z}: feature must be a feature key from app/features.`);if(W.startsWith("/__gemi__"))throw Error(`${z} is a framework route, not an app route.`);let Y=this.dispatcher.flatRoutes[W]?.[G];if(!Y)throw Error(`${z} names no route of this app. Expose a route by the path and verb it is mounted at.`);let K=[...W.matchAll(h$)].map(([,N,S])=>({name:N,modifier:S})),Q=X.params??{};for(let N of K)if(!(N.name in Q))throw Error(`${z}: the path param "${N.name}" must be bound or declared "input".`);for(let[N,S]of Object.entries(Q)){if(!K.some((w)=>w.name===N))throw Error(`${z}: "${N}" in params is not a param of the url.`);if(H3(S))o$(z,`params.${N}`,S);else V3(z,`params.${N}`,S)}let U=[],V;if(X.input){if(V=X.input.toJSONSchema(),V.type!=="object"||!V.properties)throw Error(`${z}: input must be an s.object(...), the fields of the request body.`);U=Object.keys(V.properties)}let H=Object.entries(X.files??{}).map(([N,S])=>({name:N,binder:S}));for(let N of H)V3(z,`files.${N.name}`,N.binder);if(X.result!==void 0&&typeof X.result!=="function")throw Error(`${z}: result must be a function.`);if(X.output!==void 0&&typeof X.output?.safeParse!=="function")throw Error(`${z}: output must be a schema, built with s.`);if(X.title!==void 0&&(typeof X.title!=="string"||X.title===""))throw Error(`${z}: title must be a non-empty string.`);let F=J3(z,G,X.annotations);if(H.length>0&&G==="GET")throw Error(`${z}: a GET has no body to carry a file.`);let P={},I=(N,S)=>{if(N in P)throw Error(`${z}: "${N}" is the input key of two params or files, and the model can only send one.`);P[N]=S},J=new Map,D=new Map;for(let N of K){let S=Q[N.name];if(S==="input"){let w=l.string().describe(`The ":${N.name}" segment of the url.`);I(N.name,N.modifier==="?"||N.modifier==="*"?w.optional():w)}else if(H3(S)){let w=S.as??N.name;I(w,S.input),D.set(N.name,{key:w,param:S})}else J.set(N.name,S)}let j={};for(let N of H)if(N.binder==="input")I(N.name,l.string().describe("The id of an attachment the user uploaded or a tool produced (gemi_att_\u2026), whose file is sent as this field.")),j[N.name]=this.remoteFileSchema();let T=[...Object.keys(P),...H.map((N)=>N.name)];for(let N of new Set(T))if(U.includes(N))throw Error(`${z}: "${N}" is both an input field and a param or file, and the model can only send one.`);let x=Object.freeze({kind:"route",name:$,description:X.description,method:G,url:W,inputSchema:F3(X.input,V,l.object(P)),...X.output?{outputSchema:X.output}:{},...X.title?{title:X.title}:{},annotations:F,tags:Object.freeze([...X.tags??[]]),requiresApproval:X.requiresApproval===!0,...X.feature!==void 0?{feature:X.feature}:{},...Y.source?{source:Y.source}:{}}),A=!H.every((N)=>N.binder==="input")?null:H.length===0?x:Object.freeze({...x,inputSchema:F3(X.input,V,l.object(e$(P,Object.keys(j))),j)});return{kind:"route",descriptor:x,remote:A,params:K,paramBinders:J,modelParams:D,fileFields:H,jsonKeys:U,...X.result?{result:X.result}:{}}}remoteFileSchema(){let{maxBytes:$,fetch:Z}=this.files,z={name:{type:"string",description:"The file's name, like report.pdf."},mimeType:{type:"string",description:"The file's media type, like application/pdf."},data:{type:"string",contentEncoding:"base64",description:`The file's bytes, base64-encoded (RFC 4648, standard alphabet). At most ${$} bytes decoded.`}};if(Z)z.url={type:"string",format:"uri",description:"An https URL the server downloads the file from, instead of data."};let G={type:"object",description:Z?"A file, sent as base64 in data or fetched from url: exactly one of the two.":"A file, sent as base64 in data.",properties:z,required:["name","mimeType"],additionalProperties:!1},W=Object.keys(z),X=(Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return{ok:!1,errors:["a file must be an object"]};let K=[],Q={};for(let U of Object.keys(Y))if(!W.includes(U))K.push(`a file has no field "${U}"`);for(let U of W){let V=Y[U];if(V===void 0||V===null){if(U==="name"||U==="mimeType")K.push(`a file needs "${U}"`);continue}if(typeof V!=="string")K.push(`a file's "${U}" must be a string`);else Q[U]=V}return K.length>0?{ok:!1,errors:K}:{ok:!0,value:Q}};return{toJSONSchema:()=>G,safeParse:X,parse(Y){let K=X(Y);if(K.ok===!1)throw Error(K.errors.join(", "));return K.value}}}planNative($,Z){if(!G3.test($))throw Error(`McpRouter: "${$}" is not a valid tool name. A routes key is the tool's name as a model and an MCP client see it, used verbatim \u2014 letters, digits, "_" and "-", at most 64.`);let z=`McpRouter: "${$}" (a native tool)`,{tool:G,meta:W={}}=Z;if(!(G instanceof Object)||typeof G.name!=="string")throw Error(`${z} is not an AgentTool. Pass one built with AgentTool.create(...).`);if(G.answeredBy==="client"||typeof G.execute!=="function")throw Error(`${z}: "${G.name}" is answered by the client, and only a tool the server runs can be called through the registry.`);if(typeof G.inputSchema==="function")throw Error(`${z}: "${G.name}" resolves its input schema per run, and the registry lists one schema to every caller. Give it a fixed inputSchema.`);if(typeof G.inputSchema?.safeParse!=="function")throw Error(`${z}: its inputSchema must be a schema, built with s.`);if(typeof W!=="object"||W===null)throw Error(`${z}: the meta must be an object.`);if(W.description!==void 0&&(typeof W.description!=="string"||W.description.trim()===""))throw Error(`${z}: description must be a non-empty string.`);if(W.title!==void 0&&(typeof W.title!=="string"||W.title===""))throw Error(`${z}: title must be a non-empty string.`);if(W.tags!==void 0&&(!Array.isArray(W.tags)||W.tags.some((Q)=>typeof Q!=="string")))throw Error(`${z}: tags must be an array of strings.`);if(W.requiresApproval===!1&&G.requiresApproval)throw Error(`${z}: "${G.name}" requires approval, and requiresApproval: false would run it without asking. Leave it out, or register a tool that does not ask.`);let X=W.remote;if(X!==void 0){if(typeof X!=="object"||X===null||typeof X.context!=="function")throw Error(`${z}: remote must be { context(call) }, building the AgentContext a remote call runs with.`);if(X.progress!==void 0&&typeof X.progress!=="function")throw Error(`${z}: remote.progress must be a function.`)}let Y=W.description??G.description;if(typeof Y!=="string"||Y.trim()==="")throw Error(`${z} needs a description: the tool's own, or the meta's.`);let K=Object.freeze({kind:"tool",name:$,description:Y,inputSchema:G.inputSchema,...G.outputSchema?{outputSchema:G.outputSchema}:{},...W.title?{title:W.title}:{},annotations:J3(z,void 0,W.annotations),tags:Object.freeze([...W.tags??[]]),requiresApproval:G.requiresApproval||W.requiresApproval===!0});return{kind:"tool",descriptor:K,remote:X?K:null,tool:G,meta:W}}async approvalRequired($,Z,z,G={}){let W=this.plans.get(Z);if(!W)return!0;if(!K2(W))return W.descriptor.requiresApproval;let X=W;if($.kind!=="remote"||!X.meta.remote)return!0;let Y=X.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)return!0;let K={caller:$,req:$.req,tool:X.descriptor,input:Y.value},Q;try{Q=await this.bind(X,"the remote context",()=>X.meta.remote.context(K))}catch{return!0}if(typeof Q!=="object"||Q===null)return!0;let U=G.signal??new AbortController().signal;return Q3(X,Y.value,K3(Y3(X,Q,U,[])))}nativeApproval($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return K2(Z)??Z.descriptor.requiresApproval}nativeTool($){let Z=this.plans.get($);if(Z?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${$}".`);return Z.tool}startNative($,Z,z,G){let W=this.plans.get(Z);if(W?.kind!=="tool")throw Error(`McpRegistry: there is no native tool named "${Z}".`);if($===void 0)return W.tool.execute(z,G);if(O2($),$.kind!=="local")throw Error("McpRegistry: startNative is for a local caller. A remote call goes through execute().");let X=W.descriptor.inputSchema.safeParse(z);if(X.ok===!1)throw new O(`Invalid arguments for "${Z}": ${X.errors.join(", ")}`);return this.runNative(W,{caller:$,req:$.req,tool:W.descriptor,input:X.value},G)}runNative($,Z,z){let G={...z};return j3.set(G,{...Z,ctx:G}),$.tool.execute(Z.input,G)}async executeNative($,Z,z,G,W){let{name:X}=$.descriptor,Y=$.descriptor.inputSchema.safeParse(z);if(Y.ok===!1)throw new O(`Invalid arguments for "${X}": ${Y.errors.join(", ")}`);let K={caller:Z,req:Z.req,tool:$.descriptor,input:Y.value},Q=(A,N)=>{if(!W.progress)return;let S;try{S=$.meta.remote?.progress?$.meta.remote.progress(A,N):c$(A,N)}catch(w){console.error(`[gemi/mcp] The progress mapping of "${X}" failed:`,w);return}if(S)W.progress(S)};if(Z.kind==="local"){if(!G)throw Error(`McpRegistry: "${X}" is a native tool, which runs with the tool context of an agent call, and none was passed to execute().`);return await X3(this.runNative($,{...K,ctx:G},G),Q)}let U=$.meta.remote,V=await this.bind($,"the remote context",()=>U.context(K));if(typeof V!=="object"||V===null)throw console.error(`[gemi/mcp] The remote context of "${X}" is not an object:`,V),new O(`"${X}" failed on the server.`,500);let H=$.tool.timeoutMs,F=[...W.signal?[W.signal]:[],...H!==void 0?[AbortSignal.timeout(H)]:[]],P=F.length===0?new AbortController().signal:F.length===1?F[0]:AbortSignal.any(F),I=[],J=Y3($,V,P,I);if(!W.approved&&K2($)&&await Q3($,K.input,K3(J)))throw new m(`"${X}" needs the user's approval, and this call does not have it.`,"approval-required");let D;try{D=await X3(this.runNative($,{...K,ctx:J},J),Q,P)}catch(A){if(P.aborted&&A===P.reason){if(W.signal?.aborted)throw new O(`"${X}" was cancelled.`,499);throw new O(`"${X}" did not finish within ${H} ms.`,504)}if(A instanceof O)throw A;if(A instanceof n||A instanceof m)throw new O(A.message);throw console.error(`[gemi/mcp] "${X}" failed for a remote caller:`,A),new O(`"${X}" failed on the server.`,500)}let j=(A)=>{return console.error(`[gemi/mcp] "${X}" ${A}`),new O(`"${X}" failed on the server.`,500)};if(P3(D))throw j("answered a job handle, and a remote call has no background jobs.");let T;try{T=await Promise.all(I)}catch(A){throw j(`could not read an image it showed: ${A}`)}let x=D;if($.descriptor.outputSchema){let A=$.descriptor.outputSchema.safeParse(x);if(A.ok===!1)throw j(`answered what its output schema refuses: ${A.errors.join(", ")}`);x=A.value}for(let A of T)W.images?.(A);if(x===void 0)return null;if(typeof x==="string")return x.length>E?`${x.slice(0,E)}\u2026 [cut at ${E} of ${x.length} characters]`:x;let z2=JSON.stringify(x);if(z2!==void 0&&z2.length>E)return`${z2.slice(0,E)}\u2026 [cut at ${E} of ${z2.length} characters]`;return x}async fillPath($,Z){let{input:z,req:G}=Z,W=$.descriptor.url;for(let X of $.params){let Y=$.paramBinders.get(X.name),K=$.modelParams.get(X.name),Q;if(Y||K){if(Q=K?await this.bind($,`the param "${X.name}"`,()=>K.param.bind(z[K.key],G,Z),{refusals:!0}):await this.bind($,`the param "${X.name}"`,()=>Y(G,Z)),Q===void 0||Q===null||Q==="")throw console.error(`[gemi/mcp] The ${K?"resolver":"binder"} for "${X.name}" of "${$.descriptor.name}" returned ${JSON.stringify(Q)}.`),new O(`"${$.descriptor.name}" failed on the server.`,500)}else Q=z[X.name];let U=`:${X.name}${X.modifier}`;if(Q===void 0||Q===null||Q===""){if(X.modifier!=="?"&&X.modifier!=="*")throw new O(`"${X.name}" of "${$.descriptor.name}" must not be empty.`);W=W.replace(`/${U}`,"");continue}W=W.replace(U,$8($.descriptor.name,X,String(Q)))}return W}async formData($,Z,z){let{input:G,ctx:W}=z,X=$.descriptor.name;if(z.caller.kind==="remote"){let K=new FormData;for(let[Q,U]of Object.entries(Z))j2(K,Q,U);for(let Q of $.fileFields)K.append(Q.name,await this.remoteFile(X,Q.name,G[Q.name]));return K}if(!W)throw Error(`McpRegistry: "${X}" sends a file, which is resolved through the tool context's attachments, and none was passed to execute().`);let Y=new FormData;for(let[K,Q]of Object.entries(Z))j2(Y,K,Q);for(let K of $.fileFields){let Q=K.binder==="input"?G[K.name]:await this.bind($,`the file "${K.name}"`,()=>K.binder(W,z));if(typeof Q!=="string"||Q==="")throw new O(`"${X}" needs a file for "${K.name}", and this turn has none. Ask the user to attach one.`);Y.append(K.name,await W.attachments.file(Q))}return Y}async remoteFile($,Z,z){let G=(V)=>new O(`"${Z}" of "${$}" ${V}`,400),W=z,{maxBytes:X,fetch:Y}=this.files;if(!l$(W.name))throw G("needs a name of 1 to 255 characters, without control characters or slashes.");if(!n$.test(W.mimeType))throw G(`has a mimeType that is not a media type: "${W.mimeType.slice(0,100)}".`);let K=typeof W.data==="string",Q=typeof W.url==="string";if(K===Q)throw G(Y?"needs exactly one of data or url.":"needs its bytes, base64, in data.");if(K){let V=W.data.replace(/\s+/g,"");if(Math.floor(V.length*3/4)-t$(V)>X)throw G(`is larger than the ${X} bytes a file may be.`);if(V.length%4!==0||!s$.test(V))throw G("has data that is not base64 (RFC 4648, standard alphabet, padded).");return new File([Buffer.from(V,"base64")],W.name,{type:W.mimeType})}if(!Y)throw G("cannot be fetched from a URL here. Send its bytes, base64, in data.");let U;try{U=new URL(W.url)}catch{throw G("has a url that is not a URL.")}if(U.protocol!=="https:")throw G("can only be fetched from an https URL.");try{let V=await B3(U.href,{...Y,maxSize:Math.min(Y.maxSize??X,X),redirect:"follow"});if(!V.ok)throw G(`could not be fetched: ${U.host} answered ${V.status}.`);let H=await V.arrayBuffer();return new File([H],W.name,{type:W.mimeType})}catch(V){if(V instanceof O)throw V;throw G(`could not be fetched from ${U.host}: ${V instanceof Error?V.message:"failed"}.`)}}grants($,Z){for(let z of $.scopes??[])if(this.scopeTools.get(z)?.tools.has(Z))return!0;return!1}resolveScopes(){let $=this.router.scopes;if($===void 0){this.scopeTools.set(v$,{description:"Use this app's tools as you",tools:new Set(this.plans.keys())});return}if(typeof $!=="object"||$===null)throw Error("McpRouter: scopes must be an object of scope names.");let Z=new Set([...this.plans.values()].flatMap(({descriptor:z})=>z.tags));for(let[z,G]of Object.entries($)){let W=`McpRouter: scope "${z}"`;if(!g$.test(z))throw Error(`${W} is not a valid OAuth scope: printable ASCII, no spaces or quotes.`);if(typeof G?.description!=="string"||G.description==="")throw Error(`${W} needs a description: it is what a consent screen shows.`);let X=new Set;for(let Y of G.tags??[]){if(!Z.has(Y))throw Error(`${W} names the tag "${Y}", which no tool has.`);for(let[K,{descriptor:Q}]of this.plans)if(Q.tags.includes(Y))X.add(K)}for(let Y of G.names??[]){if(!this.plans.has(Y))throw Error(`${W} names "${Y}", which is no tool.`);X.add(Y)}if(X.size===0)throw Error(`${W} reaches no tool. Give it tags or names.`);this.scopeTools.set(z,{description:G.description,tools:X})}}async project($,Z,z){let{name:G,outputSchema:W}=$.descriptor;if(z.status<200||z.status>=300)return await N3(G,z);let X=(H,F)=>{if(F===void 0)console.error(`[gemi/mcp] "${G}" ${H}`);else console.error(`[gemi/mcp] "${G}" ${H}`,F);return new O(`"${G}" failed on the server.`,500)},Y=z.headers.get("Content-Type"),K=await z.text(),Q=null;if(K!=="")try{Q=JSON.parse(K)}catch{throw X(`answered ${Y??"a body with no content-type"} that is not JSON, and its result or output needs JSON.`)}let U=Q;if($.result)try{U=await $.result(Q,Z)}catch(H){throw X("failed in its result projection:",H)}if(W){let H=W.safeParse(U);if(H.ok===!1)throw X(`answered what its output schema refuses: ${H.errors.join(", ")}`);U=H.value}if(U===void 0)return null;let V=JSON.stringify(U);if(V!==void 0&&V.length>E)return`${V.slice(0,E)}\u2026 [cut at ${E} of ${V.length} characters]`;return U}async bind($,Z,z,G={}){try{return await z()}catch(W){if(G.refusals&&W instanceof n)throw W;throw console.error(`[gemi/mcp] Binding ${Z} of "${$.descriptor.name}" failed:`,W),new O(`"${$.descriptor.name}" failed on the server.`,500)}}}function u$($){return $ instanceof Object&&$.__internal_brand==="McpTool"}function d$($){return typeof $==="object"&&$!==null&&typeof $.next==="function"&&Symbol.asyncIterator in $}async function X3($,Z,z){let G;if(z)G=new Promise((X,Y)=>{if(z.aborted)Y(z.reason);else z.addEventListener("abort",()=>Y(z.reason),{once:!0})}),G.catch(()=>{});let W=(X)=>G?Promise.race([X,G]):X;if(!d$($))return await W(Promise.resolve($));try{let X=0,Y=await W($.next());while(!Y.done)Z(Y.value,++X),Y=await W($.next());return Y.value}catch(X){throw $.return(void 0).catch(()=>{}),X}}function c$($,Z){if(typeof $==="string")return{progress:Z,message:$};if(typeof $==="object"&&$!==null){let{progress:z,total:G,message:W}=$;if(typeof z==="number"&&Number.isFinite(z))return{progress:z,...typeof G==="number"?{total:G}:{},...typeof W==="string"?{message:W}:{}};if(typeof W==="string")return{progress:Z,message:W}}return{progress:Z}}function Y3($,Z,z,G){let W=$.descriptor.name,X=`mcp_${crypto.randomUUID()}`,Y=`mcp_call_${crypto.randomUUID()}`,K=(V)=>async()=>{throw new n(`"${W}" was called by a remote MCP client, which has no ${V}.`,{retryable:!1})},U={put:async(V,H={})=>{if(!H.showModel)return K("attachment store")();let F=H.mimeType||V.type;if(!/^image\//i.test(F))throw new n(`"${W}" was called by a remote MCP client, which is shown images only, and this is ${F?`"${F}"`:"a blob with no type"}.`,{retryable:!1});let P=V.arrayBuffer().then((I)=>({type:"image",data:Buffer.from(I).toString("base64"),mimeType:F}));return P.catch(()=>{}),G.push(P),{id:`gemi_att_${crypto.randomUUID()}`,scopeKey:`mcp:${X}`,name:H.name??(V instanceof File?V.name:"image"),mimeType:F,size:V.size,createdAt:new Date().toISOString(),destination:"provider"}},get:K("attachment store"),read:K("attachment store"),file:K("attachment store")};return{context:Z,body:{},runId:X,toolCallId:Y,signal:z,step:1,depth:0,resumed:!1,attachments:U,turn:Object.freeze({attachments:Object.freeze([])}),runAgent:K("agent run to nest a sub-agent in"),generateImage:K("attachment store to put an image in"),editImage:K("attachment store to put an image in"),generate:(V)=>O3({...V,signal:V.signal?AbortSignal.any([z,V.signal]):z},{origin:{mcp:W,runId:X,toolCallId:Y}}),jobs:_3({jobs:void 0,threadId:void 0,runId:X,toolCallId:Y,toolName:W,depth:0,async:$.tool.async,attachments:null}),memory:L3(),meter:I3().meter}}function K2($){if($.kind!=="tool"||$.meta.requiresApproval===!0)return;return $.tool.approvalPredicate}function K3($){return{context:$.context,body:$.body,runId:$.runId,threadId:$.threadId,toolCallId:$.toolCallId,step:$.step,depth:$.depth,signal:$.signal}}async function Q3($,Z,z){try{return await $.tool.approvalPredicate(Z,z)!==!1}catch(G){return console.error(`[gemi/mcp] The requiresApproval of "${$.descriptor.name}" threw, so the call asks the user:`,G),!0}}function O2($){if($?.kind==="local"&&$.req)return;if($?.kind==="remote"&&$.req&&$.principal?.user&&typeof $.principal.id==="string"&&Array.isArray($.principal.scopes))return;throw Error('McpRegistry: a caller is { kind: "local", req } or { kind: "remote", req, principal }, with the principal a caller resolver verified.')}function U3($,Z){if(Z?.names&&!Z.names.includes($.name))return!1;if(Z?.tags&&!$.tags.some((z)=>Z.tags.includes(z)))return!1;return!0}var p$=10485760;function i$($){let Z=$?.maxBytes??p$;if(!Number.isSafeInteger(Z)||Z<=0)throw Error("McpRegistry: files.maxBytes must be a positive whole number of bytes.");let z=$?.fetchUrls===!0?{}:typeof $?.fetchUrls==="object"&&$.fetchUrls!==null?$.fetchUrls:null;return{maxBytes:Z,fetch:z}}function l$($){if($.length===0||$.length>255)return!1;for(let Z of $){let z=Z.codePointAt(0);if(z<32||z===127||Z==="/"||Z==="\\")return!1}return!0}var n$=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}(\s*;.{0,200})?$/,s$=/^[A-Za-z0-9+/]*={0,2}$/;function t$($){return $.endsWith("==")?2:$.endsWith("=")?1:0}function V3($,Z,z){if(z!=="input"&&typeof z!=="function")throw Error(`${$}: ${Z} must be a function or "input".`)}function H3($){return $ instanceof Object&&$.__internal_brand==="McpModelParam"}function o$($,Z,z){if(z.as!==void 0&&(typeof z.as!=="string"||z.as===""))throw Error(`${$}: ${Z}.as must be a non-empty string.`);let G=z.input;if(typeof G?.safeParse!=="function"||typeof G.toJSONSchema!=="function")throw Error(`${$}: ${Z}.input must be a schema, built with s.`);if(typeof z.bind!=="function")throw Error(`${$}: ${Z}.bind must be a function.`)}var a$=new Set(["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"]);function r$($){switch($){case"GET":return{readOnlyHint:!0};case"DELETE":return{destructiveHint:!0};case"PUT":return{idempotentHint:!0};default:return{}}}function J3($,Z,z){if(z!==void 0&&(typeof z!=="object"||z===null))throw Error(`${$}: annotations must be an object of hints.`);let G=Z?r$(Z):{};for(let[W,X]of Object.entries(z??{})){if(!a$.has(W))throw Error(`${$}: "${W}" is not a tool annotation. Use readOnlyHint, destructiveHint, idempotentHint or openWorldHint.`);if(X===void 0)continue;if(typeof X!=="boolean")throw Error(`${$}: annotations.${W} must be true or false.`);G[W]=X}if(G.readOnlyHint===!0&&(G.destructiveHint||G.idempotentHint))throw Error(`${$} is read-only${z?.readOnlyHint?"":` (a ${Z})`} and also ${G.destructiveHint?"destructive":"idempotent"}, which only a tool that is not read-only can be. Set readOnlyHint: false if it changes something.`);return Object.freeze(G)}function F3($,Z,z,G={}){let W=z.toJSONSchema(),X=Object.fromEntries(Object.entries(G).map(([Q,U])=>[Q,U.toJSONSchema()])),Y={...Z??{},type:"object",properties:{...Z?.properties??{},...W.properties,...X},required:[...Z?.required??[],...W.required??[],...Object.keys(G)],additionalProperties:!1},K=(Q)=>{if(typeof Q!=="object"||Q===null||Array.isArray(Q))return{ok:!1,errors:["expected an object"]};let U=[],V={};if($){let F=$.safeParse(Q);if(F.ok===!1)U.push(...F.errors);else V={...F.value}}let H=z.safeParse(Q);if(H.ok===!1)U.push(...H.errors);else V={...V,...H.value};for(let[F,P]of Object.entries(G)){let I=Q[F];if(I===void 0){U.push(`"${F}" is required`);continue}let J=P.safeParse(I);if(J.ok===!1)U.push(...J.errors.map((D)=>`${F}: ${D}`));else V[F]=J.value}return U.length>0?{ok:!1,errors:U}:{ok:!0,value:V}};return{toJSONSchema:()=>Y,safeParse:K,parse(Q){let U=K(Q);if(U.ok===!1)throw Error(U.errors.join(", "));return U.value}}}function e$($,Z){return Object.fromEntries(Object.entries($).filter(([z])=>!Z.includes(z)))}function $8($,Z,z){let G=Z.modifier==="*"||Z.modifier==="+"?z.split("/"):[z];if(G.some((W)=>W==="."||W===".."))throw new O(`"${z}" is not a valid value for "${Z.name}" of "${$}".`);return G.map(encodeURIComponent).join("/")}function j2($,Z,z){if(z===void 0||z===null)return;if(Array.isArray(z)){for(let G of z)j2($,Z,G);return}$.append(Z,typeof z==="object"?JSON.stringify(z):String(z))}function Z8($){let Z=new URLSearchParams,z=(G,W)=>{if(W===void 0||W===null)return;if(Array.isArray(W)){for(let X of W)z(G,X);return}Z.append(G,typeof W==="object"?JSON.stringify(W):String(W))};for(let[G,W]of Object.entries($))z(G,W);return Z.toString()}async function N3($,Z){if(Z.status>=200&&Z.status<300){let G=Z.headers.get("Content-Type");if(G&&!m$.test(G)){let X=(await Z.arrayBuffer()).byteLength;return`"${$}" answered with ${X} bytes of ${G}, which is not shown.`}let W=await Z.text();if(W==="")return null;if(W.length>E)return`${W.slice(0,E)}\u2026 [cut at ${E} of ${W.length} characters]`;try{return JSON.parse(W)}catch{return W}}let z=await Z.text();if(Z.status>=400&&Z.status<500){let G=z.length>W3?`${z.slice(0,W3)}\u2026`:z;throw new O(`"${$}" was refused with ${Z.status}${G?`: ${G}`:"."}`,Z.status)}if(Z.status<500)console.error(`[gemi/mcp] "${$}" answered ${Z.status}${Z.headers.get("Location")?` to ${Z.headers.get("Location")}`:""}, which a tool call cannot follow.`);throw new O(`"${$}" failed on the server.`,Z.status)}import{createHash as z8,randomBytes as G8,timingSafeEqual as W8}from"crypto";function D2($){let Z=$.headers.get("authorization");if(!Z)return null;let z=/^Bearer[ ]+([\x21-\x7e]+)$/i.exec(Z.trim());return z?z[1]:null}class X8{options;name="api-key";constructor($){this.options=$;if(typeof $?.prefix!=="string"||!/^[A-Za-z0-9_-]{3,32}$/.test($.prefix))throw Error('McpApiKeyResolver: prefix is required: 3 to 32 letters, digits, _ or -, like "myapp_mcp_".');if(typeof $.verify!=="function")throw Error("McpApiKeyResolver: verify must be a function that looks a key up.")}static generate($){return`${$}${G8(32).toString("base64url")}`}static hash($){return z8("sha256").update($).digest("hex")}static hashesMatch($,Z){let z=Buffer.from($),G=Buffer.from(Z);return z.length===G.length&&W8(z,G)}async resolve($){let Z=D2($);if(!Z?.startsWith(this.options.prefix))return null;let z=await this.options.verify(Z,$);if(!z)return{ok:!1,error:"invalid_token",description:"The API key is not valid."};if(!z.user||typeof z.id!=="string"||z.id===""||!Array.isArray(z.scopes))throw Error("McpApiKeyResolver: verify must answer { user, id, scopes } for a key it knows, or null.");return{ok:!0,principal:{user:z.user,via:this.name,id:z.id,scopes:[...z.scopes]}}}}import{createHash as v3,randomBytes as C3}from"crypto";async function x2($,Z){let z=Y8();if(!z)return null;let G=await z.consume($,Z);return G.allowed?null:Math.max(1,Math.ceil(G.retryAfter/1000))}function Y8(){try{let $=k();return $.bound(t)?$.make(t):null}catch{return null}}var A2=["2026-07-28"],U2=["2025-11-25","2025-06-18","2025-03-26"],C2=[...A2,...U2],S2="io.modelcontextprotocol/protocolVersion",q2="io.modelcontextprotocol/clientCapabilities";var T2="io.modelcontextprotocol/serverInfo",L={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022};class _ extends Error{code;data;status;constructor($,Z,z,G=200){super(Z);this.code=$;this.data=z;this.status=G;this.name="JsonRpcError"}}function b($,Z){return{jsonrpc:"2.0",id:$,error:{code:Z.code,message:Z.message,...Z.data!==void 0?{data:Z.data}:{}}}}function D3($){if(Array.isArray($))throw new _(L.InvalidRequest,"Batched requests are not supported.",void 0,400);if(typeof $!=="object"||$===null||$.jsonrpc!=="2.0")throw new _(L.InvalidRequest,"Not a JSON-RPC 2.0 message.",void 0,400);let Z=$,z=Z.id,G=typeof z==="string"||typeof z==="number"&&Number.isFinite(z);if(typeof Z.method==="string"){if(Z.params!==void 0&&(typeof Z.params!=="object"||Z.params===null||Array.isArray(Z.params)))throw new _(L.InvalidRequest,"params must be an object.",void 0,400);if(z===void 0)return{kind:"notification",message:Z};if(!G)throw new _(L.InvalidRequest,"id must be a string or a number.",void 0,400);return{kind:"request",message:Z}}if(G&&(("result"in Z)||("error"in Z)))return{kind:"response",message:Z};throw new _(L.InvalidRequest,"Not a JSON-RPC request, notification or response.",void 0,400)}function M2($,Z){let z=$.outputSchema?.toJSONSchema(),G={...$.annotations,...$.title&&!Z?{title:$.title}:{}};return{name:$.name,...$.title?{title:$.title}:{},description:$.description,inputSchema:$.inputSchema.toJSONSchema(),...z&&(Z||z.type==="object")?{outputSchema:z}:{},...Object.keys(G).length>0?{annotations:G}:{}}}function M($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function x3($){let Z=/^=\?base64\?([A-Za-z0-9+/]*={0,2})\?=$/.exec($);if(!Z)return $;try{let z=Buffer.from(Z[1],"base64");return new TextDecoder("utf-8",{fatal:!0}).decode(z)}catch{return null}}import{createHmac as K8,timingSafeEqual as Q8}from"crypto";function k2($,Z,z){let G=Buffer.from(JSON.stringify(z)).toString("base64url");return`${Z}.${G}.${A3($,Z,G).toString("base64url")}`}function R2($,Z,z,G=Date.now()){if(typeof z!=="string"||z.length>8192)return null;let W=z.split(".");if(W.length!==3||W[0]!==Z)return null;let[,X,Y]=W,K=Buffer.from(Y,"base64url"),Q=A3($,Z,X);if(K.length!==Q.length||!Q8(K,Q))return null;let U;try{U=JSON.parse(Buffer.from(X,"base64url").toString("utf8"))}catch{return null}if(typeof U!=="object"||U===null)return null;if(typeof U.exp!=="number"||U.exp<=G)return null;return U}function A3($,Z,z){return K8("sha256",V2($)).update(`${Z}.${z}`).digest()}var E2="gemi.mcp.request-state.v1",S3="gemi.mcp.session.v1",U8=86400000,q3=600000,T3="gemi_approval",b2=2000,V8={limit:600,window:60},H8={limit:30,window:60};class G2{registry;static token="router.mcp.http";endpoint;resolvers;context;allowedOrigins;hosts;rateLimit;maxBodyBytes;serverInfo;instructions;nonces;approvalTimeoutMs;onCall;feature;featureOn;pending=new Map;inflight=new Map;constructor($,Z,z={}){this.registry=$;if(typeof Z.url!=="string")throw Error(`route.mcp.remote.url is required: the endpoint's canonical URL, like "https://example.com/mcp".`);this.endpoint=N8(Z.url);let G=Z.resolvers??[];if(!Array.isArray(G)||G.length===0)throw Error("route.mcp.remote is enabled without a caller resolver. Configure route.mcp.remote.resolvers \u2014 an McpOAuthServer, an McpApiKeyResolver, or your own \u2014 or leave the endpoint off. Without one every request would be refused, or answered as nobody.");for(let W of G)if(typeof W?.resolve!=="function"||typeof W.name!=="string"||W.name==="")throw Error("route.mcp.remote.resolvers: each resolver needs a name and a resolve().");this.resolvers=G,V2(E2),this.context={resource:this.resource,registry:$},this.allowedOrigins=new Set((Z.allowedOrigins??[]).map((W)=>{if(new URL(W).origin!==W)throw Error(`route.mcp.remote.allowedOrigins: "${W}" is not an origin (scheme://host[:port]).`);return W})),this.allowedOrigins.add(this.endpoint.origin),this.hosts=new Set([this.endpoint.host]);for(let W of Z.hosts??[]){let X=null;try{X=typeof W==="string"&&W!==""&&!/[/?#@\\\s]/.test(W)?new URL(`http://${W}`):null}catch{}if(!X)throw Error(`route.mcp.remote.hosts: "${String(W)}" is not a host (host[:port]).`);this.hosts.add(X.host)}if(this.rateLimit=Z.rateLimit===!1?!1:Z.rateLimit??V8,this.maxBodyBytes=Z.maxBodyBytes??Math.ceil($.maxFileBytes*1.4)+1048576,this.serverInfo={name:Z.server?.name??"gemi",version:Z.server?.version??"1.0.0"},this.instructions=Z.server?.instructions,this.nonces=Z.nonces??new f3,this.approvalTimeoutMs=Z.approvalTimeoutMs??q3,Z.onCall!==void 0&&typeof Z.onCall!=="function")throw Error("route.mcp.remote.onCall must be a function.");if(this.onCall=Z.onCall,Z.feature!==void 0){if(typeof Z.feature!=="string"||Z.feature==="")throw Error("route.mcp.remote.feature must be a feature key from app/features.");this.feature=Z.feature}this.featureOn=z.featureOn??Q2;for(let W of G)W.boot?.(this.context)}get resource(){return this.endpoint.href.replace(/\/$/,"")}async handle($){let Z=new URL($.url);if(!this.hosts.has(Z.host))return null;if(this.feature!==void 0){if(!this.ownsPath(Z.pathname))return null;if(await this.featureOn(this.feature)!==!0)return null}for(let W of this.resolvers){let X=await W.handle?.($,this.context);if(X)return X}if(Z.pathname!==this.endpoint.pathname)return null;let z=$.headers.get("origin");if(z!==null&&!this.allowedOrigins.has(z))return v(b(null,new _(L.InvalidRequest,"Origin not allowed.")),403);let G=z?F8(z):{};if($.method==="OPTIONS")return new Response(null,{status:204,headers:{...G,"Access-Control-Allow-Methods":"POST","Access-Control-Allow-Headers":"Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Mcp-Method, Mcp-Name, Last-Event-ID","Access-Control-Max-Age":"600"}});if($.method!=="POST")return M3(new Response(null,{status:405,headers:{Allow:"POST, OPTIONS"}}),G);return M3(await this.post($),G)}ownsPath($){let Z=this.endpoint.pathname.replace(/\/$/,"");return $===this.endpoint.pathname||$===Z||$.startsWith(`${Z}/`)||$.startsWith("/.well-known/")}async post($){let Z=null;for(let Y of this.resolvers){let K=await Y.resolve($,this.context);if(K===null)continue;if(K.ok===!1)return await this.failedAttempt($)??this.unauthorized(K.description);Z={...K.principal,via:Y.name};break}if(!Z)return(D2($)!==null?await this.failedAttempt($):null)??this.unauthorized();let z=await this.spend(Z);if(z)return z;let G=$.headers.get("content-type")??"";if(!/^application\/json\s*(;|$)/i.test(G))return new Response("Content-Type must be application/json.",{status:415});let W;try{W=JSON.parse(await J8($,this.maxBodyBytes))}catch(Y){if(Y instanceof J2)return v(b(null,new _(L.InvalidRequest,`The request is larger than ${this.maxBodyBytes} bytes.`)),413);return v(b(null,new _(L.ParseError,"Parse error.")),400)}let X=new d($,{},"api",this.endpoint.pathname);return await u.run(X,async()=>{try{return await this.dispatch($,X,Z,W)}catch(Y){if(Y instanceof _){let K=M(W)&&(typeof W.id==="string"||typeof W.id==="number")?W.id:null;return v(b(K,Y),Y.status)}return console.error("[gemi/mcp] The MCP endpoint failed:",Y),v(b(null,new _(L.InternalError,"Internal error.")),500)}},{user:Z.user})}async dispatch($,Z,z,G){let W=D3(G),X={kind:"remote",req:Z,principal:z};if(W.kind==="response"){let I=this.session($,z),J=this.pending.get(String(W.message.id));if(J&&J.session===I.id)this.pending.delete(String(W.message.id)),J.resolve(W.message);return new Response(null,{status:202})}let{message:Y}=W,K=Y.params??{},Q=M(K._meta)?K._meta:{};if(typeof Q[S2]==="string"){if(this.checkModernHeaders($,Y,Q[S2]),W.kind==="notification")return new Response(null,{status:202});return await this.respond(Y,async(I,J)=>this.modern({principal:z,caller:X,message:Y,params:K,era:{modern:!0},stream:I,signal:J}),R3(K),$.signal)}if(Y.method==="initialize"){if(W.kind!=="request")throw new _(L.InvalidRequest,"initialize is a request.",void 0,400);return this.initialize(W.message,K,z)}let U=this.session($,z),V=$.headers.get("mcp-protocol-version");if(V!==null&&V!==U.state.v)throw new _(L.InvalidRequest,`MCP-Protocol-Version ${V} is not the session's ${U.state.v}.`,void 0,400);if(W.kind==="notification"){if(Y.method==="notifications/cancelled"){let I=K.requestId;this.inflight.get(`${U.id}:${String(I)}`)?.abort()}return new Response(null,{status:202})}let H=`${U.id}:${String(Y.id)}`,F=new AbortController;this.inflight.set(H,F);let P=AbortSignal.any([F.signal,$.signal]);try{return await this.respond(Y,async(I,J)=>this.legacy({principal:z,caller:X,message:Y,params:K,era:{modern:!1,session:U.state,sessionId:U.id},stream:I,signal:J}),R3(K)||I8(this.registry,Y,U.state),P,()=>this.inflight.delete(H))}catch(I){throw this.inflight.delete(H),I}}async modern($){switch($.message.method){case"server/discover":return this.complete({supportedVersions:C2,capabilities:{tools:{}},...this.instructions?{instructions:this.instructions}:{},ttlMs:60000,cacheScope:"private"});case"tools/list":return this.complete({tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!0)),ttlMs:60000,cacheScope:"private"});case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`,void 0,404)}}async legacy($){switch($.message.method){case"ping":return{};case"tools/list":return{tools:(await this.registry.available($.caller)).map((Z)=>M2(Z,!1))};case"tools/call":return await this.callTool($);default:throw new _(L.MethodNotFound,`Method not found: ${$.message.method}`)}}complete($){return{resultType:"complete",...$,_meta:{[T2]:this.serverInfo}}}initialize($,Z,z){let G=Z.protocolVersion,W=U2.includes(G)?G:U2[0],X=M(Z.capabilities)?Z.capabilities:{},Y={v:W,e:k3(X.elicitation),p:H2(z),exp:Date.now()+U8},K=k2(S3,"gms1",Y);return v({jsonrpc:"2.0",id:$.id,result:{protocolVersion:W,capabilities:{tools:{listChanged:!1}},serverInfo:this.serverInfo,...this.instructions?{instructions:this.instructions}:{}}},200,{"Mcp-Session-Id":K})}session($,Z){let z=$.headers.get("mcp-session-id");if(!z)throw new _(L.InvalidRequest,"Missing Mcp-Session-Id. Send initialize first, or a request carrying io.modelcontextprotocol/protocolVersion in _meta.",void 0,400);let G=R2(S3,"gms1",z);if(!G||G.p!==H2(Z))throw new _(L.InvalidRequest,"Session not found.",void 0,404);return{id:z,state:G}}checkModernHeaders($,Z,z){if(!A2.includes(z))throw new _(L.UnsupportedProtocolVersion,"Unsupported protocol version",{supported:C2,requested:z},400);let G=(Y)=>new _(L.HeaderMismatch,`Header mismatch: ${Y}`,void 0,400);if($.headers.get("mcp-protocol-version")!==z)throw G("MCP-Protocol-Version does not match the protocol version in _meta.");if($.headers.get("mcp-method")!==Z.method)throw G("Mcp-Method does not match the method.");let W=Z.params??{},X=Z.method==="tools/call"||Z.method==="prompts/get"?W.name:Z.method==="resources/read"?W.uri:void 0;if(X!==void 0){let Y=$.headers.get("mcp-name");if(Y===null||x3(Y)!==X)throw G("Mcp-Name does not match the request's name.")}}async callTool($){let Z=$.params.name;if(typeof Z!=="string")throw new _(L.InvalidParams,"tools/call needs a tool name.");let z=$.params.arguments??{};if(!this.onCall)return await this.runTool($,Z,z,{approved:!1});let G=performance.now(),W={approved:!1};try{let X=await this.runTool($,Z,z,W);if(!W.pending)await this.report($,Z,z,W,G);return X}catch(X){if(!W.outcome){if(W.outcome="error",W.message=X instanceof _?X.message:"Internal error.",!(X instanceof _))W.error=X}throw await this.report($,Z,z,W,G),X}}async report($,Z,z,G,W){let{principal:X}=$;try{await this.onCall({user:X.user,via:X.via,credentialId:X.id,clientId:X.clientId??null,scopes:X.scopes,tool:Z,arguments:z,outcome:G.outcome??"ok",...G.reason!==void 0?{reason:G.reason}:{},...G.message!==void 0?{message:G.message}:{},...G.status!==void 0?{status:G.status}:{},...G.error!==void 0?{error:G.error}:{},approved:G.approved,durationMs:Math.round((performance.now()-W)*1000)/1000,req:$.caller.req})}catch(Y){console.error(`[gemi/mcp] route.mcp.remote.onCall failed for "${Z}":`,Y)}}async runTool($,Z,z,G){let{caller:W,principal:X}=$,Y=(J,D)=>{G.outcome="denied",G.reason=J,G.message=D},K=(J,D,j)=>{if(G.outcome="error",G.message=J,D!==void 0)G.status=D;if(j!==void 0)G.error=j},Q=(await this.registry.available(W,{names:[Z]}))[0];if(!Q)throw Y("unknown-tool",`Unknown tool: ${Z}`),new _(L.InvalidParams,`Unknown tool: ${Z}`);if(Q.requiresApproval){let J=Q.inputSchema.safeParse(z);if(J.ok===!1){let j=`Invalid arguments for "${Z}": ${J.errors.join(", ")}`;return K(j),this.toolResult($,{content:[{type:"text",text:j}],isError:!0})}if($.era.modern&&M($.params.inputResponses)&&$.params.requestState!==void 0||await this.registry.approvalRequired(W,Z,z,{signal:$.signal})){let j=await this.approval($,Q,z,Y,G);if(j.kind==="answer")return j.result;G.approved=!0}}let U=P8($),V=[],H;try{H=await this.registry.execute(W,Z,z,void 0,{approved:G.approved,signal:$.signal,images:(J)=>V.push(J),...U?{progress:U}:{}})}catch(J){if(J instanceof O){if(J.status===401||J.status===403)Y("forbidden",J.message),G.status=J.status;else K(J.message,J.status);return this.toolResult($,{content:[{type:"text",text:J.message}],isError:!0})}if(J instanceof m){let j=J.reason==="unknown-tool"?`Unknown tool: ${Z}`:J.message;throw Y(J.reason,j),new _(L.InvalidParams,j)}console.error(`[gemi/mcp] "${Z}" failed for ${X.via}:${X.id}:`,J);let D=`"${Z}" failed on the server.`;return K(D,void 0,J),this.toolResult($,{content:[{type:"text",text:D}],isError:!0})}let F=typeof H==="string"?H:JSON.stringify(H??null),P=Q.outputSchema&&($.era.modern||M(H))?{structuredContent:H}:{},I=[...V.length>0&&H===null?[]:[{type:"text",text:F}],...V];return G.outcome="ok",this.toolResult($,{content:I,...P,isError:!1})}toolResult($,Z){return $.era.modern?this.complete(Z):Z}async approval($,Z,z,G,W){let X=_8(Z,z),Y=(F,P="approval-declined")=>{return G(P,F),{kind:"answer",result:this.toolResult($,{content:[{type:"text",text:F}],isError:!0})}},K=(F,P)=>{return G(F,P.message),P};if($.era.modern){let F=M($.params._meta)?$.params._meta:{},P=M(F[q2])?F[q2]:{},I=M($.params.inputResponses)?$.params.inputResponses:null,J=$.params.requestState,D=B8(z);if(I&&J!==void 0){let T=R2(E2,"grs1",J);if(!T||T.p!==H2($.principal)||T.t!==Z.name||T.a!==D)throw K("approval-invalid",new _(L.InvalidParams,"requestState is not valid for this call."));if(!await this.spendNonce(T.n,T.exp))throw K("approval-replayed",new _(L.InvalidParams,"requestState has already been used."));return E3(I[T3])?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}if(!k3(P.elicitation))throw K("approval-unavailable",new _(L.MissingRequiredClientCapability,`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation).`,{requiredCapabilities:{elicitation:{form:{}}}},400));let j={p:H2($.principal),t:Z.name,a:D,n:C3(16).toString("base64url"),exp:Date.now()+q3};return W.pending=!0,{kind:"answer",result:{resultType:"input_required",inputRequests:{[T3]:{method:"elicitation/create",params:{mode:"form",...X}}},requestState:k2(E2,"grs1",j),_meta:{[T2]:this.serverInfo}}}}let Q=$.era;if(!Q.session.e||!$.stream)return Y(`"${Z.name}" needs the user's approval, and this client cannot ask for it (elicitation). It did not run.`,"approval-unavailable");let U=`gemi-approval-${C3(12).toString("base64url")}`,V=Q.sessionId,H=await new Promise((F)=>{let P=setTimeout(()=>{this.pending.delete(U),F(null)},this.approvalTimeoutMs),I=(J)=>{clearTimeout(P),F(J)};this.pending.set(U,{session:V,resolve:I}),$.signal.addEventListener("abort",()=>{this.pending.delete(U),I(null)}),$.stream.send({jsonrpc:"2.0",id:U,method:"elicitation/create",params:Q.session.v==="2025-11-25"?{mode:"form",...X}:X})});return H&&!H.error&&E3(H.result)?{kind:"approved"}:Y(`The user did not approve "${Z.name}", and it did not run.`)}async spendNonce($,Z){try{return await this.nonces.consume($,Z)}catch(z){return console.error("[gemi/mcp] Spending an approval failed:",z),!1}}async respond($,Z,z,G,W){if(!z)try{let Q=await Z(null,G);return v({jsonrpc:"2.0",id:$.id,result:Q},200)}finally{W?.()}let X=new AbortController,Y=AbortSignal.any([X.signal,G]),K=new g3(()=>X.abort());return(async()=>{try{let Q=await Z(K,Y);K.send({jsonrpc:"2.0",id:$.id,result:Q})}catch(Q){if(Q instanceof _)K.send(b($.id,Q));else console.error("[gemi/mcp] The MCP endpoint failed:",Q),K.send(b($.id,new _(L.InternalError,"Internal error.")))}finally{W?.(),K.close()}})(),new Response(K.readable,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}unauthorized($){let Z=this.resolvers.map((G)=>G.challenge?.(this.context)).find(Boolean)??'Bearer realm="mcp"',z=$?`${Z}, error="invalid_token", error_description="${$.replace(/["\\]/g,"")}"`:Z;return v(b(null,new _(L.InvalidRequest,"Unauthorized.")),401,{"WWW-Authenticate":z})}async failedAttempt($){let Z=y3(new d($,{},"api",this.endpoint.pathname)),z=await x2(`mcp-auth-failed:${Z}`,H8);return z===null?null:b3(z)}async spend($){if(!this.rateLimit)return null;let Z=await x2(`mcp-endpoint:${$.via}:${$.id}`,this.rateLimit);return Z===null?null:b3(Z)}}class g3{readable;controller;closed=!1;encoder=new TextEncoder;constructor($){this.readable=new ReadableStream({start:(Z)=>{this.controller=Z},cancel:()=>{this.closed=!0,$()}})}send($){if(this.closed)return;this.controller.enqueue(this.encoder.encode(`event: message
|
|
3
3
|
data: ${JSON.stringify($)}
|
|
4
4
|
|
|
5
5
|
`))}close(){if(this.closed)return;this.closed=!0,this.controller.close()}}class J2 extends Error{}async function J8($,Z){let z=Number($.headers.get("content-length"));if(Number.isFinite(z)&&z>Z)throw new J2;if(!$.body)return"";let G=$.body.getReader(),W=[],X=0;for(;;){let{done:Y,value:K}=await G.read();if(Y)break;if(X+=K.byteLength,X>Z)throw await G.cancel(),new J2;W.push(K)}return Buffer.concat(W).toString("utf8")}function v($,Z,z={}){return new Response(JSON.stringify($),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",...z}})}function M3($,Z){for(let[z,G]of Object.entries(Z))$.headers.set(z,G);return $}function F8($){return{"Access-Control-Allow-Origin":$,"Access-Control-Expose-Headers":"Mcp-Session-Id, WWW-Authenticate",Vary:"Origin"}}function N8($){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 H2($){return v3("sha256").update(`${$.via}\x00${$.id}\x00${$.user?.id}`).digest("base64url").slice(0,32)}function B8($){return v3("sha256").update(w3($??{})).digest("base64url")}function k3($){if(!M($))return!1;if(Object.keys($).length===0)return!0;return"form"in $}function R3($){let Z=M($._meta)?$._meta:{};return typeof Z.progressToken==="string"||typeof Z.progressToken==="number"}function I8($,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 P8($){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 _8($,Z){let z=JSON.stringify(Z??{},null,1),G=z.length>b2?`${z.slice(0,b2)}\u2026 (${z.length-b2} more characters not shown)`:z;return{message:`Allow "${$.title??$.name}" to run? ${$.description}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as c,Z as P,aa as f,ba as l}from"./chunk-
|
|
2
|
+
import{$ as c,Z as P,aa as f,ba as l}from"./chunk-gjpwvet7.js";import{Ba as u,Ca as m}from"./chunk-rpwvwsq9.js";import"./chunk-v2fd69at.js";import"./chunk-hke4hzfm.js";import"./chunk-0cckwd91.js";import"./chunk-rreb2k19.js";import"./chunk-ba1h9pm6.js";import"./chunk-vvq18rrr.js";import{Hj as S}from"./chunk-2g1h9ktj.js";import{Bm as T}from"./chunk-7fh7cfjh.js";import{Vm as y}from"./chunk-4mysb5ej.js";import"./chunk-c7hbdsjv.js";import{join as YJ}from"path";import{createServer as AJ}from"vite";import{join as R,sep as o}from"path";import{existsSync as a,statSync as s}from"fs";import{IncomingMessage as t,ServerResponse as r}from"http";import{Socket as e}from"net";function i(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
|
|
3
3
|
`).split(`
|
|
4
4
|
`).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
|
|
5
5
|
`).trim()}function N(J){return`
|
package/dist/kernel/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ta as E}from"../chunk-7ycjs0xn.js";import{ob as l}from"../chunk-gxre6wnc.js";import{pb as H}from"../chunk-by0ydsqs.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,dc as b,gc as f,hc as k,ic as m}from"../chunk-
|
|
2
|
+
import{Ta as E}from"../chunk-7ycjs0xn.js";import{ob as l}from"../chunk-gxre6wnc.js";import{pb as H}from"../chunk-by0ydsqs.js";import{$b as I,Cb as g,Db as W,Eb as _,Fb as p,Gb as P,Hb as u,Ib as $,Jb as V,Kb as q,Lb as B,Mb as K,Qb as L,Rb as Q,Sb as T,Wb as U,Xb as y,Yb as F,Zb as C,_b as D,dc as b,gc as f,hc as k,ic as m}from"../chunk-rftxm3ny.js";import"../chunk-58xb0s71.js";import"../chunk-samm4h7d.js";import"../chunk-51mz612v.js";import"../chunk-w9v8bbp8.js";import{Qe as h}from"../chunk-6gek696n.js";import"../chunk-wjjxqw9b.js";import"../chunk-bhycdjcv.js";import{Pf as n,Qf as v,oh as w,sh as A,tf as d,uf as s,wh as R}from"../chunk-q8pr18w6.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import"../chunk-j3zz8046.js";import"../chunk-2g1h9ktj.js";import"../chunk-e4adgvd6.js";import"../chunk-0xmk4jyj.js";import"../chunk-8wvh099n.js";import{hk as M}from"../chunk-4sv5vkab.js";import"../chunk-768yza4f.js";import"../chunk-9a3wbbr6.js";import"../chunk-0wa8ztk5.js";import"../chunk-6wv3k8ap.js";import"../chunk-ccymw1ed.js";import"../chunk-aczp96k5.js";import"../chunk-3qmhe96e.js";import"../chunk-rc86ewq1.js";import"../chunk-x68jra5n.js";import{tm as O,vm as J}from"../chunk-3mq0wmq7.js";import"../chunk-wgb26e02.js";import"../chunk-7fh7cfjh.js";import"../chunk-vqmy8jfr.js";import"../chunk-zsmwmg8x.js";import"../chunk-4mysb5ej.js";import"../chunk-c7hbdsjv.js";var N=[C,I,E,T,L,k,B,Q,D,y,_,U,f,V,F,H,b,K,q,m,$];class S{config={};providers=[];services=[];serviceInstances=[];serviceTokens=new Set;servicesBooted=!1;models=[];app=new J;boot(){if(this.models.length>0)l(...this.models);else a();this.app.config.merge(this.config),J.setInstance(this.app),this.app.registerMany([...N,...this.providers]),this.registerServices()}registerServices(){let j=this.serviceTokens;this.serviceInstances=[],this.serviceTokens=new Set,this.servicesBooted=!1;let X=new Map;for(let z of this.services){let G=typeof z==="function"?new z:z,x=G.constructor;if(!x.token)throw Error(`Service [${x.name}] is listed in \`services\` but does not declare a \`static token\`.`);let Y=X.get(x.token);if(Y)throw Error(`Services [${Y}] and [${x.name}] both declare the token "${x.token}". Tokens are the container's keys, so they must be unique.`);X.set(x.token,x.name);let Z=x;if(!j.has(x.token)&&this.app.bound(Z))throw Error(`Service [${x.name}] declares the token "${x.token}", which is already bound in the container by the framework or a provider. Binding it would replace that service everywhere, so pick a token nothing else owns.`);this.app.instance(Z,G),this.serviceInstances.push(G),this.serviceTokens.add(x.token)}this.app.setShutdownHooks(this.serviceInstances.map((z)=>({name:`${z.constructor.name}.onShutdown`,shutdown:(G)=>z.onShutdown(G)})))}async waitForBoot(){await this.app.boot(),await this.bootServices(),p(this.app)}async bootServices(){if(this.servicesBooted)return;for(let j of this.serviceInstances)await j.boot();this.servicesBooted=!0}shutdown(j){return this.run(()=>this.app.shutdown(j))}run(j){return O.run(this.app,j)}resolve(j){return this.app.make(j)}apiRoutes(){return this.app.make(A)}viewRoutes(){return this.app.make(w)}domains(){return this.app.make(R)}queue(){return this.app.make(h)}mcpHttp(){return this.app.config.get("route.mcp.remote.enabled")===!0?this.app.make(g):null}sockets(){return this.app.config.get("route.channels")?this.app.make(u):null}globalMiddleware(j){return P(j)}destroy(){if(this.app.resolved(W))this.app.make(W).stop();if(this.app.flush(),J.getInstance()===this.app)J.setInstance(void 0);O.disable()}}function a(){if(Bun.env.NODE_ENV==="production")return;let j=M();if(j.length===0)return;console.warn(`[gemi] ${j.length} model${j.length===1?" is":"s are"} registered, but Kernel.models is empty.
|
|
3
3
|
Nested relation reads resolve a model by name, so a policy on a subclass that does not own its
|
|
4
4
|
`+" name is skipped inside every include \u2014 scoped at the root, "+`unscoped in an include, with nothing
|
|
5
5
|
to notice it. Declaring the modules registers each class under its own name and audits the set:
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-vvq18rrr.js";import{Fm as Q,Hm as q,Im as w,Lm as Z,Mm as P,Nm as y,Om as S,Pm as U}from"../chunk-vqmy8jfr.js";import{Tm as H}from"../chunk-zsmwmg8x.js";import"../chunk-4mysb5ej.js";import{$m as F}from"../chunk-c7hbdsjv.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-
|
|
2
|
+
import{Ra as f}from"../chunk-ba1h9pm6.js";import{Sa as A}from"../chunk-vvq18rrr.js";import{Fm as Q,Hm as q,Im as w,Lm as Z,Mm as P,Nm as y,Om as S,Pm as U}from"../chunk-vqmy8jfr.js";import{Tm as H}from"../chunk-zsmwmg8x.js";import"../chunk-4mysb5ej.js";import{$m as F}from"../chunk-c7hbdsjv.js";var x="/__gemi__/health",$=Symbol.for("gemi.server.health");function V(){let z=globalThis;return z[$]??={lagMs:0,consecutiveBreaches:0,degraded:!1,timer:void 0},z[$]}function W(){let z=V(),B=Q();return{healthy:!B&&!z.degraded,shuttingDown:B,lagMs:z.lagMs,consecutiveBreaches:z.consecutiveBreaches}}function E(z,B){let I=V();I.lagMs=z,I.consecutiveBreaches=z>B.maxLagMs?I.consecutiveBreaches+1:0;let J=I.consecutiveBreaches>=B.breaches;if(J&&!I.degraded)console.warn(`[gemi] Health: degraded (event-loop lag ${Math.round(z)}ms, ${I.consecutiveBreaches} samples in a row over ${B.maxLagMs}ms).`);else if(!J&&I.degraded)console.log(`[gemi] Health: recovered (event-loop lag ${Math.round(z)}ms).`);I.degraded=J}function G(z){let B=V();if(B.timer)return;let I=performance.now()+z.intervalMs;B.timer=setInterval(()=>{let J=performance.now();E(Math.max(0,J-I),z),I=J+z.intervalMs},z.intervalMs),B.timer.unref?.()}function _(z=process.env){return{paths:D(z.GEMI_HEALTH_PATH),intervalMs:O("GEMI_HEALTH_INTERVAL_MS",z.GEMI_HEALTH_INTERVAL_MS,500),maxLagMs:O("GEMI_HEALTH_MAX_LAG_MS",z.GEMI_HEALTH_MAX_LAG_MS,1000),breaches:Math.ceil(O("GEMI_HEALTH_BREACHES",z.GEMI_HEALTH_BREACHES,3))}}function D(z){if(z===void 0||z.trim()==="")return[x];if(z.trim().toLowerCase()==="off")return[];let B=z.split(",").map((J)=>J.trim()).filter(Boolean);if(B.filter((J)=>!J.startsWith("/")).length>0)throw Error(`GEMI_HEALTH_PATH: expected comma-separated paths starting with "/", or "off"; got ${JSON.stringify(z)}.`);return B}function O(z,B,I){if(B===void 0||B.trim()==="")return I;let J=Number(B);if(Number.isFinite(J)&&J>0)return J;return console.warn(`[gemi] Ignoring ${z}="${B}": expected a positive number.`),I}function j(z,B){if(B.length===0)return z;let I=new Set(B);return async(J,K)=>{if(!B.some((b)=>J.url.includes(b))||!I.has(new URL(J.url).pathname))return z(J,K);return y(R(J.method))}}function R(z){let B={"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"};if(z!=="GET"&&z!=="HEAD")return new Response("Method Not Allowed",{status:405,headers:{...B,Allow:"GET, HEAD"}});let{healthy:I,shuttingDown:J}=W();return new Response(z==="HEAD"?null:I?"ok":J?"shutting down":"degraded",{status:I?200:503,headers:B})}var L=Symbol.for("gemi.server.devGeneration"),X={graceMs:1e4,providerTimeoutMs:5000};class Y{app;inFlight=0;waiters=new Set;constructor(z){this.app=z}track(z){return async(B,I)=>{this.inFlight++;try{return await z(B,I)}finally{if(this.inFlight--,this.inFlight===0)this.wake()}}}get pending(){return this.inFlight}async retire({graceMs:z,providerTimeoutMs:B}){try{await this.idle(z),await Promise.resolve().then(()=>this.app.shutdown({timeoutMs:B}))}catch(I){C(I)}}idle(z){if(this.inFlight===0)return Promise.resolve();return new Promise((B)=>{let I=()=>{clearTimeout(J),this.waiters.delete(I),B()},J=setTimeout(I,z);this.waiters.add(I)})}wake(){for(let z of this.waiters)z()}}function N(z,B=X){let I=globalThis,J=I[L];if(I[L]=z,!J||J===z||typeof J.retire!=="function")return Promise.resolve();let K=J.retire.bind(J);return Promise.resolve().then(()=>K(B)).catch(C)}function C(z){console.error("[gemi] Shutting down the application a reload replaced failed:",z)}class k{app;instrumentation;handleSignals;server;stopping;settings;constructor(z){this.app=new A({kernel:z.kernel}),this.handleSignals=z.handleSignals??!0,this.instrumentation=S(z.instrumentation??((B,I)=>I(B)))}async start(){process.env.ROOT_DIR=H();let z=Bun.env.NODE_ENV==="production",B=_();if(z)G(B);let I=j(this.instrumentation,B.paths);if(z){if(this.handleSignals)U(()=>this.stop());this.settings=Z()}try{await this.app.waitForBoot()}catch(J){if(!z)this.app.shutdown({timeoutMs:X.providerTimeoutMs});throw J}if(z){let{httpProd:J}=await import("../chunk-7azdbwdc.js");this.server=await J(this.app,I)}else{f();let{httpDev:J}=await import("../chunk-wefcda84.js"),K=new Y(this.app);this.server=await J(this.app,K.track(I)),N(K)}return this.server}stop(z={}){let B=this.app.sockets();return this.stopping??=P({server:this.server,closeSockets:B?()=>B.shutdown():void 0,shutdownProviders:(I)=>this.app.shutdown(I),settings:{...this.settings??Z(),...z}}),this.stopping}}export{q as shutdownSignal,W as liveness,Q as isShuttingDown,w as holdShutdown,k as Server};
|
|
3
3
|
|
|
4
4
|
//# debugId=FB8C958ED0D5DD0364756E2164756E21
|
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,ic as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-pkew0k7c.js";import{lc as d4}from"../chunk-mmc5bbf4.js";import"../chunk-samm4h7d.js";import{he as D9,ie as H9,je as N9,ke as U9,le as x9,me as R9,ne as O9,oe as _9,pe as V9,qe as k9,re as C9,se as T9,te as P9,ue as b9,ve as w9,we as q9}from"../chunk-51mz612v.js";import{xe as S9}from"../chunk-w9v8bbp8.js";import{Ae as pZ,Be as dZ,Ce as lZ,De as nZ,Ee as iZ,Fe as sZ,Ge as oZ,He as aZ,Ie as tZ,Je as rZ,Ke as eZ,Le as W9,Me as Z9,Ne as $9,Oe as Q9,Pe as Y9,Qe as K9,Ve as J9,ye as cZ,ze as uZ}from"../chunk-6gek696n.js";import{We as h9,Xe as E9}from"../chunk-wjjxqw9b.js";import"../chunk-bhycdjcv.js";import{$g as TZ,Af as Y8,Ag as GZ,Bf as K8,Cf as J8,Cg as XZ,Df as z8,Dg as BZ,Ef as G8,Eg as jZ,Ff as X8,Fg as MZ,Gf as B8,Gg as FZ,Hf as j8,Hg as LZ,If as Y6,Ig as DZ,Ih as yZ,Jf as M8,Jg as HZ,Jh as AZ,Kf as F8,Kg as NZ,Lf as L8,Lg as UZ,Mf as D8,Nf as H8,Qg as R,Rg as i,Sg as xZ,Tg as SZ,Ug as RZ,Vg as OZ,Wg as _Z,Yg as VZ,Zg as kZ,_g as CZ,ag as T8,bg as P8,bh as PZ,cg as b8,df as V6,dg as w8,ef as e5,eg as q8,eh as bZ,ff as W8,fg as v8,fh as wZ,gf as Z8,gh as qZ,if as $8,jh as vZ,mg as e8,ng as q6,of as k6,og as WZ,oh as IZ,pf as C4,qf as B6,rf as T4,sf as P4,sg as ZZ,sh as fZ,tg as $Z,ug as YZ,wf as f6,wh as i4,xf as y6,xg as KZ,xh as z1,yg as JZ,zf as Q8,zg as zZ}from"../chunk-q8pr18w6.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{$i as Y1,Aj as _8,Bi as k4,Ci as O4,Cj as d1,Di as k1,Vi as h4,Zi as j1,cj as _4,dj as C1,ej as p1,fj as N8,gj as U8,hj as x8,ij as S8,jj as R8,vj as mW,wj as cW,zj as O8}from"../chunk-j3zz8046.js";import"../chunk-2g1h9ktj.js";import{Nj as V8,Oj as k8,Pj as C8}from"../chunk-e4adgvd6.js";import{Rj as q}from"../chunk-0xmk4jyj.js";import{$j as U,Zj as g8,_j as m8,ak as c8,bk as b,ck as u8,dk as p8}from"../chunk-8wvh099n.js";import{jk as A8,kk as h8,lk as E8}from"../chunk-4sv5vkab.js";import"../chunk-768yza4f.js";import{Uk as QZ}from"../chunk-9a3wbbr6.js";import{$k as n8,Wk as I8,Xk as f8,Yk as y8,Zk as d8,_k as l8,al as i8,bl as s8,cl as o8,hl as a8,il as t8,jl as r8}from"../chunk-0wa8ztk5.js";import"../chunk-6wv3k8ap.js";import"../chunk-ccymw1ed.js";import"../chunk-aczp96k5.js";import"../chunk-3qmhe96e.js";import{hm as w4,im as hZ,jm as EZ,km as gZ,mm as mZ}from"../chunk-rc86ewq1.js";import"../chunk-x68jra5n.js";import{wm as C}from"../chunk-3mq0wmq7.js";import"../chunk-wgb26e02.js";import"../chunk-7fh7cfjh.js";import"../chunk-vqmy8jfr.js";import"../chunk-zsmwmg8x.js";import"../chunk-4mysb5ej.js";import{$m as u1}from"../chunk-c7hbdsjv.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-qb8pjdez.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
2
|
+
import{rb as z$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,ic as J$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-rftxm3ny.js";import{lc as d4}from"../chunk-58xb0s71.js";import"../chunk-samm4h7d.js";import{he as D9,ie as H9,je as N9,ke as U9,le as x9,me as R9,ne as O9,oe as _9,pe as V9,qe as k9,re as C9,se as T9,te as P9,ue as b9,ve as w9,we as q9}from"../chunk-51mz612v.js";import{xe as S9}from"../chunk-w9v8bbp8.js";import{Ae as pZ,Be as dZ,Ce as lZ,De as nZ,Ee as iZ,Fe as sZ,Ge as oZ,He as aZ,Ie as tZ,Je as rZ,Ke as eZ,Le as W9,Me as Z9,Ne as $9,Oe as Q9,Pe as Y9,Qe as K9,Ve as J9,ye as cZ,ze as uZ}from"../chunk-6gek696n.js";import{We as h9,Xe as E9}from"../chunk-wjjxqw9b.js";import"../chunk-bhycdjcv.js";import{$g as TZ,Af as Y8,Ag as GZ,Bf as K8,Cf as J8,Cg as XZ,Df as z8,Dg as BZ,Ef as G8,Eg as jZ,Ff as X8,Fg as MZ,Gf as B8,Gg as FZ,Hf as j8,Hg as LZ,If as Y6,Ig as DZ,Ih as yZ,Jf as M8,Jg as HZ,Jh as AZ,Kf as F8,Kg as NZ,Lf as L8,Lg as UZ,Mf as D8,Nf as H8,Qg as R,Rg as i,Sg as xZ,Tg as SZ,Ug as RZ,Vg as OZ,Wg as _Z,Yg as VZ,Zg as kZ,_g as CZ,ag as T8,bg as P8,bh as PZ,cg as b8,df as V6,dg as w8,ef as e5,eg as q8,eh as bZ,ff as W8,fg as v8,fh as wZ,gf as Z8,gh as qZ,if as $8,jh as vZ,mg as e8,ng as q6,of as k6,og as WZ,oh as IZ,pf as C4,qf as B6,rf as T4,sf as P4,sg as ZZ,sh as fZ,tg as $Z,ug as YZ,wf as f6,wh as i4,xf as y6,xg as KZ,xh as z1,yg as JZ,zf as Q8,zg as zZ}from"../chunk-q8pr18w6.js";import"../chunk-vcmwp7pv.js";import"../chunk-c3c37k46.js";import{$i as Y1,Aj as _8,Bi as k4,Ci as O4,Cj as d1,Di as k1,Vi as h4,Zi as j1,cj as _4,dj as C1,ej as p1,fj as N8,gj as U8,hj as x8,ij as S8,jj as R8,vj as mW,wj as cW,zj as O8}from"../chunk-j3zz8046.js";import"../chunk-2g1h9ktj.js";import{Nj as V8,Oj as k8,Pj as C8}from"../chunk-e4adgvd6.js";import{Rj as q}from"../chunk-0xmk4jyj.js";import{$j as U,Zj as g8,_j as m8,ak as c8,bk as b,ck as u8,dk as p8}from"../chunk-8wvh099n.js";import{jk as A8,kk as h8,lk as E8}from"../chunk-4sv5vkab.js";import"../chunk-768yza4f.js";import{Uk as QZ}from"../chunk-9a3wbbr6.js";import{$k as n8,Wk as I8,Xk as f8,Yk as y8,Zk as d8,_k as l8,al as i8,bl as s8,cl as o8,hl as a8,il as t8,jl as r8}from"../chunk-0wa8ztk5.js";import"../chunk-6wv3k8ap.js";import"../chunk-ccymw1ed.js";import"../chunk-aczp96k5.js";import"../chunk-3qmhe96e.js";import{hm as w4,im as hZ,jm as EZ,km as gZ,mm as mZ}from"../chunk-rc86ewq1.js";import"../chunk-x68jra5n.js";import{wm as C}from"../chunk-3mq0wmq7.js";import"../chunk-wgb26e02.js";import"../chunk-7fh7cfjh.js";import"../chunk-vqmy8jfr.js";import"../chunk-zsmwmg8x.js";import"../chunk-4mysb5ej.js";import{$m as u1}from"../chunk-c7hbdsjv.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-qb8pjdez.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
package/package.json
CHANGED
package/dist/chunk-m0n0ddd2.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$d as M,Ld as IQ,Td as A,Ud as JQ,Vd as U5,Wd as D5,Xd as RQ,Yd as x5,Zd as f,_d as GQ,td as VQ,vd as g}from"./chunk-samm4h7d.js";import{Ij as B5,Qj as P5}from"./chunk-e4adgvd6.js";var{fetch:i5,WebSocket:n5}=globalThis;function sQ(Q,$){if(typeof Bun>"u")return Q!==$;return typeof Q!=="function"||!/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(Q))}class qQ extends Error{constructor(Q){super(`A model provider tried to call ${r5(Q)} from a test. Tests under vitest do not reach real model providers: give the agent a scripted or fake provider, or set GEMI_AI_LIVE=1 to make real (billed) calls.`);this.name="LiveModelCallRefusedError"}}function aQ(Q=process.env){return!Q.VITEST||Q.GEMI_AI_LIVE==="1"}function oQ(Q){if(aQ()||sQ(globalThis.fetch,i5)||eQ(Q))return;throw new qQ(Q)}function tQ(Q){let $=globalThis.WebSocket;if(aQ()||sQ($,n5)||eQ(Q))return;throw new qQ(Q)}function eQ(Q){let $;try{$=new URL(Q).hostname}catch{return!1}return $==="localhost"||$.endsWith(".localhost")||$==="[::1]"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test($)}function r5(Q){try{return new URL(Q).origin}catch{return"a provider"}}function CQ(Q,$,J){let Z=Q.on;if(Z===void 0)return!0;if(typeof Z!=="function")return Z.includes($.code);try{return Z($,J)===!0}catch{return!1}}var s5=4000,a5=60000;function Q5(Q){if(Q===void 0)return;let $=(J,Z)=>typeof J==="number"&&Number.isFinite(J)&&J>=Z;if(!Q||!$(Q.patienceMs,0)||Q.initialWaitMs!==void 0&&!$(Q.initialWaitMs,1)||Q.maxWaitMs!==void 0&&!$(Q.maxWaitMs,1)||Q.on!==void 0&&typeof Q.on!=="function"&&!(Array.isArray(Q.on)&&Q.on.every((J)=>typeof J==="string")))throw Error(`The provider's retry policy ${JSON.stringify(Q)} is not usable: patienceMs has to be a number of milliseconds (0 or more), initialWaitMs and maxWaitMs above 0, and on a list of error codes or a function.`)}function FQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let V=Q.maxWaitMs??a5,z=Q.initialWaitMs??s5,H=J!==void 0?Math.min(J,V):Math.round(Math.min(V,z*2**$)*(0.5+Y()*0.5));return Math.min(H,G)}var o5=500,$5=20000;function t5(Q,$){if(!Q)return;let J=Q.trim();if(/^\d+(\.\d+)?$/.test(J))return Math.max(0,Number(J)*1000);let Z=Date.parse(J);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function $Q(Q,$){let J=Math.min($5,o5*2**Q);return Math.round(J*(0.5+$()*0.5))}function e5(Q){return Q===429||Q===408||Q===409||Q>=500}function Q6(Q,$){return e5(Q)&&M($).retryable}function J5(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function Z5(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(J5($))},{once:!0})})}async function NQ(Q,$,J=Z5){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(J5($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function m(Q,$,J){if(!J.fetchImpl)oQ(Q);let Z=J.fetchImpl??((B,W)=>fetch(B,W)),Y=J.sleep??Z5,G=J.random??Math.random,V=J.now??Date.now,z=Math.max(0,J.maxRetries),H=J.startedAt??V(),K=J.retry,X=(B,W,q,F)=>{let x=V()-H;try{J.onRetry?.({attempt:W+1,maxRetries:z,error:M(q),...f(q),timedOut:F,delayMs:B,elapsedMs:x,...K?{remainingMs:Math.max(0,K.patienceMs-x-B)}:{}})}catch{}return NQ(B,J.signal,Y)},j=(B,W,q,F)=>{if(!K)return;let{status:x}=f(q);if(!CQ(K,M(q),{...x?{status:x}:{},timedOut:F}))return;return FQ(K,B-z,W,V()-H,G)};for(let B=0;;B++){J.signal?.throwIfAborted();let W=new AbortController,q=()=>W.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let F=!1,x=J.timeoutMs>0?setTimeout(()=>{F=!0,W.abort()},J.timeoutMs):void 0,U;try{U=await Z(Q,{...$,signal:W.signal})}catch(o){if(x!==void 0)clearTimeout(x);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw o;let k=F?new JQ(J.timeoutMs):o;if(F&&J.retryTimeouts===!1)throw k;let T=B<z?$Q(B,G):j(B,void 0,k,F);if(T===void 0)throw k;await X(T,B,k,F);continue}if(x!==void 0)clearTimeout(x);if(U.ok)return U;J.signal?.removeEventListener("abort",q);let p=await $6(U),I=new A(U.status,p,U.headers.get("x-request-id")??U.headers.get("request-id")??void 0,t5(U.headers.get("retry-after"),V()));if(!Q6(U.status,I))throw I;let P=I.retryAfter??(U.status===429?M(I).retryAfter:void 0),S=B>=z?j(B,P,I,!1):P===void 0?$Q(B,G):Math.min(P,$5);if(S===void 0)throw I;await X(S,B,I,!1)}}async function $6(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function Y5(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,Y=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!Y)return Q;let G=Y?performance.now()+Y:1/0,V=Q.getReader();return new ReadableStream({async pull(z){let H,K,X=Math.max(0,G-performance.now()),j=!Z||X<=Z,B=j?X:Z,W=new Promise((q,F)=>{H=setTimeout(()=>{K=j?J.max():J.idle(),F(K)},B)});try{let q=await Promise.race([V.read(),W]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let F=K??q;z.error(F),V.cancel(F).catch(()=>{})}finally{clearTimeout(H)}},cancel(z){return V.cancel(z)}},{highWaterMark:0})}var PQ=30000,G5=10,V5=7200,J6=600,Z6="gpt-live-transcribe";function Y6(Q){return Q.type==="transcription"}function G6(Q){if(Q.language!==void 0&&Q.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let Y of Q.keywords??[])if(/[<>\r\n]/.test(Y))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(Y)}.`);let $={model:Q.model??Z6};if(Q.prompt!==void 0)$.prompt=Q.prompt;if(Q.keywords?.length)$.keywords=Q.keywords;if(Q.languages?.length)$.languages=Q.languages;if(Q.language!==void 0)$.language=Q.language;if(Q.delay!==void 0)$.delay=Q.delay;let J={transcription:$,turn_detection:Q.turnDetection?K5(Q.turnDetection):null};if(Q.noiseReduction!==void 0)J.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Z={type:"transcription",audio:{input:J}};if(Q.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...Q.vendor}}function V6(Q){if(!Q)return{type:"object",properties:{}};return B5(Q)?Q.toJSONSchema():Q}function ZQ(Q,$){if(Y6(Q))return G6(Q);let J={type:"realtime"},Z=Q.model??$;if(Z)J.model=Z;if(Q.instructions!==void 0)J.instructions=Q.instructions;if(Q.outputModalities)J.output_modalities=Q.outputModalities;if(Q.maxOutputTokens!==void 0)J.max_output_tokens=Q.maxOutputTokens;if(Q.truncation!==void 0)J.truncation=Q.truncation;if(Q.tools)J.tools=Q.tools.map((V)=>({type:"function",name:V.name,...V.description?{description:V.description}:{},parameters:V6(V.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let Y={};if(Q.turnDetection!==void 0)Y.turn_detection=Q.turnDetection&&K5(Q.turnDetection);if(Q.transcription!==void 0)Y.transcription=Q.transcription;if(Q.noiseReduction!==void 0)Y.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let G={};if(Q.voice!==void 0)G.voice=Q.voice;if(Q.speed!==void 0)G.speed=Q.speed;if(Object.keys(Y).length||Object.keys(G).length)J.audio={...Object.keys(Y).length?{input:Y}:{},...Object.keys(G).length?{output:G}:{}};return{...J,...Q.vendor}}function K5(Q){let $={type:Q.type};if(Q.createResponse!==void 0)$.create_response=Q.createResponse;if(Q.interruptResponse!==void 0)$.interrupt_response=Q.interruptResponse;if(Q.type==="semantic_vad"){if(Q.eagerness!==void 0)$.eagerness=Q.eagerness}else{if(Q.threshold!==void 0)$.threshold=Q.threshold;if(Q.prefixPaddingMs!==void 0)$.prefix_padding_ms=Q.prefixPaddingMs;if(Q.silenceDurationMs!==void 0)$.silence_duration_ms=Q.silenceDurationMs;if(Q.idleTimeoutMs!==void 0)$.idle_timeout_ms=Q.idleTimeoutMs}return $}function UQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},Y=Q?.input_token_details??Q?.input_tokens_details,G=Q?.output_token_details??Q?.output_tokens_details;if(typeof Y?.cached_tokens==="number")Z.cachedInputTokens=Y.cached_tokens;if(typeof Y?.audio_tokens==="number")Z.audioInputTokens=Y.audio_tokens;let V=Y?.cached_tokens_details?.audio_tokens;if(typeof V==="number")Z.cachedAudioInputTokens=V;if(typeof Y?.image_tokens==="number"&&Y.image_tokens>0)Z.imageInputTokens=Y.image_tokens;if(typeof G?.audio_tokens==="number")Z.audioOutputTokens=G.audio_tokens;return Z}class i extends Error{code;retryable;status;constructor(Q,$={}){super(Q.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=Q.code,this.retryable=Q.retryable,$.status!==void 0)this.status=$.status}}var B6=60;class YQ{model;target;options;constructor(Q,$){this.target=Q,this.options=$,this.model=$.model}url(Q){return`${this.target.base}/realtime${Q}${this.target.query}`}sidebandUrl(Q){let $=this.target.base.replace(/^http(s?):/i,(Z,Y)=>`ws${Y}:`),J=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${J}call_id=${encodeURIComponent(Q)}`}async createCall(Q){let $=Q.flow??this.options.callFlow??"unified",J,Z;if($==="ephemeral")J={authorization:`Bearer ${(await this.clientSecret({session:Q.session,ttlSeconds:B6,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let H=new FormData;H.set("sdp",Q.sdp),H.set("session",JSON.stringify(ZQ(Q.session??{},this.model))),J=await this.target.headers(),Z=H}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=this.url("/calls"),G=await this.request(Q.webrtcFilter?`${Y}${Y.includes("?")?"&":"?"}webrtcfilter=on`:Y,{method:"POST",headers:J,body:Z},Q.signal),V=await G.text(),z=W6(G);if(!z)throw new i({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:V,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??J6;if(!Number.isInteger($)||$<G5||$>V5)throw RangeError(`ttlSeconds must be a whole number from ${G5} to ${V5}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:ZQ(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new i({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:Y.value,expiresAt:Number(Y.expires_at??0),session:Y.session,callsUrl:this.url("/calls")}}async hangup(Q,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(Q)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(J){if(K6(J,Q))return;throw J}}sideband(Q,$={}){return new LQ({...$,callId:Q,url:this.sidebandUrl(Q),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(Q)})}async request(Q,$,J){try{return await m(Q,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:J,fetchImpl:this.options.fetchImpl})}catch(Z){if(J?.aborted)throw Z;throw new i(M(Z),{cause:Z,...Z instanceof A?{status:Z.status}:{}})}}}function K6(Q,$){if(!(Q instanceof i)||Q.status!==404)return!1;let J=Q.cause instanceof A?Q.cause.body:void 0,Z=J?.error??J,Y=String(Z?.code??"").toLowerCase(),G=String(Z?.message??"").toLowerCase();if(Y.includes("call"))return!0;if(G.includes($.toLowerCase()))return!0;return/\bcall\b/.test(G)&&/not (be )?found|does not exist|no longer|ended/.test(G)}function W6(Q){let $=Q.headers.get("location");if(!$)return;let J=$.split("?")[0].replace(/\/+$/,""),Z=J.slice(J.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}var X6={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function H6(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=X6[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=UQ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=UQ($.usage);return $}var W5=1,j6=500;function z6(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return tQ(Q),new J(Q,{headers:$.headers})}class LQ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(Q){this.init=Q,this.callId=Q.callId,this.ready=new Promise(($,J)=>{this.resolveReady=$,this.rejectReady=J}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(Q){if(this.finished||this.closing)return;let $=JSON.stringify(Q);if(this.socket?.readyState===W5)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:ZQ(Q)})}addItem(Q){this.send({type:"conversation.item.create",item:Q})}addNote(Q){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:Q}]})}functionOutput(Q,$){this.addItem({type:"function_call_output",call_id:Q,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(Q={}){let $={};if(Q.instructions!==void 0)$.instructions=Q.instructions;if(Q.toolChoice!==void 0)$.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};if(Q.outputModalities)$.output_modalities=Q.outputModalities;if(Q.conversation)$.conversation=Q.conversation;if(Q.metadata)$.metadata=Q.metadata;Object.assign($,Q.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(Q){this.send(Q?{type:"response.cancel",response_id:Q}:{type:"response.cancel"})}on(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}[Symbol.asyncIterator](){let Q={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(Q),{next:async()=>{for(;;){let J=Q.queue.shift();if(J)return{value:J,done:!1};if(Q.done)return this.subscribers.delete(Q),{value:void 0,done:!0};await new Promise((Z)=>Q.wake=Z),Q.wake=void 0}},return:async()=>{return Q.done=!0,Q.queue.length=0,this.subscribers.delete(Q),{value:void 0,done:!0}}}}close(Q=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=W5)this.socket.close(Q,$);else this.finish(Q,$,!0)}async hangup(){try{await this.init.hangup()}catch(Q){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw Q}this.close(1000,"hangup")}async open(){let Q;try{let J=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);Q=(this.init.webSocket??z6)(this.init.url,{headers:J})}catch(J){return this.dropped(1006,J instanceof Error?J.message:String(J),!1)}this.socket=Q;let $=!1;Q.addEventListener("open",()=>{$=!0;let J=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let Y of this.outbox.splice(0))Q.send(Y);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=H6(J.data);if(Z)this.emit(Z)}),Q.addEventListener("close",(J)=>{if(this.socket!==Q)return;this.dropped(J.code??1006,J.reason??"",$)}),Q.addEventListener("error",()=>{})}dropped(Q,$,J){if(this.socket=void 0,this.closing)return this.finish(Q,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((Q!==1000||!J)&&this.failures<Z))return this.finish(Q,$,!1);this.failures+=1;let G=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),G)}finish(Q,$,J){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:Q,reason:$,byClient:J};this.finalEvent=Z,this.emit(Z);for(let Y of this.subscribers)Y.done=!0,Y.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${Q} ${$}).`));this.resolveClosed(Z)}emit(Q){if(this.backlog){if(this.backlog.push(Q),this.backlog.length>j6)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var j5=3;function DQ(Q){let $=new Map;for(let J of Q)for(let Z of J.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function z5(Q,$,J=new Map){if(!($ instanceof A))return[];if($.status!==400&&$.status!==404)return[];let Z=OQ($.body);if(!Z)return[];let Y=q6(Q.input);if(Y.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let K=Q.input[Number(G[1])],X=xQ(K)[Number(G[2])],j=X&&typeof X.file_id==="string"?X.file_id:void 0;if(j)return[j]}let V=Z.message??"",z=H5(Y.map((K)=>K.fileId).filter((K)=>C6(V,K)));if(z.length>0)return z;let H=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(V);if(H){let K=H[1].toLowerCase()==="image type"?"input_image":"input_file",X=H[2].toLowerCase(),j=H5(Y.filter((W)=>W.type===K).map((W)=>W.fileId)),B=j.filter((W)=>(J.get(W)?.name??"").trim().toLowerCase().endsWith(`.${X}`));if(B.length===1)return B;if(B.length===0&&j.length===1)return j}return[]}function q5(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=xQ(Z);if(!Y.some((G)=>X5(G,$)))return Z;return{...Z,content:Y.map((G)=>X5(G,$)?{type:"input_text",text:n(J.get(String(G.file_id))?.name)}:G)}})}}function n(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function X5(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function xQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function q6(Q){let $=[];for(let J of Q)for(let Z of xQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function OQ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof J.message==="string"?J.message:void 0,param:typeof J.param==="string"?J.param:void 0}}function C6(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function H5(Q){return[...new Set(Q)]}function C5(Q,$){if(!($ instanceof A))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=OQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(V)=>V?.type==="reasoning";if(!J.some((V)=>G(V)&&V.id===Y))return null;return{...Q,input:J.filter((V)=>!G(V))}}async function*_Q(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let H={event:J,data:Z.join(`
|
|
3
|
-
`),id:Y};return J="",Z=[],Y=void 0,H.data?H:null},V=(H)=>{let K=H.endsWith("\r")?H.slice(0,-1):H;if(K==="")return G();if(K.startsWith(":"))return null;let X=K.indexOf(":"),j=X===-1?K:K.slice(0,X),B=X===-1?"":K.slice(X+1);if(B.startsWith(" "))B=B.slice(1);if(j==="event")J=B;else if(j==="data")Z.push(B);else if(j==="id")Y=B;return null};for await(let H of Q){$+=H;let K=$.indexOf(`
|
|
4
|
-
`);while(K!==-1){let X=$.slice(0,K);$=$.slice(K+1);let j=V(X);if(j)yield j;K=$.indexOf(`
|
|
5
|
-
`)}}if($.length>0){let H=V($);if(H)yield H}let z=G();if(z)yield z}async function*F5(Q,$={}){let J=new Map,Z=new Set,Y,G=!1,V,z=(H,K)=>({type:"finish",reason:H,usage:K,...V?{model:V}:{}});for await(let H of _Q(Q)){if(H.data==="[DONE]")break;let K;try{K=JSON.parse(H.data)}catch{continue}let X=typeof K.type==="string"?K.type:H.event,j=K.response?.model;if(typeof j==="string"&&j)V=j;switch(X){case"response.output_text.delta":{let B=String(K.delta??"");if(!B)break;yield $.structuredOutput?{type:"output-delta",delta:B}:{type:"text-delta",delta:B};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let B=String(K.delta??"");if(!B)break;yield{type:"reasoning-delta",delta:B,id:K.item_id};break}case"response.output_item.added":{let B=K.item;if(!B)break;if(B.type==="function_call"){let W=String(B.id??K.item_id??B.call_id??"");J.set(W,{callId:String(B.call_id??W),name:String(B.name??""),namespace:typeof B.namespace==="string"&&B.namespace?B.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let B=J.get(String(K.item_id??""));if(!B)break;let W=String(K.delta??"");if(!W)break;yield{type:"tool-call-delta",toolCallId:B.callId,name:B.name,argsDelta:W,...B.namespace?{namespace:B.namespace}:{}};break}case"response.function_call_arguments.done":{let B=String(K.item_id??""),W=J.get(B);if(!W)break;W.done=!0,yield{type:"tool-call",toolCallId:W.callId,name:W.name,args:String(K.arguments??""),...W.namespace?{namespace:W.namespace}:{}};break}case"response.output_item.done":{let B=K.item;if(!B)break;if(B.type==="function_call"){let W=String(B.id??K.item_id??B.call_id??""),q=J.get(W);if(q?.done)break;let F=(typeof B.namespace==="string"?B.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(B.call_id??W),name:String(B.name??q?.name??""),args:String(B.arguments??""),...F?{namespace:F}:{}},q)q.done=!0;break}if(B.type==="tool_search_call"||B.type==="tool_search_output"){if(B.type==="tool_search_call"&&B.arguments!==void 0)Y=B.arguments;let W=F6(B);if(W.loaded.length===0&&W.namespaces.length===0)break;let q=String(B.tool_search_call_id??B.id??"");if(Z.has(q))break;Z.add(q);let F=Y;Y=void 0,yield{type:"tool-search",...W,...F!==void 0&&F!==null?{arguments:F}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(K.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield z("stop",MQ(K.response?.usage));break}case"response.incomplete":{G=!0;let B=MQ(K.response?.usage),W=K.response?.incomplete_details?.reason;if(W==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:N6(K.response?.content_filters),retryable:!1}},yield z("error",B);break}yield z(W==="max_output_tokens"?"length":"stop",B);break}case"response.failed":case"error":{G=!0;let B=K.response?.error??K.error??K;yield{type:"error",error:L6(B),...GQ(B)},yield z("error",MQ(K.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield z("error",D())}function F6(Q){let $=[],J=[];return N5(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:SQ($),namespaces:SQ(J)}}function N5(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let Y of Q){if(typeof Y==="string"){$.push(Y);continue}if(!Y||typeof Y!=="object")continue;let G=Y,V=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",z=G.tools??G.functions;if(Array.isArray(z)){if(V)J.push(V);N5(z,$,J,Z+1);continue}if(V)$.push(V)}}function SQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function N6(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let J=[];for(let Z of Q){if(!Z||typeof Z!=="object")continue;let Y=Z,G=Y.content_filter_results;if(!G||typeof G!=="object")continue;for(let[V,z]of Object.entries(G))if(z&&typeof z==="object"&&z.filtered===!0)J.push(`${V} (${String(Y.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${SQ(J).join(", ")}.`}function L6(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",J=String(Q?.code??"").toLowerCase();if(J==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(J==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(J.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function D(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function MQ(Q){if(!Q)return D();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},Y=Q.output_tokens_details?.reasoning_tokens;if(typeof Y==="number")Z.reasoningTokens=Y;let G=Q.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*L5(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:Y,value:G}=await $.read();if(Y)break;if(G)yield J.decode(G,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function BQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,streamIdleTimeoutMs:Q.streamIdleTimeoutMs,streamMaxDurationMs:Q.streamMaxDurationMs,maxToolArgumentChars:Q.maxToolArgumentChars,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace,maxRetries:Q.maxRetries,...Q.retry?{retry:Q.retry}:{}}}async function*KQ(Q,$,J){let Z=J.parse??F5,Y=$,G=new Set,V=0,z=!1,H=Math.max(0,Q.maxRetries),K=Q.random??Math.random,X,j=(P)=>{if(!X)return P;let S=g(g(D(),X),P.usage);return X=void 0,{...P,usage:S}},B=(P)=>j({type:"finish",reason:"aborted",usage:P??D()}),W=(P)=>g(g(D(),X??D()),P),q=Q.streamIdleTimeoutMs??0,F=Q.streamMaxDurationMs??0,x=Q.maxToolArgumentChars??0,U=Q.maxToolArgumentWhitespace??0,p=Q.now??Date.now,I=p();for(let P=0;;P++){let S=new AbortController,o=J.signal?AbortSignal.any([J.signal,S.signal]):S.signal,k;while(k===void 0)try{let N=[],C=()=>{},L=m(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(Y)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:o,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:I,...Q.retry?{retry:Q.retry}:{},onRetry:(R)=>{N.push({type:"retry",...R,phase:"request"}),C()}}),_=L.then(()=>!0,()=>!0);for(;;){let R=new Promise((y)=>C=()=>y(!1)),b=await Promise.race([_,R]);if(yield*N.splice(0),b)break}k=await L}catch(N){let C=Y,L=J.files&&V<j5?z5(C,N,J.files).filter((b)=>!G.has(b)):[];if(L.length>0){V++;let b=M(N).message;for(let y of L)G.add(y),yield{type:"file-rejected",fileId:y,message:b,...f(N)};Y=q5(C,new Set(L),J.files);continue}let _=z?null:C5(Y,N);if(_){z=!0,Y=_;continue}let R=M(N);if(R.code==="aborted"){yield B();return}yield{type:"error",error:R,...f(N)},yield j({type:"finish",reason:"error",usage:D()});return}let T=[],l=!1,u,zQ=!1,E,w=new Map,v,rQ=()=>v?{usage:W(v)}:{},t;try{let N=Y5(k.body,{idleMs:q,maxMs:F},{idle:()=>{let C=new U5(q);return S.abort(C),C},max:()=>{let C=new D5(F);return S.abort(C),C}});for await(let C of Z(L5(N),{structuredOutput:J.structuredOutput,onUsage:(L)=>v=L})){if(C.type==="usage"){v=C.usage,yield{type:"usage",usage:W(C.usage)};continue}if(C.type==="tool-call-delta"){let L=w.get(C.toolCallId);if(!L)w.set(C.toolCallId,L=P6());U6(L,C.argsDelta,U>0);let _=L.chars;if(U>0&&L.space>U){let R=L.text.trimEnd(),b=D6(R);if(x6(C.name,C.toolCallId,_,L.space,U,b),!b){let y=new x5(U,C.name,C.toolCallId,_,L.space);throw S.abort(y),y}w.delete(C.toolCallId),t={type:"tool-call",toolCallId:C.toolCallId,name:C.name,args:R,...C.namespace?{namespace:C.namespace}:{}};break}if(x>0&&_>x){let R=new RQ(x,C.name,C.toolCallId,_);throw S.abort(R),R}yield C;continue}if(C.type==="tool-call")w.delete(C.toolCallId);if(l){yield C.type==="finish"?j(C):C;continue}if(VQ(C)){l=!0,yield*T.splice(0),yield C;continue}if(C.type==="error")u=C.error;T.push(C)}if(t)await N?.cancel().catch(()=>{})}catch(N){zQ=N instanceof JQ;let C=M(N);if(C.code==="aborted"||J.signal?.aborted){yield B(v);return}if(N instanceof RQ)E=N.detail;if(l){yield{type:"error",error:C,...E?{toolArgumentsTooLong:E}:{},...rQ()},yield j({type:"finish",reason:"error",usage:v??D()});return}u=C,T.push({type:"error",error:C,...E?{toolArgumentsTooLong:E}:{},...rQ()},{type:"finish",reason:"error",usage:v??D()})}if(t){if(S.abort(),!l)yield*T.splice(0);if(yield t,w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};yield j({type:"finish",reason:"stop",usage:v??D()});return}if(l)return;let e={};for(let N of T)if(N.type==="error")e=f(N);let QQ=!u?.retryable||J.signal?.aborted||E&&J.retryToolArgumentsTooLong===!1?void 0:P<H?$Q(P,K):Q.retry&&CQ(Q.retry,u,{...e.status!==void 0?{status:e.status}:{},timedOut:zQ,...E?{toolArgumentsTooLong:E}:{}})?FQ(Q.retry,P-H,u.retryAfter,p()-I,K):void 0;if(QQ!==void 0){let N;for(let _ of T)if(_.type==="finish")N=g(N??D(),_.usage);if(N)X=g(X??D(),N);let C=N&&N.totalTokens>0?{usage:N}:{};if(w.size>0)yield{type:"tool-call-discard",toolCallIds:[...w.keys()]};let L=p()-I;if(yield{type:"retry",attempt:P+1,maxRetries:H,error:u,...e,...C,phase:"stream",timedOut:zQ,...E?{toolArgumentsTooLong:E}:{},delayMs:QQ,elapsedMs:L,...Q.retry?{remainingMs:Math.max(0,Q.retry.patienceMs-L-QQ)}:{}},X&&X.totalTokens>0)yield{type:"usage",usage:W(D())};try{await NQ(QQ,J.signal,Q.sleep)}catch{yield B();return}continue}for(let N of T)yield N.type==="finish"?j(N):N;return}}function P6(){return{chars:0,text:"",inString:!1,escaped:!1,space:0}}function U6(Q,$,J){if(Q.chars+=$.length,!J)return;Q.text+=$;for(let Z of $){if(Q.inString){if(Q.escaped)Q.escaped=!1;else if(Z==="\\")Q.escaped=!0;else if(Z==='"')Q.inString=!1}else if(Z===" "||Z===`
|
|
6
|
-
`||Z==="\r"||Z==="\t"){Q.space++;continue}else if(Z==='"')Q.inString=!0;Q.space=0}}function D6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function x6(Q,$,J,Z,Y,G){let V=`[gemi/ai] tool call "${Q}" ran away in white space (more than ${Y} characters, maxToolArgumentWhitespace); ${G?"its arguments were whole JSON, so it was finished as written":"its arguments were not whole JSON, so it was cut"}`,z={tool:Q,toolCallId:$,chars:J,whitespace:Z,limit:Y,whole:G},H=!1;try{P5.warning(V,z),H=!0}catch{}if(!H||Bun.env.NODE_ENV==="development")console.warn(V,z)}async function WQ(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let G=await(await m(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}async function XQ(Q,$){let J=Q.filesUrl.indexOf("?"),Z=J===-1?Q.filesUrl:Q.filesUrl.slice(0,J),Y=J===-1?"":Q.filesUrl.slice(J);try{await(await m(`${Z}/${encodeURIComponent($)}${Y}`,{method:"DELETE",headers:await Q.headers()},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl,...Q.sleep?{sleep:Q.sleep}:{},...Q.random?{random:Q.random}:{}})).body?.cancel()}catch(G){if(G instanceof A&&G.status===404)return;throw G}}function AQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:O6(Q.messages,J,Q.tools),stream:!0};if(Q.trailingContext)Z.input.push({role:"developer",content:[{type:"input_text",text:Q.trailingContext}]});if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let Y=M5(Q.tools,J),G;if(Q.allowedTools)if(Y.every((V)=>V.type==="function"))G=Q.allowedTools;else Y=M5(k6(Q.tools??[],Q.allowedTools),J);if(Y.length>0){if(Z.tools=Y,!J.parallelToolCalls)Z.parallel_tool_calls=!1;let V=Q.toolChoice;if(G&&V!=="none"&&typeof V!=="object")Z.tool_choice={type:"allowed_tools",mode:V==="required"?"required":"auto",tools:G.map((z)=>({type:"function",name:z}))};else if(V!==void 0)Z.tool_choice=typeof V==="string"?V:{type:"function",name:V.name}}if(Q.output)Z.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&J.reasoning)Z.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")Z.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")Z.max_output_tokens=Q.maxOutputTokens;if(Q.promptCacheKey)Z.prompt_cache_key=Q.promptCacheKey;return Z}function O6(Q,$,J){let Z=[],Y=new Map;if($.toolSearch){for(let G of J??[])if(s(G))Y.set(G.name,G)}for(let G of Q){let V=G.role,z=!A6.has(G.finishReason),H=[],K=()=>{if(H.length===0)return;Z.push({type:"message",role:V,content:H}),H=[]};for(let X of G.content??[])switch(X.type){case"text":{if(!X.text)break;H.push(c(V,X.text));break}case"output":{if(X.partial)break;H.push(c(V,JSON.stringify(X.value)));break}case"file":{if(V==="assistant")break;let j=TQ(X);if(!$.fileInput){if(j)H.push(c(V,r(X,!1)));break}if(kQ(X,j),X.providerRejected){if(j)H.push(c(V,r(X,!1)));H.push(c(V,n(X.name)));break}if(j)H.push(c(V,r(X,!!X.fileId)));if(X.fileId)H.push(_6(X));break}case"reasoning":{if(K(),!z)break;let j=T6(X);if(j)Z.push(j);break}case"tool-call":{if(X.partial)break;if(K(),$.toolSearch&&Array.isArray(X.toolSearches))for(let B of X.toolSearches)Z.push(...E6(B,J??[]));let j={type:"function_call",call_id:X.toolCallId,name:String(X.name),arguments:JSON.stringify(X.input??{})};if(X.namespace&&Y.has(X.namespace))j.namespace=X.namespace;Z.push(j);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:X.toolCallId,output:wQ(X)});break}}K()}return S6(Z)}var M6="No result was recorded for this tool call. Assume it did not complete.";function S6(Q){let $=new Set,J=new Set,Z=[];for(let G of Q){if(G.type==="function_call"){let V=String(G.call_id);if($.has(V))continue;$.add(V)}else if(G.type==="function_call_output"){let V=String(G.call_id);if(!$.has(V)||J.has(V))continue;J.add(V)}Z.push(G)}if(J.size===$.size)return Z;let Y=[];for(let G of Z){if(Y.push(G),G.type!=="function_call")continue;let V=String(G.call_id);if(J.has(V))continue;J.add(V),Y.push({type:"function_call_output",call_id:V,output:M6})}return Y}function c(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function TQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(IQ)?$:void 0}function r(Q,$){let J=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)J.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)J.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let Z=`attachment ${J.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function _6(Q){return{type:EQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function EQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":R6(Q.name)}function kQ(Q,$){if(Q.fileId?.startsWith(IQ))throw Error(`FilePart.fileId holds a gemi attachment id (${Q.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Q.fileId&&!$)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.")}function R6(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&I6.has($[1])}var I6=new Set(["jpeg","jpg","png","gif","webp"]),A6=new Set(["error","aborted","interrupted"]);function T6(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function wQ(Q){if(Q.status==="ok"){let $=Q.modelOutput!==void 0?Q.modelOutput:Q.output;return typeof $==="string"?$:JSON.stringify($??null)}if(Q.status==="running"){let $=Q.job?.summary===void 0?"":` Started with: ${JSON.stringify(Q.job.summary)}.`;return`Started background job ${Q.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;if(Q.cause==="denied-earlier")return`The user already declined this tool call earlier in this conversation, so it did not run and they were not asked again. Do not ask for it again; carry on without it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function E6(Q,$){let J=new Set(O5(Q?.loaded)),Z=O5(Q?.namespaces),Y=new Set(Z),G=[];for(let z of $)if(s(z)){if(!Y.has(z.name))continue;let H=z.tools.filter((K)=>J.size===0||J.has(K.name));if(H.length===0)continue;G.push({type:"namespace",name:z.name,description:z.description,tools:H.map((K)=>d(K,!0))})}else if(z.deferred&&J.has(z.name))G.push(d(z,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:Z.length>0?Z:[...J]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function O5(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function s(Q){return Array.isArray(Q.tools)}function M5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let Y=[];for(let G of Q)if(s(G))for(let V of G.tools)Y.push(d(V,!1));else Y.push(d(G,!1));return Y}let J=[],Z=!1;for(let Y of Q)if(s(Y)){let G=Y.tools.map((V)=>{if(V.deferred)Z=!0;return d(V,!0)});J.push({type:"namespace",name:Y.name,description:Y.description,tools:G})}else{if(Y.deferred)Z=!0;J.push(d(Y,!0))}if(Z)J.push({type:"tool_search"});return J}function k6(Q,$){let J=new Set($);return Q.flatMap((Z)=>{if(!s(Z))return J.has(Z.name)?[Z]:[];let Y=Z.tools.filter((G)=>J.has(G.name));return Y.length>0?[{...Z,tools:Y}]:[]})}function d(Q,$){let J={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)J.defer_loading=!0;return J}var w6=64000;function S5(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??w6,messages:l6(Q.messages,$.capabilities),stream:!0},Z=Q.output,Y=!!Z?.strict&&!c6(Z.schema),G=Z&&!Y?d6(Z.schema):void 0,V=[Q.systemPrompt,G].filter(Boolean);if(V.length>0)J.system=[{type:"text",text:V.join(`
|
|
7
|
-
|
|
8
|
-
`)}];let z=$.capabilities.reasoning?Q.reasoning:void 0;if(z==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(z)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:h6(z,$.modelId)};else if($.capabilities.reasoning&&b6(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&Y)J.output_config={...J.output_config,format:{type:"json_schema",schema:m6(Z.schema)}};let H=$7(Q.tools);if(H.length>0){J.tools=H;let K=p6(Q.toolChoice,$.forcedToolChoice);if(!$.capabilities.parallelToolCalls)K.disable_parallel_tool_use=!0;if(Q.toolChoice!==void 0||K.disable_parallel_tool_use)J.tool_choice=K}return v6(y6(J),Q.trailingContext)}function v6(Q,$){if(!$)return Q;let J={type:"text",text:$},Z=Q.messages.at(-1);if(Z?.role==="user")Z.content=[...Z.content,J];else Q.messages.push({role:"user",content:[J]});return Q}function b6(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var vQ="thinking-binding-controls-2026-08-01";function _5(Q){if(/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(Q))return"thinking";if(/schema is too complex/i.test(Q))return"schema";return}function R5(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((G)=>G.type!=="thinking"&&G.type!=="redacted_thinking");if(Z.length===0)continue;let Y=$.at(-1);if(Y?.role===J.role)Y.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function h6(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function y6(Q){let $=(Z)=>{if(Z)Z.cache_control={type:"ephemeral"}};$(Q.tools?.at(-1)),$(Q.system?.at(-1));let J=Q.messages.at(-1)?.content??[];return $([...J].reverse().find((Z)=>Z.type!=="thinking"&&Z.type!=="redacted_thinking")),Q}var f6=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),g6=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),u6=/\\[1-9]|\(\?<?[=!]|\\[bB]/,I5=new Set(["properties","patternProperties","$defs","definitions"]);function m6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!h(J))return J;let Z={},Y=[];for(let[G,V]of Object.entries(J)){if(f6.has(G)||G==="minItems"&&typeof V==="number"&&V>1||G==="format"&&typeof V==="string"&&!g6.has(V)||G==="pattern"&&typeof V==="string"&&u6.test(V)){Y.push(`${G}: ${JSON.stringify(V)}`);continue}Z[G]=I5.has(G)&&h(V)?Object.fromEntries(Object.entries(V).map(([H,K])=>[H,$(K)])):$(V)}if(Y.length>0){let G=`{${Y.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${G}`:G}if(Z.type==="object"||h(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function c6(Q){let $=0,J=0,Z=(Y)=>{if(Array.isArray(Y))return Y.forEach(Z);if(!h(Y))return;if(Array.isArray(Y.anyOf)||Array.isArray(Y.type))J++;if(h(Y.properties)){let G=new Set(Array.isArray(Y.required)?Y.required:[]);$+=Object.keys(Y.properties).filter((V)=>!G.has(V)).length}for(let[G,V]of Object.entries(Y))if(I5.has(G)&&h(V))Object.values(V).forEach(Z);else Z(V)};return Z(Q),$>24||J>16}function d6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
9
|
-
${JSON.stringify(Q)}`}function p6(Q,$){if(Q==="none")return{type:"none"};if(Q==="required")return $?{type:"any"}:{type:"auto"};if(Q&&typeof Q==="object")return $?{type:"tool",name:Q.name}:{type:"auto"};return{type:"auto"}}function l6(Q,$){let J=[],Z=new Map;for(let X of Q){let j=X.role==="assistant"?"assistant":"user";J.push("step-end");for(let B of X.content??[])switch(B.type){case"text":{if(j==="assistant"?!!B.text:!!B.text?.trim())J.push({role:j,block:{type:"text",text:B.text}});break}case"output":{if(B.partial)break;let W=B.text??JSON.stringify(B.value);J.push({role:j,block:{type:"text",text:W}});break}case"file":{if(j==="assistant")break;for(let W of o6(B,$))J.push({role:j,block:W});break}case"reasoning":{let W=j==="assistant"?a6(B):void 0;if(W)J.push({role:j,block:W});break}case"tool-call":{if(B.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:B.toolCallId,name:String(B.name),input:h(B.input)?B.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(B.toolCallId))break;Z.set(B.toolCallId,{type:"tool_result",tool_use_id:B.toolCallId,content:wQ(B),...B.status==="error"?{is_error:!0}:{}});break}}}let Y=[],G=(X,j)=>{let B=Y[Y.length-1];if(B&&B.role===X)B.content.push(j);else Y.push({role:X,content:[j]})},V=new Set,z=[],H=!1,K=()=>{for(let X of z)G("user",Z.get(X)??s6(X));z=[],H=!1};for(let X of J){if(X==="step-end"){H=!0;continue}let{role:j,block:B}=X;if(H||j==="user")K();if(B.type==="tool_use"){let W=String(B.id);if(V.has(W))continue;V.add(W),z.push(W)}G(j,B)}if(K(),Y[0]?.role==="assistant")Y.unshift({role:"user",content:[{type:"text",text:i6}]});if(Y.at(-1)?.role==="assistant")Y.push({role:"user",content:[{type:"text",text:n6}]});return Y}var i6="(The conversation continues from an earlier point.)",n6="Continue.",r6="No result was recorded for this tool call. Assume it did not complete.";function s6(Q){return{type:"tool_result",tool_use_id:Q,content:r6}}function a6(Q){let $=Q.providerMetadata?.anthropic;if(!h($))return;if($.type==="thinking"&&typeof $.signature==="string")return{type:"thinking",thinking:Q.text??"",signature:$.signature};if($.type==="redacted_thinking"&&typeof $.data==="string")return{type:"redacted_thinking",data:$.data};return}function o6(Q,$){let J=TQ(Q),Z=(G)=>J?[{type:"text",text:r(Q,G)}]:[];if(!$.fileInput)return Z(!1);if(kQ(Q,J),!Q.fileId)return Z(!1);let Y=Q.providerRejected?void 0:e6(Q);if(!Y)return[...Z(!1),{type:"text",text:n(Q.name)}];return[...Z(!0),{type:Y,source:{type:"file",file_id:Q.fileId}}]}var t6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function e6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(EQ(Q))return!$||t6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function h(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function Q7(Q){return Array.isArray(Q.tools)}function $7(Q){let $=[];for(let J of Q??[])for(let Z of Q7(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*k5(Q,$={}){let J=new Map,Z=[],Y,G={},V,z,H=!1,K=(X)=>({type:"finish",reason:X,usage:a(G),...Y?{model:Y}:{}});for await(let X of _Q(Q)){let j;try{j=JSON.parse(X.data)}catch{continue}switch(typeof j.type==="string"?j.type:X.event){case"message_start":{let W=j.message??{};if(typeof W.model==="string"&&W.model)Y=W.model;G=E5(G,W.usage),$.onUsage?.(a(G)),yield{type:"usage",usage:a(G)};break}case"content_block_start":{let W=Number(j.index),q=j.content_block??{},F={type:String(q.type??""),id:typeof q.id==="string"?q.id:void 0,name:typeof q.name==="string"?q.name:void 0,args:"",signature:typeof q.signature==="string"?q.signature:""};if(J.set(W,F),F.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(q.data??"")}}};if(F.type==="text"&&typeof q.text==="string"&&q.text)yield T5(q.text,$);break}case"content_block_delta":{let W=J.get(Number(j.index)),q=j.delta??{};if(!W)break;if(q.type==="text_delta"){let F=String(q.text??"");if(F)yield T5(F,$)}else if(q.type==="thinking_delta"){let F=String(q.thinking??"");if(F)yield{type:"reasoning-delta",delta:F}}else if(q.type==="signature_delta")W.signature+=String(q.signature??"");else if(q.type==="input_json_delta"&&W.type==="tool_use"){let F=String(q.partial_json??"");if(!F)break;W.args+=F,yield{type:"tool-call-delta",toolCallId:W.id??"",name:W.name??"",argsDelta:F}}break}case"content_block_stop":{let W=Number(j.index),q=J.get(W);if(J.delete(W),q?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:q.signature}}};if(q?.type==="tool_use")if(q.args||="{}",J7(q.args))yield A5(q);else Z.push(q);break}case"message_delta":{if(typeof j.delta?.stop_reason==="string")V=j.delta.stop_reason;if(j.delta?.stop_details)z=j.delta.stop_details;G=E5(G,j.usage),$.onUsage?.(a(G)),yield{type:"usage",usage:a(G)};break}case"message_stop":{if(H=!0,V==="refusal"){yield{type:"error",error:Y7(z)},yield K("error");break}let W=Z7(V);if(Z.length>0&&W==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((q)=>q.id??"")};else for(let q of Z)yield A5(q);yield K(W);break}case"error":{H=!0;let W=j.error??j;yield{type:"error",error:G7(W),...GQ(W)},yield K("error");break}}if(H)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function A5(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function J7(Q){try{return JSON.parse(Q),!0}catch{return!1}}function T5(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function Z7(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function Y7(Q){let $=typeof Q?.explanation==="string"?Q.explanation:"",J=typeof Q?.category==="string"?` (${Q.category})`:"";return{code:"content_filtered",message:$||`The model declined to answer${J}.`,retryable:!1}}function G7(Q){let $=String(Q?.type??"").toLowerCase(),J=typeof Q?.message==="string"?Q.message:"The provider stream failed.";if($==="rate_limit_error")return{code:"rate_limited",message:J,retryable:!0};if($==="invalid_request_error"||$==="request_too_large")return{code:/prompt is too long|request_too_large/i.test(`${$} ${J}`)?"context_length_exceeded":"provider_error",message:J,retryable:!1};if($==="authentication_error"||$==="permission_error"||$==="billing_error"||$==="not_found_error")return{code:"provider_error",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function E5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let Y of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[Y]==="number")J[Y]=$[Y];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function a(Q){if(!Q)return D();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),Y=Q.output_tokens??0,G={inputTokens:Z,outputTokens:Y,totalTokens:Z+Y};if(typeof $==="number")G.cachedInputTokens=$;if(typeof J==="number")G.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")G.reasoningTokens=Q.thinking_tokens;return G}function bQ(Q){let $=HQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:!0};let J=v5($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:w5(J),supportsForcedToolChoice:!0};if(J?.kind==="gpt")return{reasoning:J.major>=5,structuredOutput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:w5(J),supportsForcedToolChoice:!0};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,supportsForcedToolChoice:!0}}function w5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function hQ(Q){let $=v5(HQ(Q));return{trailingContext:!0,allowedTools:!$||$.kind==="gpt"&&$.major>=5}}function yQ(){return{trailingContext:!0}}function fQ(Q){let $=HQ(Q),J=/^claude-(?:opus|sonnet|haiku)-4(?:-(\d{1,2}))?(?:-\d{8})?$/.exec($);return{reasoning:!(/^claude-(?:3|2|instant)/.test($)||!!J&&Number(J[1]??0)<=5),structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:V7(Q)}}function V7(Q){let $=HQ(Q);return/^claude-(?:3|2|instant)/.test($)||/^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test($)||/^claude-(?:opus|sonnet|fable|mythos)-5(?:-\d{8})?$/.test($)||/^claude-haiku-5-5(?:-\d{8})?$/.test($)}function HQ(Q){return Q.trim().toLowerCase()}function v5(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let J=/^o(\d+)(?:[-.]|$)/.exec(Q);if(J?.[1])return{kind:"o",major:Number(J[1]),minor:0};return null}var gQ=120000,uQ=2,mQ=120000,cQ=300000,dQ=1000;function O(Q){return typeof process>"u"?void 0:process.env?.[Q]}var B7="preview";function b5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function K7(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function pQ(Q,$={}){return{base:(Q.baseURL??O("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??O("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??gQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??mQ,streamMaxDurationMs:Q.streamMaxDurationMs??cQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??dQ,maxRetries:Q.maxRetries??uQ,...iQ(Q)}}function h5(Q){let $=Q.baseURL??Q.endpoint??O("AZURE_OPENAI_ENDPOINT");if($)return b5($);let J=Q.resourceName??O("AZURE_OPENAI_RESOURCE_NAME")??O("AZURE_RESOURCE_NAME");return J?b5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function lQ(Q,$={}){let J=Q.apiVersion??O("AZURE_OPENAI_API_VERSION")??B7;return{base:`${h5(Q)}${K7(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??O("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??gQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??mQ,streamMaxDurationMs:Q.streamMaxDurationMs??cQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxToolArgumentWhitespace:Q.maxToolArgumentWhitespace??dQ,maxRetries:Q.maxRetries??uQ,...iQ(Q)}}var W7="2026-10-21";function y5(Q,$={}){let J=Q.baseURL??O("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return g5(J,Q,$,async()=>{let Z=Q.workspaceId??O("ANTHROPIC_WORKSPACE_ID"),Y=Z?{"anthropic-workspace-id":Z}:{},G=Q.apiKey??O("ANTHROPIC_API_KEY");if(G)return{"x-api-key":G,...Y};let V=O("ANTHROPIC_AUTH_TOKEN");return V?{authorization:`Bearer ${V}`,...Y}:Y})}function f5(Q,$={}){let J=Q.resourceName??O("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??O("ANTHROPIC_FOUNDRY_BASE_URL")??(J?`https://${J.trim()}.services.ai.azure.com/anthropic`:"");if(!Z.trim())throw Error("AzureAnthropicProvider has no Foundry endpoint. Set `endpoint` (the deployment's Target URI without `/v1/messages`, e.g. `https://<resource>.services.ai.azure.com/anthropic`) or `resourceName`, or the ANTHROPIC_FOUNDRY_BASE_URL or ANTHROPIC_FOUNDRY_RESOURCE environment variable.");return g5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let Y=Q.apiKey??O("ANTHROPIC_FOUNDRY_API_KEY");return Y?{"api-key":Y}:{}})}function g5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":W7,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??gQ,streamIdleTimeoutMs:$.streamIdleTimeoutMs??mQ,streamMaxDurationMs:$.streamMaxDurationMs??cQ,maxToolArgumentChars:$.maxToolArgumentChars??0,maxToolArgumentWhitespace:$.maxToolArgumentWhitespace??dQ,maxRetries:$.maxRetries??uQ,...iQ($)}}function u5(Q,$={}){return{...lQ(Q,$),base:`${h5(Q)}/v1`,query:""}}function iQ(Q){return Q5(Q.retry),Q.retry?{retry:Q.retry}:{}}class jQ{static models(){return[]}normalizeError(Q){return M(Q)}}var m5=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class c5 extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...bQ(Q),...hQ(Q)},this.config=$}static model(Q,$){return new c5(Q,$)}static models(){return m5}stream(Q){let $=AQ(Q,{model:this.model,capabilities:this.capabilities});return KQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:DQ(Q.messages)})}upload(Q){return WQ(this.endpoint(),Q)}deleteFile(Q){return XQ(this.endpoint(),Q)}endpoint(){return BQ(pQ(this.config))}get realtime(){return new YQ(pQ(this.config,{timeoutMs:PQ}),{model:this.model})}}var X7=["claude-opus-5-5","claude-sonnet-5-5","claude-haiku-5-5","claude-fable-5-2","claude-fable-5-1","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-opus-4-8","claude-sonnet-4-6","claude-haiku-4-5"];class nQ extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...fQ(Q),...yQ()},this.config=$}cacheWriteFactor(Q){return 1.25}static model(Q,$){return new nQ(Q,$)}static models(){return X7}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let Y=this.request($);if(J)Y=R5(Y);let G,V=!1;for await(let z of KQ(this.endpointFor(Y),Y,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),parse:k5})){if(G)continue;if(!V&&z.type==="error"&&z.status===400){let H=_5(z.error.message);if(H&&!Z.has(H)){Z.add(H),G=H;continue}}if(VQ(z))V=!0;yield z}if(!G)return;if(G==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return S5(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:this.capabilities.supportsForcedToolChoice!==!1,blockBinding:this.bindsThinking()})}endpointFor(Q){let $=this.endpoint();if(!(Q.thinking?.type==="adaptive"&&Q.thinking.block_binding))return $;return{...$,headers:async()=>{let Z=await $.headers(),Y=Z["anthropic-beta"];return{...Z,"anthropic-beta":Y?`${Y},${vQ}`:vQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return WQ(this.endpoint(),Q,null)}deleteFile(Q){return XQ(this.endpoint(),Q)}endpoint(){return d5(y5(this.config))}}function d5(Q){return{...BQ(Q),responsesUrl:`${Q.base}/messages`}}class p5 extends nQ{constructor(Q,$={}){super(Q,$);this.capabilities={...fQ(Q),...yQ(),fileInput:!1}}static model(Q,$){return new p5(Q,$)}upload(Q){return Promise.reject(Error("AzureAnthropicProvider does not upload files: the Files API is not available on Azure-hosted Foundry deployments. The file is still stored by gemi and named to the model by its attachment id."))}deleteFile(Q){return Promise.reject(Error("AzureAnthropicProvider does not delete files: the Files API is not available on Azure-hosted Foundry deployments."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return d5(f5(this.config))}}class l5 extends jQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities={...bQ(Q),...hQ(Q)},this.config=$}static model(Q,$){return new l5(Q,$)}static models(){return m5}stream(Q){let $=AQ(Q,{model:this.deployment(),capabilities:this.capabilities});return KQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:DQ(Q.messages)})}upload(Q){return WQ(this.endpoint(),Q,"assistants")}deleteFile(Q){return XQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return BQ(lQ(this.config))}get realtime(){return new YQ(u5(this.config,{timeoutMs:PQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
10
|
-
export{m as ca,pQ as da,lQ as ea,LQ as fa,Z6 as ga,UQ as ha,i as ia,YQ as ja,K6 as ka,jQ as la,c5 as ma,nQ as na,p5 as oa,l5 as pa};
|
|
11
|
-
|
|
12
|
-
//# debugId=C8C737B1165E48CC64756E2164756E21
|
|
File without changes
|
|
File without changes
|
|
File without changes
|