@decocms/mesh 2.123.1 → 2.123.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1469,7 +1469,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
1469
1469
  ${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
1470
1470
 
1471
1471
  Stack trace:
1472
- ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function BO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=BO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=BO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=BO(Y,H);Z.resolve($),$.dispose()}catch($){let F=qO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=qO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return BO(Y,W)}catch(K){let W=qO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var kc0=()=>{};function OO1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function zr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){OO1(Y);let K=await Promise.race([G,Cm6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function zv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await DO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,zO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=BO(G,Y);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await zr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await zr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())OO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Os(W,H,$)}}async function NO1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await DO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,zO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=BO(G,Y);G.setProp(G.global,"input",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await zr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (input). Got ${D}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await zr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())OO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Os(W,H,$)}}var Cm6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var vc0=j(()=>{Sc0();kc0()});var Dr=j(()=>{vc0()});async function Rm6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function _c0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Im6(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let U=await Q.createMCPProxy(q);return{connection:q,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,U),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,U])=>{try{let D=(await U.proxy.listTools()).tools,L=X.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);D=D.filter((E)=>w.has(E.name))}return{connectionId:q,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,z),null}})),Z=new Set,H=[],$=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=q.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:z}}),$.set(L.name,U)}}let F=async(q,U)=>{let z=$.get(q);if(!z)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:U})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function NP(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await Rm6(J,Y);else X=await _c0(Q.id,Y)}else X=await _c0(Q.id,Y);return Im6(X,Y)}function jm6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function Sm6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Or(Y,Q,X){let J=jm6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:Sm6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Nr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Lr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return zv({code:Y,tools:J,timeoutMs:X})}function Dv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function qB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function DF(Y){let Q=new Set(km6);return Y.filter((X)=>!Q.has(X.name))}var km6;var UO=j(()=>{Dr();km6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var LO1;var yc0=j(()=>{F4();Uv();UO();LO1=t1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wc0,outputSchema:Ac0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await NP(Q),J=Or(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var MO1;var fc0=j(()=>{F4();Uv();UO();MO1=t1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Pc0,outputSchema:Ec0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return Nr(Y.tools,X.tools)}})});var wO1;var bc0=j(()=>{F4();Uv();UO();wO1=t1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:Tc0,outputSchema:Cc0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return await Lr(Y.code,X,Y.timeoutMs)}})});var hc0=j(()=>{yc0();fc0();bc0();Uv()});var _m6,ym6,AO1;var xc0=j(()=>{QY();a1();F4();an();p$();_m6=B.object({data:_T.describe("Data for the new connection (id is auto-generated if not provided)")}),ym6=B.object({item:Y5.describe("The created connection entity")}),AO1=t1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:_m6,outputSchema:ym6,handler:async(Y,Q)=>{z0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=AU(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=PU($)}let K=await EA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var fm6,bm6,gc0;var uc0=j(()=>{a1();MG();fm6=pH.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),bm6=cH("assistant",fm6),gc0=[...bm6]});var Ov,OF,lc0,hm6,xm6,dc0,gm6,um6,mm6,lm6,dm6,pm6,pc0,cm6,nm6,im6,am6,rm6,om6,sm6,tm6,em6,Yl6,vF9,Ql6,_F9,mc0,Xl6,Jl6,PO1,Nv;var Mr=j(()=>{a1();xD();MG();Ov=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),Ov),B.array(Ov)])),OF=B.record(B.string(),B.record(B.string(),Ov)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),lc0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:OF}),hm6=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),xm6=B.string().describe("File data as URL string"),dc0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:xm6,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:OF}),gm6=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),um6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:OF}),mm6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),lm6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:OF}),dm6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),pm6=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:Ov}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:Ov}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))}),B.object({type:B.literal("execution-denied"),reason:B.string().optional()}),B.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),pc0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:pm6.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:OF}),cm6=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),nm6=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),im6=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:OF}),am6=B.object({role:B.literal("user"),content:B.array(B.union([lc0,dc0])).describe("User message content parts (text or file)"),providerOptions:OF}),rm6=B.object({role:B.literal("assistant"),content:B.array(B.union([lc0,dc0,um6,lm6,pc0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:OF}),om6=B.object({role:B.literal("tool"),content:B.array(pc0).describe("Tool message content (tool results)"),providerOptions:OF}),sm6=B.union([im6,am6,rm6,om6]),tm6=B.array(sm6).describe("A list of messages forming the prompt"),em6=B.object({prompt:tm6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),Yl6=B.object({content:B.array(B.union([hm6,gm6,mm6,dm6,cm6,nm6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),vF9=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Ql6=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),_F9=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),mc0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:em6}),Xl6=pH.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Jl6=cH("llm",Xl6,{readOnly:!0}),PO1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:Ql6},{name:"LLM_DO_STREAM",inputSchema:mc0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:mc0,outputSchema:Yl6},...Jl6],Nv=lH(PO1)});function LP(){return!1}function wr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function MP(Y,Q){let X=J91(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:Gl6,bindings:["OBJECT_STORAGE"],status:"active"}}var Gl6;var Ar=j(()=>{Gi();QY();a1();Gl6=tS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function Zl6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function BB(Y){return typeof Y==="string"||typeof Y==="number"}function Pr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Pr(Y,$));case"or":return H.some(($)=>Pr(Y,$));case"not":return!H.every(($)=>Pr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=EO1(Y,K);switch(J){case"eq":return W===G;case"gt":return BB(W)&&BB(G)&&W>G;case"gte":return BB(W)&&BB(G)&&W>=G;case"lt":return BB(W)&&BB(G)&&W<G;case"lte":return BB(W)&&BB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Zl6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function EO1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Kl6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=EO1(X,K),Z=EO1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var Wl6,Hl6,$l6,TO1;var cc0=j(()=>{Yk();uc0();MG();Mr();Gi();QY();a1();F4();Ar();p$();Wl6={LLM:PO1,ASSISTANTS:gc0,OBJECT_STORAGE:tS};Hl6=lZ.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),$l6=n$(Y5),TO1=t1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Hl6,outputSchema:$l6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=Wl6[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?Yi(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(LP()){let q=X7(),U=IY.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=MP(X.id,q);K.unshift(z)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((q)=>Pr(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=Kl6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Fl6,CO1;var nc0=j(()=>{MG();F4();Ar();p$();Fl6=hS(Y5),CO1=t1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:bS,outputSchema:Fl6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),LP()&&wr(Y.id,X.id))return{item:MP(X.id,X7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Er=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function ic0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Vl6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function ql6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function RO1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Vl6(J);if(!G)continue;let[K,W]=G,Z=Er(K,Y),H=ql6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function ac0(Y,Q){let X=RO1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var IO1=()=>{};import{randomBytes as Bl6}from"crypto";function rc0(){if(Lv)return Lv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Lv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Lv=new Uint8Array(Bl6(32));return Lv}async function oc0(Y,Q="5m"){let X=rc0();return await new s5(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function sc0(Y){try{let Q=rc0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Lv=null;var jO1=j(()=>{t5();wP()});async function tc0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class NF{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=J9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Tr=j(()=>{F7()});async function Mv(Y,Q,X){let J=Y.id,G=RO1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await oc0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new NF(Q.db,Q.vault),q=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!q,hasRefresh:!!q?.refreshToken,expiresAt:q?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),q){let U=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await tc0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),F=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=q.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var SO1=j(()=>{IO1();jO1();Tr()});function Cr(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new eJ({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var kO1=j(()=>{LU()});function ec0(Y){let Q=new _S({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Yn0=j(()=>{mq1()});class wv{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Av(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Qn0="mcp.mesh";var Xn0,vO1,LF;var Pv=j(()=>{Xn0=class Xn0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};vO1=class vO1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};LF=class LF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Xn0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new vO1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new vO1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Qn0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Ul6="mcp.mesh",AP;var Jn0=j(()=>{Pv();AP=class AP extends wv{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new LF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Ul6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function Wn0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function yO1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function fO1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function bO1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function zl6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Dl6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1472
+ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function BO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=BO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=BO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=BO(Y,H);Z.resolve($),$.dispose()}catch($){let F=qO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=qO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return BO(Y,W)}catch(K){let W=qO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var kc0=()=>{};function OO1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function zr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){OO1(Y);let K=await Promise.race([G,Cm6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function zv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await DO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,zO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=BO(G,Y);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await zr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await zr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())OO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Os(W,H,$)}}async function NO1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=kB(W,await DO1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=kB(W,J.newContext({interruptAfterMs:X}),0);const K=kB(W,zO1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=BO(G,Y);G.setProp(G.global,"input",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await zr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (input). Got ${D}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await zr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())OO1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:qO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{Os(W,H,$)}}var Cm6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var vc0=j(()=>{Sc0();kc0()});var Dr=j(()=>{vc0()});async function Rm6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function _c0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Im6(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let U=await Q.createMCPProxy(q);return{connection:q,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,U),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,U])=>{try{let D=(await U.proxy.listTools()).tools,L=X.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);D=D.filter((E)=>w.has(E.name))}return{connectionId:q,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,z),null}})),Z=new Set,H=[],$=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=q.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:z}}),$.set(L.name,U)}}let F=async(q,U)=>{let z=$.get(q);if(!z)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:U})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function NP(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await Rm6(J,Y);else X=await _c0(Q.id,Y)}else X=await _c0(Q.id,Y);return Im6(X,Y)}function jm6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function Sm6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Or(Y,Q,X){let J=jm6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:Sm6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Nr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Lr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return zv({code:Y,tools:J,timeoutMs:X})}function Dv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function qB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function DF(Y){let Q=new Set(km6);return Y.filter((X)=>!Q.has(X.name))}var km6;var UO=j(()=>{Dr();km6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var LO1;var yc0=j(()=>{F4();Uv();UO();LO1=t1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wc0,outputSchema:Ac0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await NP(Q),J=Or(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var MO1;var fc0=j(()=>{F4();Uv();UO();MO1=t1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Pc0,outputSchema:Ec0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return Nr(Y.tools,X.tools)}})});var wO1;var bc0=j(()=>{F4();Uv();UO();wO1=t1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:Tc0,outputSchema:Cc0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await NP(Q);return await Lr(Y.code,X,Y.timeoutMs)}})});var hc0=j(()=>{yc0();fc0();bc0();Uv()});var _m6,ym6,AO1;var xc0=j(()=>{QY();a1();F4();an();p$();_m6=B.object({data:_T.describe("Data for the new connection (id is auto-generated if not provided)")}),ym6=B.object({item:Y5.describe("The created connection entity")}),AO1=t1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:_m6,outputSchema:ym6,handler:async(Y,Q)=>{z0(Q);let X=v0(Q);await Q.access.check();let J=TY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=AU(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=PU($)}let K=await EA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var fm6,bm6,gc0;var uc0=j(()=>{a1();MG();fm6=pH.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),bm6=cH("assistant",fm6),gc0=[...bm6]});var Ov,OF,lc0,hm6,xm6,dc0,gm6,um6,mm6,lm6,dm6,pm6,pc0,cm6,nm6,im6,am6,rm6,om6,sm6,tm6,em6,Yl6,vF9,Ql6,_F9,mc0,Xl6,Jl6,PO1,Nv;var Mr=j(()=>{a1();xD();MG();Ov=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),Ov),B.array(Ov)])),OF=B.record(B.string(),B.record(B.string(),Ov)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),lc0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:OF}),hm6=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),xm6=B.string().describe("File data as URL string"),dc0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:xm6,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:OF}),gm6=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),um6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:OF}),mm6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),lm6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:OF}),dm6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),pm6=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:Ov}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:Ov}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))}),B.object({type:B.literal("execution-denied"),reason:B.string().optional()}),B.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),pc0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:pm6.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:OF}),cm6=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),nm6=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),im6=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:OF}),am6=B.object({role:B.literal("user"),content:B.array(B.union([lc0,dc0])).describe("User message content parts (text or file)"),providerOptions:OF}),rm6=B.object({role:B.literal("assistant"),content:B.array(B.union([lc0,dc0,um6,lm6,pc0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:OF}),om6=B.object({role:B.literal("tool"),content:B.array(pc0).describe("Tool message content (tool results)"),providerOptions:OF}),sm6=B.union([im6,am6,rm6,om6]),tm6=B.array(sm6).describe("A list of messages forming the prompt"),em6=B.object({prompt:tm6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),Yl6=B.object({content:B.array(B.union([hm6,gm6,mm6,dm6,cm6,nm6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),vF9=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Ql6=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),_F9=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),mc0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:em6}),Xl6=pH.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Jl6=cH("llm",Xl6,{readOnly:!0}),PO1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:Ql6},{name:"LLM_DO_STREAM",inputSchema:mc0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:mc0,outputSchema:Yl6},...Jl6],Nv=lH(PO1)});function LP(){return!1}function wr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function MP(Y,Q){let X=J91(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:Gl6,bindings:["OBJECT_STORAGE"],status:"active"}}var Gl6;var Ar=j(()=>{Gi();QY();a1();Gl6=tS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function Zl6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function BB(Y){return typeof Y==="string"||typeof Y==="number"}function Pr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Pr(Y,$));case"or":return H.some(($)=>Pr(Y,$));case"not":return!H.every(($)=>Pr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=EO1(Y,K);switch(J){case"eq":return W===G;case"gt":return BB(W)&&BB(G)&&W>G;case"gte":return BB(W)&&BB(G)&&W>=G;case"lt":return BB(W)&&BB(G)&&W<G;case"lte":return BB(W)&&BB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=Zl6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function EO1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function Kl6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=EO1(X,K),Z=EO1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var Wl6,Hl6,$l6,TO1;var cc0=j(()=>{Yk();uc0();MG();Mr();Gi();QY();a1();F4();Ar();p$();Wl6={LLM:PO1,ASSISTANTS:gc0,OBJECT_STORAGE:tS};Hl6=lZ.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),$l6=n$(Y5),TO1=t1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Hl6,outputSchema:$l6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=Wl6[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?Yi(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(LP()){let q=X7(),U=IY.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=MP(X.id,q);K.unshift(z)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((q)=>Pr(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=Kl6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Fl6,CO1;var nc0=j(()=>{MG();F4();Ar();p$();Fl6=hS(Y5),CO1=t1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:bS,outputSchema:Fl6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),LP()&&wr(Y.id,X.id))return{item:MP(X.id,X7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Er=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function ic0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Vl6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function ql6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function RO1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Vl6(J);if(!G)continue;let[K,W]=G,Z=Er(K,Y),H=ql6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function ac0(Y,Q){let X=RO1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var IO1=()=>{};import{randomBytes as Bl6}from"crypto";function rc0(){if(Lv)return Lv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Lv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Lv=new Uint8Array(Bl6(32));return Lv}async function oc0(Y,Q="5m"){let X=rc0();return await new s5(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function sc0(Y){try{let Q=rc0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Lv=null;var jO1=j(()=>{t5();wP()});async function tc0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class NF{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=J9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Tr=j(()=>{F7()});async function Mv(Y,Q,X){let J=Y.id,G=RO1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await oc0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new NF(Q.db,Q.vault),q=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!q,hasRefresh:!!q?.refreshToken,expiresAt:q?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),q){let U=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await tc0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),F=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=q.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var SO1=j(()=>{IO1();jO1();Tr()});function Cr(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new eJ({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var kO1=j(()=>{LU()});function ec0(Y){let Q=new _S({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Yn0=j(()=>{mq1()});class wv{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Av(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Qn0="mcp.mesh";var Xn0,vO1,LF;var Pv=j(()=>{Xn0=class Xn0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};vO1=class vO1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};LF=class LF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Xn0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new vO1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new vO1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Qn0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Ul6="mcp.mesh",AP;var Jn0=j(()=>{Pv();AP=class AP extends wv{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new LF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Ul6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function Wn0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function yO1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function fO1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function bO1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function zl6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Dl6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1473
1473
  `);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function _O1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(f3(Y.connectionId))return;let G=yO1(Y.request.params.arguments),K=fO1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map(($)=>$.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function Zn0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let $=await Z(),F=Q.organization?.id;if(X&&F){let V=$.clone();(async()=>{try{let{text:q,truncated:U}=await zl6(V,Gn0),z=Date.now()-H,D=V.headers.get("content-type")??"",L=q;if(D.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=$.status>=400,E=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof E==="string"&&E?E:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${$.status} ${$.statusText}`.trim():U?`Response body truncated to ${Gn0} bytes`:void 0,C=bO1(L),P=Dl6(q);if(P)Object.assign(C,P);await _O1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:T,durationMs:z})}catch(q){let U=Date.now()-H;await _O1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:U})}})()}return $}catch($){let F=$,V=Date.now()-H;throw await _O1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:F.message,durationMs:V}),$}}}var Gn0=262144;var hO1=j(()=>{QY()});var PP;var Kn0=j(()=>{WI();hO1();PP=class PP extends wv{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,$=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let F="error"in Y,V=F?Y.error:Y.result,q=F?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record($,{"connection.id":J,"tool.name":W,status:F?"error":"success"}),F)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(F&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:q,duration:$,isError:Boolean(F)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:$}=Y;if(!ul().enabled)return;let V=Q.organization?.id;if(!V)return;let q=Wn0(Z),U=bO1(Z),z=yO1(W),D=fO1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:$,errorMessage:q,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:D})}catch(L){console.error("[MonitoringTransport] Failed to log to database:",L)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var Hn0=j(()=>{Jn0();Kn0()});async function $n0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!jK(K))throw Error("STDIO connection missing parameters");let W=ec0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=Av(W,(Z)=>new AP(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new PP(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Ol6(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Mv(Y,Q,X);console.log("[EventBus:Debug] outbound HTTP client",{connectionId:J,url:Y.connection_url,superUser:X,headerKeys:Object.keys(K)});let W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new qV(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Av(Z,(H)=>new AP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new PP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Mv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new fD(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Av(Z,(H)=>new AP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new PP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var Ol6;var Fn0=j(()=>{p$();pn();vT();SO1();kO1();Yn0();Hn0();Ol6=Cr()});function UB(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function Bn0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function Ev(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var xO1,oV9,Q3,Vn0,qn0;var MF=j(()=>{a1();xO1=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),oV9=B.object({"tool.fn":B.string().describe("JavaScript ES module code that exports a default async function")}),Q3=B.object({id:B.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description of what the tool does"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:xO1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:B.string().describe("When the virtual tool was created"),updated_at:B.string().describe("When the virtual tool was last updated")}),Vn0=B.object({name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema for output"),annotations:xO1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),qn0=B.object({name:B.string().min(1).max(255).optional().describe("New tool name"),description:B.string().nullable().optional().describe("New description (null to clear)"),inputSchema:B.record(B.string(),B.unknown()).optional().describe("New input schema"),outputSchema:B.record(B.string(),B.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:xO1.nullable().optional().describe("New annotations (null to clear)"),code:B.string().optional().describe("New JavaScript code"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function zO(Y){return(Q)=>{if(Q instanceof u0&&Q.code===o0.MethodNotFound)return Y;throw Q}}var gO1=j(()=>{kQ()});class Un0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function EP(Y){return new Un0(Y)}function Nl6(Y,Q,X){let J=new eJ({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=y5(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return DO(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,$,F)=>{return(await K()).callTool(H,$,F)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,$)=>{return(await K()).getPrompt(H,$)},J.readResource=async(H,$)=>{return(await K()).readResource(H,$)},J.callStreamableTool=async(H,$)=>{let F=await K();if("callStreamableTool"in F&&typeof F.callStreamableTool==="function")return F.callStreamableTool(H,$);let V=await F.callTool({name:H,arguments:$});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function Ll6(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,Nl6(G,Q,X));return J}async function zn0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var TP;var uO1=j(()=>{CP();gO1();LU();Dr();MF();TP=class TP extends eJ{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=Ll6(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=EP(()=>this.loadToolsCache()),this._cachedResources=EP(()=>this.loadCache("resources")),this._cachedPrompts=EP(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((F)=>F.tools),$=this._selectionMap.get(W);if($?.selected_tools?.length){let F=new Set($.selected_tools);H=H.filter((V)=>F.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,F=this._connections.get(Z)?.title??"";for(let V of H){let q=V.name;if(J.has(q))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:F,...V?._meta}};X.push(U),J.set(q,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(zO({resources:[]})).then((F)=>F.resources):await W.listPrompts().catch(zO({prompts:[]})).then((F)=>F.prompts),H=this._selectionMap.get(K),$=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[$]?.length){let F=new Set(H[$]);return{connectionId:K,data:Z.filter((V)=>F.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,$=this._connections.get(W)?.title??"";for(let F of Z){let V=F.name??F.uri;if(G.has(V))continue;let q={...F,_meta:{connectionId:W,connectionTitle:$,...F?._meta}};J.push(q),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=Bn0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let $=J.get(H);if(!$)continue;W[Z]=async(F)=>{let V=await $.callTool({name:Z,arguments:F});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let q=V.content;if(q?.[0]?.type==="text"&&q[0].text)try{return JSON.parse(q[0].text)}catch{return q[0].text}return V}}try{let H=`
1474
1474
  const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
1475
1475
  export default async (tools) => {
@@ -1467,7 +1467,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
1467
1467
  ${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
1468
1468
 
1469
1469
  Stack trace:
1470
- ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function hN(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=hN(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=hN(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=hN(Y,H);Z.resolve(F),F.dispose()}catch(F){let $=bN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=bN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return hN(Y,W)}catch(K){let W=bN(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var cy0=()=>{};function iy0(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function ny0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){iy0(Y);let K=await Promise.race([G,b24(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function sR({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=VI(W,await dy0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=VI(W,J.newContext({interruptAfterMs:X}),0);const K=VI(W,gy0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),B=hN(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await ny0(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),O=G.typeof(z);if(O!=="function")return z.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(z,G.undefined,B);B.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(M),P=await ny0(G,w,X);w.dispose();let j=G.unwrapResult(P);if(G.runtime.hasPendingJob())iy0(G);let C=G.dump(j);return j.dispose(),{returnValue:C,consoleLogs:K.logs}}catch($){return console.log($),{error:bN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{uV1(W,H,F)}}var b24=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var ay0=S(()=>{py0();cy0()});var J$1=S(()=>{ay0()});async function h24(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function ry0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function x24(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let O=(await U.proxy.listTools()).tools,M=X.get(B);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);O=O.filter((P)=>w.has(P.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:O}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,z),null}})),Z=new Set,H=[],F=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:z,tools:O}=B.value;for(let M of O){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:U,connectionTitle:z}}),F.set(M.name,U)}}let $=async(B,U)=>{let z=F.get(B);if(!z)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let O=G.get(z);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await O.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:$}}async function xN(Y){let Q=B0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await h24(J,Y);else X=await ry0(Q.id,Y)}else X=await ry0(Q.id,Y);return x24(X,Y)}function g24(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function u24(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function $p(Y,Q,X){let J=g24(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:u24(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Vp(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function qp(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return sR({code:Y,tools:J,timeoutMs:X})}function tR(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function M$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function m3(Y){let Q=new Set(m24);return Y.filter((X)=>!Q.has(X.name))}var m24;var WU=S(()=>{J$1();m24=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var G$1;var oy0=S(()=>{k0();oR();WU();G$1=v1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ky0,outputSchema:yy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q),J=$p(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var W$1;var sy0=S(()=>{k0();oR();WU();W$1=v1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:fy0,outputSchema:by0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return Vp(Y.tools,X.tools)}})});var Z$1;var ty0=S(()=>{k0();oR();WU();Z$1=v1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:hy0,outputSchema:xy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return await qp(Y.code,X,Y.timeoutMs)}})});var ey0=S(()=>{oy0();sy0();ty0();oR()});var d24,p24,K$1;var Yf0=S(()=>{zY();y1();k0();dm();L3();d24=q.object({data:CA.describe("Data for the new connection (id is auto-generated if not provided)")}),p24=q.object({item:P5.describe("The created connection entity")}),K$1=v1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:d24,outputSchema:p24,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let F=LV(G.connection_url);if(!F)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let $=await Q.storage.virtualMcps.findById(F);if(!$)throw Error(`Virtual MCP not found: ${F}`);if($.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=NV(F)}let K=await iL({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,h9.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var c24,n24,Qf0;var Xf0=S(()=>{y1();gX();c24=yZ.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),n24=fZ("assistant",c24),Qf0=[...n24]});var eR,l3,Gf0,i24,a24,Wf0,r24,o24,s24,t24,e24,YE4,Zf0,QE4,XE4,JE4,GE4,WE4,ZE4,KE4,HE4,FE4,$E4,in8,VE4,an8,Jf0,qE4,BE4,H$1,rn8;var Kf0=S(()=>{y1();_B();gX();eR=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),eR),q.array(eR)])),l3=q.record(q.string(),q.record(q.string(),eR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Gf0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:l3}),i24=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),a24=q.string().describe("File data as URL string"),Wf0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:a24,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:l3}),r24=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),o24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:l3}),s24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),t24=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:l3}),e24=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),YE4=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:eR}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:eR}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Zf0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:YE4.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:l3}),QE4=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),XE4=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),JE4=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:l3}),GE4=q.object({role:q.literal("user"),content:q.array(q.union([Gf0,Wf0])).describe("User message content parts (text or file)"),providerOptions:l3}),WE4=q.object({role:q.literal("assistant"),content:q.array(q.union([Gf0,Wf0,o24,t24,Zf0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:l3}),ZE4=q.object({role:q.literal("tool"),content:q.array(Zf0).describe("Tool message content (tool results)"),providerOptions:l3}),KE4=q.union([JE4,GE4,WE4,ZE4]),HE4=q.array(KE4).describe("A list of messages forming the prompt"),FE4=q.object({prompt:HE4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),$E4=q.object({content:q.array(q.union([i24,r24,s24,e24,QE4,XE4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),in8=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),VE4=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),an8=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Jf0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:FE4}),qE4=yZ.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),BE4=fZ("llm",qE4,{readOnly:!0}),H$1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:VE4},{name:"LLM_DO_STREAM",inputSchema:Jf0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Jf0,outputSchema:$E4},...BE4],rn8=vZ(H$1)});function gN(){return!1}function Bp(Y,Q){return Y===h9.DEV_ASSETS(Q)}function uN(Y,Q){let X=Bt(Q,Y),J=new Date().toISOString();return{id:X.id??h9.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:UE4,bindings:["OBJECT_STORAGE"],status:"active"}}var UE4;var Up=S(()=>{em();zY();y1();UE4=uC.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function DE4(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function w$(Y){return typeof Y==="string"||typeof Y==="number"}function zp(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>zp(Y,F));case"or":return H.some((F)=>zp(Y,F));case"not":return!H.every((F)=>zp(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=F$1(Y,K);switch(J){case"eq":return W===G;case"gt":return w$(W)&&w$(G)&&W>G;case"gte":return w$(W)&&w$(G)&&W>=G;case"lt":return w$(W)&&w$(G)&&W<G;case"lte":return w$(W)&&w$(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=DE4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function F$1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function OE4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=F$1(X,K),Z=F$1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var zE4,LE4,NE4,$$1;var Hf0=S(()=>{Yl();Xf0();gX();Kf0();em();zY();y1();k0();Up();L3();zE4={LLM:H$1,ASSISTANTS:Qf0,OBJECT_STORAGE:uC};LE4=dG.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),NE4=M3(P5),$$1=v1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:LE4,outputSchema:NE4,handler:async(Y,Q)=>{await Q.access.check();let X=B0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=zE4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?rm(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(gN()){let B=AG(),U=h9.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=uN(X.id,B);K.unshift(z)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>zp(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=OE4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,$=W.slice(H,H+F),V=H+F<Z;return{items:$,totalCount:Z,hasMore:V}}})});var ME4,V$1;var Ff0=S(()=>{gX();k0();Up();L3();ME4=TC(P5),V$1=v1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EC,outputSchema:ME4,handler:async(Y,Q)=>{let X=B0(Q);if(await Q.access.check(),gN()&&Bp(Y.id,X.id))return{item:uN(X.id,AG())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Dp=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function $f0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function wE4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function AE4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function q$1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=wE4(J);if(!G)continue;let[K,W]=G,Z=Dp(K,Y),H=AE4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Vf0(Y,Q){let X=q$1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var B$1=()=>{};import{randomBytes as PE4}from"crypto";function EE4(){if(YI)return YI;let Y=process.env.MESH_JWT_SECRET??t9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)YI=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),YI=new Uint8Array(PE4(32));return YI}async function qf0(Y,Q="5m"){let X=EE4();return await new DX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var YI=null;var Bf0=S(()=>{OX();Op()});async function Uf0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class QI{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=Y$("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var U$1=S(()=>{DC()});async function XI(Y,Q,X){let J=Y.id,G=q$1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await qf0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},$=null,V=new QI(Q.db,Q.vault),B=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!B,hasRefresh:!!B?.refreshToken,expiresAt:B?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let O=await Uf0(B);if(O.success&&O.accessToken)await V.upsert({connectionId:J,accessToken:O.accessToken,refreshToken:O.refreshToken??B.refreshToken,scope:O.scope??B.scope,expiresAt:O.expiresIn?new Date(Date.now()+O.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),$=O.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${O.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=B.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var z$1=S(()=>{B$1();Bf0();U$1()});function zf0(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new sX({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var Df0=S(()=>{Pz()});function Of0(Y){let Q=new wC({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Lf0=S(()=>{uZ1()});class JI{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function GI(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Nf0="mcp.mesh";var Mf0,D$1,WI;var O$1=S(()=>{Mf0=class Mf0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};D$1=class D$1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};WI=class WI{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Mf0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new D$1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new D$1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Nf0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var TE4="mcp.mesh",mN;var wf0=S(()=>{O$1();mN=class mN extends JI{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new WI(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[TE4]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function Pf0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function N$1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function M$1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function w$1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function CE4(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:F}=await J.read();if(F)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let $=Q-(W-H.byteLength);if($>0)Z.push(G.decode(H.slice(0,$),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function RE4(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1470
+ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function hN(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=hN(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=hN(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=hN(Y,H);Z.resolve(F),F.dispose()}catch(F){let $=bN(F),V=Y.newString(`Promise resolution error: ${$}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let F=bN(H),$=Y.newString(`Promise rejection: ${F}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return hN(Y,W)}catch(K){let W=bN(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var cy0=()=>{};function iy0(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function ny0(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){iy0(Y);let K=await Promise.race([G,b24(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function sR({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=VI(W,await dy0({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=VI(W,J.newContext({interruptAfterMs:X}),0);const K=VI(W,gy0(G),0);try{let $=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult($),B=hN(G,Y);G.setProp(G.global,"tools",B);let U=G.runtime.hasPendingJob()?G.unwrapResult(await ny0(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),O=G.typeof(z);if(O!=="function")return z.dispose(),U.dispose(),B.dispose(),{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let M=G.callFunction(z,G.undefined,B);B.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(M),P=await ny0(G,w,X);w.dispose();let j=G.unwrapResult(P);if(G.runtime.hasPendingJob())iy0(G);let C=G.dump(j);return j.dispose(),{returnValue:C,consoleLogs:K.logs}}catch($){return console.log($),{error:bN($),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{uV1(W,H,F)}}var b24=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var ay0=S(()=>{py0();cy0()});var J$1=S(()=>{ay0()});async function h24(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function ry0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function x24(Y,Q){let X=new Map;for(let B of Y)X.set(B.connection.id,B);let J=Y.map((B)=>B.connection),G=new Map,K=await Promise.allSettled(J.map(async(B)=>{try{let U=await Q.createMCPProxy(B);return{connection:B,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${B.id}:`,U),null}}));for(let B of K)if(B.status==="fulfilled"&&B.value)G.set(B.value.connection.id,B.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([B,U])=>{try{let O=(await U.proxy.listTools()).tools,M=X.get(B);if(M?.selectedTools&&M.selectedTools.length>0){let w=new Set(M.selectedTools);O=O.filter((P)=>w.has(P.name))}return{connectionId:B,connectionTitle:U.connection.title,tools:O}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${B}:`,z),null}})),Z=new Set,H=[],F=new Map;for(let B of W){if(B.status!=="fulfilled"||!B.value)continue;let{connectionId:U,connectionTitle:z,tools:O}=B.value;for(let M of O){if(Z.has(M.name))continue;Z.add(M.name),H.push({...M,_meta:{connectionId:U,connectionTitle:z}}),F.set(M.name,U)}}let $=async(B,U)=>{let z=F.get(B);if(!z)return{content:[{type:"text",text:`Tool not found: ${B}`}],isError:!0};let O=G.get(z);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${B}`}],isError:!0};return await O.proxy.callTool({name:B,arguments:U})},V=[];for(let[,B]of G)V.push(B.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:$}}async function xN(Y){let Q=B0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await h24(J,Y);else X=await ry0(Q.id,Y)}else X=await ry0(Q.id,Y);return x24(X,Y)}function g24(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function u24(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function $p(Y,Q,X){let J=g24(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:u24(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Vp(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function qp(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return sR({code:Y,tools:J,timeoutMs:X})}function tR(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function M$(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function m3(Y){let Q=new Set(m24);return Y.filter((X)=>!Q.has(X.name))}var m24;var WU=S(()=>{J$1();m24=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var G$1;var oy0=S(()=>{k0();oR();WU();G$1=v1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ky0,outputSchema:yy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q),J=$p(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var W$1;var sy0=S(()=>{k0();oR();WU();W$1=v1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:fy0,outputSchema:by0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return Vp(Y.tools,X.tools)}})});var Z$1;var ty0=S(()=>{k0();oR();WU();Z$1=v1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:hy0,outputSchema:xy0,handler:async(Y,Q)=>{o1(Q),B0(Q),await Q.access.check();let X=await xN(Q);return await qp(Y.code,X,Y.timeoutMs)}})});var ey0=S(()=>{oy0();sy0();ty0();oR()});var d24,p24,K$1;var Yf0=S(()=>{zY();y1();k0();dm();L3();d24=q.object({data:CA.describe("Data for the new connection (id is auto-generated if not provided)")}),p24=q.object({item:P5.describe("The created connection entity")}),K$1=v1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:d24,outputSchema:p24,handler:async(Y,Q)=>{o1(Q);let X=B0(Q);await Q.access.check();let J=D9(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let F=LV(G.connection_url);if(!F)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let $=await Q.storage.virtualMcps.findById(F);if(!$)throw Error(`Virtual MCP not found: ${F}`);if($.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=NV(F)}let K=await iL({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,h9.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var c24,n24,Qf0;var Xf0=S(()=>{y1();gX();c24=yZ.extend({avatar:q.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:q.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:q.string().describe("Virtual MCP ID to use for this assistant"),model:q.object({id:q.string().describe("Model ID"),connectionId:q.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),n24=fZ("assistant",c24),Qf0=[...n24]});var eR,l3,Gf0,i24,a24,Wf0,r24,o24,s24,t24,e24,YE4,Zf0,QE4,XE4,JE4,GE4,WE4,ZE4,KE4,HE4,FE4,$E4,in8,VE4,an8,Jf0,qE4,BE4,H$1,rn8;var Kf0=S(()=>{y1();_B();gX();eR=q.lazy(()=>q.union([q.null(),q.string(),q.number(),q.boolean(),q.record(q.string(),eR),q.array(eR)])),l3=q.record(q.string(),q.record(q.string(),eR)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Gf0=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerOptions:l3}),i24=q.object({type:q.literal("text"),text:q.string().describe("The text content"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),a24=q.string().describe("File data as URL string"),Wf0=q.object({type:q.literal("file"),filename:q.string().optional().describe("Optional filename of the file"),data:a24,mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:l3}),r24=q.object({type:q.literal("file"),mediaType:q.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:q.string().describe("Generated file data as base64 encoded string")}),o24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerOptions:l3}),s24=q.object({type:q.literal("reasoning"),text:q.string().describe("The reasoning text"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),t24=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call, used to match with tool result"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:l3}),e24=q.object({type:q.literal("tool-call"),toolCallId:q.string().describe("ID of the tool call"),toolName:q.string().describe("Name of the tool being called"),input:q.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:q.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),YE4=q.union([q.object({type:q.literal("text"),value:q.string()}),q.object({type:q.literal("json"),value:eR}),q.object({type:q.literal("error-text"),value:q.string()}),q.object({type:q.literal("error-json"),value:eR}),q.object({type:q.literal("content"),value:q.array(q.union([q.object({type:q.literal("text"),text:q.string().describe("Text content")}),q.object({type:q.literal("media"),data:q.string().describe("Base-64 encoded media data"),mediaType:q.string().describe("IANA media type")})]))}),q.object({type:q.literal("execution-denied"),reason:q.string().optional()}),q.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Zf0=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),output:YE4.describe("Result of the tool call"),result:q.unknown().describe("Unknown result of the tool call"),providerOptions:l3}),QE4=q.object({type:q.literal("tool-result"),toolCallId:q.string().describe("ID of the tool call that this result is associated with"),toolName:q.string().describe("Name of the tool that generated this result"),result:q.any().describe("Result of the tool call (JSON-serializable)"),isError:q.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:q.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),XE4=q.union([q.object({type:q.literal("source"),sourceType:q.literal("url"),id:q.string().describe("The ID of the source"),url:q.string().describe("The URL of the source"),title:q.string().optional().describe("The title of the source"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")}),q.object({type:q.literal("source"),sourceType:q.literal("document"),id:q.string().describe("The ID of the source"),mediaType:q.string().describe("IANA media type of the document (e.g., application/pdf)"),title:q.string().describe("The title of the document"),filename:q.string().optional().describe("Optional filename of the document"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata")})]),JE4=q.object({role:q.literal("system"),content:q.string().describe("System message content"),providerOptions:l3}),GE4=q.object({role:q.literal("user"),content:q.array(q.union([Gf0,Wf0])).describe("User message content parts (text or file)"),providerOptions:l3}),WE4=q.object({role:q.literal("assistant"),content:q.array(q.union([Gf0,Wf0,o24,t24,Zf0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:l3}),ZE4=q.object({role:q.literal("tool"),content:q.array(Zf0).describe("Tool message content (tool results)"),providerOptions:l3}),KE4=q.union([JE4,GE4,WE4,ZE4]),HE4=q.array(KE4).describe("A list of messages forming the prompt"),FE4=q.object({prompt:HE4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:q.number().optional().describe("Maximum number of tokens to generate"),temperature:q.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:q.number().optional().describe("Nucleus sampling parameter"),topK:q.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:q.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:q.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:q.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:q.array(q.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:q.union([q.object({type:q.literal("text")}),q.object({type:q.literal("json"),schema:q.any().optional().describe("JSON schema that the generated output should conform to"),name:q.string().optional().describe("Name of output that should be generated"),description:q.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:q.array(q.any()).optional().describe("The tools that are available for the model"),toolChoice:q.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:q.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:q.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:q.any().optional().describe("Additional provider-specific options")}),$E4=q.object({content:q.array(q.union([i24,r24,s24,e24,QE4,XE4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:q.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:q.looseObject({inputTokens:q.number().optional(),outputTokens:q.number().optional(),totalTokens:q.number().optional(),reasoningTokens:q.number().optional()}).describe("Usage information for the language model call"),providerMetadata:q.any().optional().describe("Additional provider-specific metadata"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({id:q.string().optional().describe("ID for the generated response"),timestamp:q.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:q.string().optional().describe("The ID of the response model that was used"),headers:q.record(q.string(),q.string()).optional().describe("Response headers"),body:q.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:q.array(q.any()).describe("Warnings for the call, e.g. unsupported settings")}),in8=q.object({stream:q.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:q.object({body:q.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:q.object({headers:q.record(q.string(),q.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),VE4=q.object({supportedUrls:q.record(q.string(),q.array(q.string())).describe("Supported URL patterns by media type for the provider")}),an8=q.object({modelId:q.string().describe("The ID of the model"),logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Jf0=q.object({modelId:q.string().describe("The ID of the model"),callOptions:FE4}),qE4=yZ.extend({logo:q.string().nullable(),description:q.string().nullable(),capabilities:q.array(q.string()),limits:q.object({contextWindow:q.number(),maxOutputTokens:q.number()}).nullable(),costs:q.object({input:q.number(),output:q.number()}).nullable(),provider:q.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),BE4=fZ("llm",qE4,{readOnly:!0}),H$1=[{name:"LLM_METADATA",inputSchema:q.object({modelId:q.string().describe("The ID of the model")}),outputSchema:VE4},{name:"LLM_DO_STREAM",inputSchema:Jf0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Jf0,outputSchema:$E4},...BE4],rn8=vZ(H$1)});function gN(){return!1}function Bp(Y,Q){return Y===h9.DEV_ASSETS(Q)}function uN(Y,Q){let X=Bt(Q,Y),J=new Date().toISOString();return{id:X.id??h9.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:UE4,bindings:["OBJECT_STORAGE"],status:"active"}}var UE4;var Up=S(()=>{em();zY();y1();UE4=uC.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:q.toJSONSchema(Y.inputSchema),outputSchema:q.toJSONSchema(Y.outputSchema)}))});function DE4(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function w$(Y){return typeof Y==="string"||typeof Y==="number"}function zp(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every((F)=>zp(Y,F));case"or":return H.some((F)=>zp(Y,F));case"not":return!H.every((F)=>zp(Y,F));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=F$1(Y,K);switch(J){case"eq":return W===G;case"gt":return w$(W)&&w$(G)&&W>G;case"gte":return w$(W)&&w$(G)&&W>=G;case"lt":return w$(W)&&w$(G)&&W<G;case"lte":return w$(W)&&w$(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=DE4(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function F$1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function OE4(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=F$1(X,K),Z=F$1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var zE4,LE4,NE4,$$1;var Hf0=S(()=>{Yl();Xf0();gX();Kf0();em();zY();y1();k0();Up();L3();zE4={LLM:H$1,ASSISTANTS:Qf0,OBJECT_STORAGE:uC};LE4=dG.extend({binding:q.union([q.object({}).passthrough(),q.string()]).optional(),include_virtual:q.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),NE4=M3(P5),$$1=v1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:LE4,outputSchema:NE4,handler:async(Y,Q)=>{await Q.access.check();let X=B0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=zE4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?rm(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(gN()){let B=AG(),U=h9.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=uN(X.id,B);K.unshift(z)}}let W=G?await Promise.all(K.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((B)=>zp(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=OE4(W,Y.orderBy);let Z=W.length,H=Y.offset??0,F=Y.limit??100,$=W.slice(H,H+F),V=H+F<Z;return{items:$,totalCount:Z,hasMore:V}}})});var ME4,V$1;var Ff0=S(()=>{gX();k0();Up();L3();ME4=TC(P5),V$1=v1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EC,outputSchema:ME4,handler:async(Y,Q)=>{let X=B0(Q);if(await Q.access.check(),gN()&&Bp(Y.id,X.id))return{item:uN(X.id,AG())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var Dp=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function $f0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function wE4(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function AE4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function q$1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=wE4(J);if(!G)continue;let[K,W]=G,Z=Dp(K,Y),H=AE4(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Vf0(Y,Q){let X=q$1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var B$1=()=>{};import{randomBytes as PE4}from"crypto";function EE4(){if(YI)return YI;let Y=process.env.MESH_JWT_SECRET??t9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)YI=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),YI=new Uint8Array(PE4(32));return YI}async function qf0(Y,Q="5m"){let X=EE4();return await new DX(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}var YI=null;var Bf0=S(()=>{OX();Op()});async function Uf0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class QI{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=Y$("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var U$1=S(()=>{DC()});async function XI(Y,Q,X){let J=Y.id,G=q$1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await qf0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},$=null,V=new QI(Q.db,Q.vault),B=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!B,hasRefresh:!!B?.refreshToken,expiresAt:B?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),B){let U=!!B.refreshToken&&!!B.tokenEndpoint;if(V.isExpired(B,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let O=await Uf0(B);if(O.success&&O.accessToken)await V.upsert({connectionId:J,accessToken:O.accessToken,refreshToken:O.refreshToken??B.refreshToken,scope:O.scope??B.scope,expiresAt:O.expiresIn?new Date(Date.now()+O.expiresIn*1000):null,clientId:B.clientId,clientSecret:B.clientSecret,tokenEndpoint:B.tokenEndpoint}),$=O.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${O.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else $=B.accessToken}if(!$&&Y.connection_token)$=Y.connection_token;if($)F.Authorization=`Bearer ${$}`;if(W)F["x-mesh-token"]=W;return F}var z$1=S(()=>{B$1();Bf0();U$1()});function zf0(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new sX({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var Df0=S(()=>{Pz()});function Of0(Y){let Q=new wC({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Lf0=S(()=>{uZ1()});class JI{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function GI(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Nf0="mcp.mesh";var Mf0,D$1,WI;var O$1=S(()=>{Mf0=class Mf0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};D$1=class D$1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};WI=class WI{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Mf0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new D$1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new D$1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Nf0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var TE4="mcp.mesh",mN;var wf0=S(()=>{O$1();mN=class mN extends JI{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new WI(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[TE4]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function Pf0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function N$1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function M$1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function w$1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function CE4(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:F}=await J.read();if(F)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let $=Q-(W-H.byteLength);if($>0)Z.push(G.decode(H.slice(0,$),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function RE4(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1471
1471
  `);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function L$1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(OV(Y.connectionId))return;let G=N$1(Y.request.params.arguments),K=M$1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map((F)=>F.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function Ef0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),$=Q.organization?.id;if(X&&$){let V=F.clone();(async()=>{try{let{text:B,truncated:U}=await CE4(V,Af0),z=Date.now()-H,O=V.headers.get("content-type")??"",M=B;if(O.includes("application/json"))try{M=B.length?JSON.parse(B):null}catch{M=B}let w=F.status>=400,P=w&&M&&typeof M==="object"&&"error"in M?M.error:void 0,j=typeof P==="string"&&P?P:w&&typeof M==="string"&&M.trim()?M.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():U?`Response body truncated to ${Af0} bytes`:void 0,C=w$1(M),E=RE4(B);if(E)Object.assign(C,E);await L$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:j,durationMs:z})}catch(B){let U=Date.now()-H;await L$1({ctx:Q,enabled:X,organizationId:$,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${B.message}`,durationMs:U})}})()}return F}catch(F){let $=F,V=Date.now()-H;throw await L$1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:$.message,durationMs:V}),F}}}var Af0=262144;var A$1=S(()=>{zY()});var lN;var Tf0=S(()=>{xh();A$1();lN=class lN extends JI{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,F=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let $="error"in Y,V=$?Y.error:Y.result,B=$?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record(F,{"connection.id":J,"tool.name":W,status:$?"error":"success"}),$)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if($&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:B,duration:F,isError:Boolean($)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:F}=Y;if(!hh().enabled)return;let V=Q.organization?.id;if(!V)return;let B=Pf0(Z),U=w$1(Z),z=N$1(W),O=M$1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:F,errorMessage:B,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:O})}catch(M){console.error("[MonitoringTransport] Failed to log to database:",M)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var Cf0=S(()=>{wf0();Tf0()});async function Rf0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!NW(K))throw Error("STDIO connection missing parameters");let W=Of0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=GI(W,(Z)=>new mN(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new lN(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),IE4(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await XI(Y,Q,X);console.log("[EventBus:Debug] outbound HTTP client",{connectionId:J,url:Y.connection_url,superUser:X,headerKeys:Object.keys(K)});let W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new wH(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=GI(Z,(H)=>new mN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new lN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await XI(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new IB(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=GI(Z,(H)=>new mN(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new lN(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var IE4;var If0=S(()=>{L3();um();TA();z$1();Df0();Lf0();Cf0();IE4=zf0()});function _f0(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function vf0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}var P$1,qa8,pZ,jf0,Sf0;var A$=S(()=>{y1();P$1=q.object({title:q.string().optional(),readOnlyHint:q.boolean().optional(),destructiveHint:q.boolean().optional(),idempotentHint:q.boolean().optional(),openWorldHint:q.boolean().optional()}),qa8=q.object({"tool.fn":q.string().describe("JavaScript ES module code that exports a default async function")}),pZ=q.object({id:q.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description of what the tool does"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:P$1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:q.string().describe("When the virtual tool was created"),updated_at:q.string().describe("When the virtual tool was last updated")}),jf0=q.object({name:q.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:q.string().optional().describe("Human-readable description"),inputSchema:q.record(q.string(),q.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:q.record(q.string(),q.unknown()).optional().describe("JSON Schema for output"),annotations:P$1.optional().describe("MCP tool annotations"),code:q.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),Sf0=q.object({name:q.string().min(1).max(255).optional().describe("New tool name"),description:q.string().nullable().optional().describe("New description (null to clear)"),inputSchema:q.record(q.string(),q.unknown()).optional().describe("New input schema"),outputSchema:q.record(q.string(),q.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:P$1.nullable().optional().describe("New annotations (null to clear)"),code:q.string().optional().describe("New JavaScript code"),connection_dependencies:q.array(q.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function Lp(Y){return(Q)=>{if(Q instanceof w0&&Q.code===C0.MethodNotFound)return Y;throw Q}}var E$1=S(()=>{jY()});class kf0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function Np(Y){return new kf0(Y)}function jE4(Y,Q,X){let J=new sX({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=pN(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return C$1(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,F,$)=>{return(await K()).callTool(H,F,$)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,F)=>{return(await K()).getPrompt(H,F)},J.readResource=async(H,F)=>{return(await K()).readResource(H,F)},J.callStreamableTool=async(H,F)=>{let $=await K();if("callStreamableTool"in $&&typeof $.callStreamableTool==="function")return $.callStreamableTool(H,F);let V=await $.callTool({name:H,arguments:F});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function SE4(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,jE4(G,Q,X));return J}async function yf0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var dN;var T$1=S(()=>{R$1();E$1();Pz();J$1();A$();dN=class dN extends sX{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=SE4(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=Np(()=>this.loadToolsCache()),this._cachedResources=Np(()=>this.loadCache("resources")),this._cachedPrompts=Np(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then(($)=>$.tools),F=this._selectionMap.get(W);if(F?.selected_tools?.length){let $=new Set(F.selected_tools);H=H.filter((V)=>$.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,$=this._connections.get(Z)?.title??"";for(let V of H){let B=V.name;if(J.has(B))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:$,...V?._meta}};X.push(U),J.set(B,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(Lp({resources:[]})).then(($)=>$.resources):await W.listPrompts().catch(Lp({prompts:[]})).then(($)=>$.prompts),H=this._selectionMap.get(K),F=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[F]?.length){let $=new Set(H[F]);return{connectionId:K,data:Z.filter((V)=>$.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let $ of Z){let V=$.name??$.uri;if(G.has(V))continue;let B={...$,_meta:{connectionId:W,connectionTitle:F,...$?._meta}};J.push(B),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=vf0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let F=J.get(H);if(!F)continue;W[Z]=async($)=>{let V=await F.callTool({name:Z,arguments:$});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let B=V.content;if(B?.[0]?.type==="text"&&B[0].text)try{return JSON.parse(B[0].text)}catch{return B[0].text}return V}}try{let H=`
1472
1472
  const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
1473
1473
  export default async (tools) => {
@@ -1319,7 +1319,7 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
1319
1319
  ${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
1320
1320
 
1321
1321
  Stack trace:
1322
- ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=HO(Y,H);Z.resolve($),$.dispose()}catch($){let F=KO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=KO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HO(Y,W)}catch(K){let W=KO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Jp0=()=>{};function HD1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Yr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){HD1(Y);let K=await Promise.race([G,Nh6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Xv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}async function $D1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"input",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (input). Got ${D}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}var Nh6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Gp0=k(()=>{Xp0();Jp0()});var Qr=k(()=>{Gp0()});async function Lh6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function Wp0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Mh6(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let U=await Q.createMCPProxy(q);return{connection:q,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,U),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,U])=>{try{let D=(await U.proxy.listTools()).tools,L=X.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);D=D.filter((E)=>w.has(E.name))}return{connectionId:q,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,z),null}})),Z=new Set,H=[],$=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=q.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:z}}),$.set(L.name,U)}}let F=async(q,U)=>{let z=$.get(q);if(!z)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:U})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function $P(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await Lh6(J,Y);else X=await Wp0(Q.id,Y)}else X=await Wp0(Q.id,Y);return Mh6(X,Y)}function wh6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function Ah6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Xr(Y,Q,X){let J=wh6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:Ah6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Jr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Gr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Xv({code:Y,tools:J,timeoutMs:X})}function Jv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function GB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function KF(Y){let Q=new Set(Ph6);return Y.filter((X)=>!Q.has(X.name))}var Ph6;var $O=k(()=>{Qr();Ph6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var FD1;var Zp0=k(()=>{F4();Qv();$O();FD1=s1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:id0,outputSchema:ad0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q),J=Xr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var VD1;var Kp0=k(()=>{F4();Qv();$O();VD1=s1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:rd0,outputSchema:od0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return Jr(Y.tools,X.tools)}})});var qD1;var Hp0=k(()=>{F4();Qv();$O();qD1=s1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:sd0,outputSchema:td0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return await Gr(Y.code,X,Y.timeoutMs)}})});var $p0=k(()=>{Zp0();Kp0();Hp0();Qv()});var Th6,Ch6,BD1;var Fp0=k(()=>{KY();i1();F4();Sn();b$();Th6=B.object({data:PR.describe("Data for the new connection (id is auto-generated if not provided)")}),Ch6=B.object({item:W5.describe("The created connection entity")}),BD1=s1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Th6,outputSchema:Ch6,handler:async(Y,Q)=>{z0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=zz(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Dz($)}let K=await zA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var Rh6,Ih6,Vp0;var qp0=k(()=>{i1();MG();Rh6=bH.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Ih6=hH("assistant",Rh6),Vp0=[...Ih6]});var Gv,HF,Up0,jh6,Sh6,zp0,kh6,vh6,_h6,yh6,fh6,bh6,Dp0,hh6,xh6,gh6,uh6,mh6,lh6,dh6,ph6,ch6,nh6,CK9,ih6,RK9,Bp0,ah6,rh6,UD1,Wv;var Wr=k(()=>{i1();_D();MG();Gv=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),Gv),B.array(Gv)])),HF=B.record(B.string(),B.record(B.string(),Gv)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Up0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:HF}),jh6=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),Sh6=B.string().describe("File data as URL string"),zp0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:Sh6,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HF}),kh6=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),vh6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:HF}),_h6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),yh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HF}),fh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),bh6=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:Gv}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:Gv}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))}),B.object({type:B.literal("execution-denied"),reason:B.string().optional()}),B.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Dp0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:bh6.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:HF}),hh6=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),xh6=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),gh6=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:HF}),uh6=B.object({role:B.literal("user"),content:B.array(B.union([Up0,zp0])).describe("User message content parts (text or file)"),providerOptions:HF}),mh6=B.object({role:B.literal("assistant"),content:B.array(B.union([Up0,zp0,vh6,yh6,Dp0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HF}),lh6=B.object({role:B.literal("tool"),content:B.array(Dp0).describe("Tool message content (tool results)"),providerOptions:HF}),dh6=B.union([gh6,uh6,mh6,lh6]),ph6=B.array(dh6).describe("A list of messages forming the prompt"),ch6=B.object({prompt:ph6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),nh6=B.object({content:B.array(B.union([jh6,kh6,_h6,fh6,hh6,xh6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),CK9=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),ih6=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),RK9=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Bp0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:ch6}),ah6=bH.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),rh6=hH("llm",ah6,{readOnly:!0}),UD1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:ih6},{name:"LLM_DO_STREAM",inputSchema:Bp0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Bp0,outputSchema:nh6},...rh6],Wv=yH(UD1)});function FP(){return!1}function Zr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function VP(Y,Q){let X=B71(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:oh6,bindings:["OBJECT_STORAGE"],status:"active"}}var oh6;var Kr=k(()=>{mn();KY();i1();oh6=uS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function th6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function WB(Y){return typeof Y==="string"||typeof Y==="number"}function Hr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Hr(Y,$));case"or":return H.some(($)=>Hr(Y,$));case"not":return!H.every(($)=>Hr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=zD1(Y,K);switch(J){case"eq":return W===G;case"gt":return WB(W)&&WB(G)&&W>G;case"gte":return WB(W)&&WB(G)&&W>=G;case"lt":return WB(W)&&WB(G)&&W<G;case"lte":return WB(W)&&WB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=th6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function zD1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function eh6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=zD1(X,K),Z=zD1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var sh6,Yx6,Qx6,DD1;var Op0=k(()=>{lS();qp0();MG();Wr();mn();KY();i1();F4();Kr();b$();sh6={LLM:UD1,ASSISTANTS:Vp0,OBJECT_STORAGE:uS};Yx6=uZ.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),Qx6=x$(W5),DD1=s1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yx6,outputSchema:Qx6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=sh6[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?hn(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(FP()){let q=K7(),U=IY.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=VP(X.id,q);K.unshift(z)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((q)=>Hr(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=eh6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Xx6,OD1;var Np0=k(()=>{MG();F4();Kr();b$();Xx6=TS(W5),OD1=s1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:Xx6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),FP()&&Zr(Y.id,X.id))return{item:VP(X.id,K7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $r=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Lp0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Jx6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Gx6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function ND1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Jx6(J);if(!G)continue;let[K,W]=G,Z=$r(K,Y),H=Gx6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Mp0(Y,Q){let X=ND1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var LD1=()=>{};import{randomBytes as Wx6}from"crypto";function wp0(){if(Zv)return Zv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Zv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Zv=new Uint8Array(Wx6(32));return Zv}async function Ap0(Y,Q="5m"){let X=wp0();return await new BG(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Pp0(Y){try{let Q=wp0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Zv=null;var MD1=k(()=>{UG();Kv()});async function Ep0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class $F{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=X9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Fr=k(()=>{$7()});async function Hv(Y,Q,X){let J=Y.id,G=ND1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await Ap0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new $F(Q.db,Q.vault),q=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!q,hasRefresh:!!q?.refreshToken,expiresAt:q?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),q){let U=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await Ep0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),F=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=q.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var wD1=k(()=>{LD1();MD1();Fr()});function Vr(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new G5({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var AD1=k(()=>{qz()});function Tp0(Y){let Q=new wS({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Cp0=k(()=>{vV1()});class $v{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Fv(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Rp0="mcp.mesh";var Ip0,PD1,FF;var Vv=k(()=>{Ip0=class Ip0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};PD1=class PD1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};FF=class FF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Ip0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new PD1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new PD1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Rp0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Zx6="mcp.mesh",qP;var jp0=k(()=>{Vv();qP=class qP extends $v{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new FF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Zx6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function kp0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function TD1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function CD1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function RD1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function Kx6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Hx6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1322
+ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=HO(Y,H);Z.resolve($),$.dispose()}catch($){let F=KO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=KO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HO(Y,W)}catch(K){let W=KO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Jp0=()=>{};function HD1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Yr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){HD1(Y);let K=await Promise.race([G,Nh6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Xv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}async function $D1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"input",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (input). Got ${D}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}var Nh6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Gp0=k(()=>{Xp0();Jp0()});var Qr=k(()=>{Gp0()});async function Lh6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function Wp0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Mh6(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let U=await Q.createMCPProxy(q);return{connection:q,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,U),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,U])=>{try{let D=(await U.proxy.listTools()).tools,L=X.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);D=D.filter((E)=>w.has(E.name))}return{connectionId:q,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,z),null}})),Z=new Set,H=[],$=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=q.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:z}}),$.set(L.name,U)}}let F=async(q,U)=>{let z=$.get(q);if(!z)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:U})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function $P(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await Lh6(J,Y);else X=await Wp0(Q.id,Y)}else X=await Wp0(Q.id,Y);return Mh6(X,Y)}function wh6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function Ah6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Xr(Y,Q,X){let J=wh6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:Ah6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Jr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Gr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Xv({code:Y,tools:J,timeoutMs:X})}function Jv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function GB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function KF(Y){let Q=new Set(Ph6);return Y.filter((X)=>!Q.has(X.name))}var Ph6;var $O=k(()=>{Qr();Ph6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var FD1;var Zp0=k(()=>{F4();Qv();$O();FD1=s1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:id0,outputSchema:ad0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q),J=Xr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var VD1;var Kp0=k(()=>{F4();Qv();$O();VD1=s1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:rd0,outputSchema:od0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return Jr(Y.tools,X.tools)}})});var qD1;var Hp0=k(()=>{F4();Qv();$O();qD1=s1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:sd0,outputSchema:td0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return await Gr(Y.code,X,Y.timeoutMs)}})});var $p0=k(()=>{Zp0();Kp0();Hp0();Qv()});var Th6,Ch6,BD1;var Fp0=k(()=>{KY();i1();F4();Sn();b$();Th6=B.object({data:PR.describe("Data for the new connection (id is auto-generated if not provided)")}),Ch6=B.object({item:W5.describe("The created connection entity")}),BD1=s1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Th6,outputSchema:Ch6,handler:async(Y,Q)=>{z0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=zz(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Dz($)}let K=await zA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var Rh6,Ih6,Vp0;var qp0=k(()=>{i1();MG();Rh6=bH.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Ih6=hH("assistant",Rh6),Vp0=[...Ih6]});var Gv,HF,Up0,jh6,Sh6,zp0,kh6,vh6,_h6,yh6,fh6,bh6,Dp0,hh6,xh6,gh6,uh6,mh6,lh6,dh6,ph6,ch6,nh6,CK9,ih6,RK9,Bp0,ah6,rh6,UD1,Wv;var Wr=k(()=>{i1();_D();MG();Gv=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),Gv),B.array(Gv)])),HF=B.record(B.string(),B.record(B.string(),Gv)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Up0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:HF}),jh6=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),Sh6=B.string().describe("File data as URL string"),zp0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:Sh6,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HF}),kh6=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),vh6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:HF}),_h6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),yh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HF}),fh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),bh6=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:Gv}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:Gv}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))}),B.object({type:B.literal("execution-denied"),reason:B.string().optional()}),B.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Dp0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:bh6.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:HF}),hh6=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),xh6=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),gh6=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:HF}),uh6=B.object({role:B.literal("user"),content:B.array(B.union([Up0,zp0])).describe("User message content parts (text or file)"),providerOptions:HF}),mh6=B.object({role:B.literal("assistant"),content:B.array(B.union([Up0,zp0,vh6,yh6,Dp0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HF}),lh6=B.object({role:B.literal("tool"),content:B.array(Dp0).describe("Tool message content (tool results)"),providerOptions:HF}),dh6=B.union([gh6,uh6,mh6,lh6]),ph6=B.array(dh6).describe("A list of messages forming the prompt"),ch6=B.object({prompt:ph6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),nh6=B.object({content:B.array(B.union([jh6,kh6,_h6,fh6,hh6,xh6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),CK9=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),ih6=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),RK9=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Bp0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:ch6}),ah6=bH.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),rh6=hH("llm",ah6,{readOnly:!0}),UD1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:ih6},{name:"LLM_DO_STREAM",inputSchema:Bp0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Bp0,outputSchema:nh6},...rh6],Wv=yH(UD1)});function FP(){return!1}function Zr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function VP(Y,Q){let X=B71(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:oh6,bindings:["OBJECT_STORAGE"],status:"active"}}var oh6;var Kr=k(()=>{mn();KY();i1();oh6=uS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function th6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function WB(Y){return typeof Y==="string"||typeof Y==="number"}function Hr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Hr(Y,$));case"or":return H.some(($)=>Hr(Y,$));case"not":return!H.every(($)=>Hr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=zD1(Y,K);switch(J){case"eq":return W===G;case"gt":return WB(W)&&WB(G)&&W>G;case"gte":return WB(W)&&WB(G)&&W>=G;case"lt":return WB(W)&&WB(G)&&W<G;case"lte":return WB(W)&&WB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=th6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function zD1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function eh6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=zD1(X,K),Z=zD1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var sh6,Yx6,Qx6,DD1;var Op0=k(()=>{lS();qp0();MG();Wr();mn();KY();i1();F4();Kr();b$();sh6={LLM:UD1,ASSISTANTS:Vp0,OBJECT_STORAGE:uS};Yx6=uZ.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),Qx6=x$(W5),DD1=s1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yx6,outputSchema:Qx6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=sh6[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?hn(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(FP()){let q=K7(),U=IY.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=VP(X.id,q);K.unshift(z)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((q)=>Hr(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=eh6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Xx6,OD1;var Np0=k(()=>{MG();F4();Kr();b$();Xx6=TS(W5),OD1=s1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:Xx6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),FP()&&Zr(Y.id,X.id))return{item:VP(X.id,K7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $r=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Lp0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Jx6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Gx6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function ND1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Jx6(J);if(!G)continue;let[K,W]=G,Z=$r(K,Y),H=Gx6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Mp0(Y,Q){let X=ND1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var LD1=()=>{};import{randomBytes as Wx6}from"crypto";function wp0(){if(Zv)return Zv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Zv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Zv=new Uint8Array(Wx6(32));return Zv}async function Ap0(Y,Q="5m"){let X=wp0();return await new BG(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Pp0(Y){try{let Q=wp0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Zv=null;var MD1=k(()=>{UG();Kv()});async function Ep0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class $F{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=X9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Fr=k(()=>{$7()});async function Hv(Y,Q,X){let J=Y.id,G=ND1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await Ap0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new $F(Q.db,Q.vault),q=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!q,hasRefresh:!!q?.refreshToken,expiresAt:q?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),q){let U=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await Ep0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),F=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=q.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var wD1=k(()=>{LD1();MD1();Fr()});function Vr(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new G5({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var AD1=k(()=>{qz()});function Tp0(Y){let Q=new wS({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Cp0=k(()=>{vV1()});class $v{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Fv(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Rp0="mcp.mesh";var Ip0,PD1,FF;var Vv=k(()=>{Ip0=class Ip0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};PD1=class PD1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};FF=class FF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Ip0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new PD1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new PD1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Rp0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Zx6="mcp.mesh",qP;var jp0=k(()=>{Vv();qP=class qP extends $v{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new FF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Zx6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function kp0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function TD1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function CD1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function RD1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function Kx6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Hx6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1323
1323
  `);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function ED1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(o3(Y.connectionId))return;let G=TD1(Y.request.params.arguments),K=CD1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map(($)=>$.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function vp0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let $=await Z(),F=Q.organization?.id;if(X&&F){let V=$.clone();(async()=>{try{let{text:q,truncated:U}=await Kx6(V,Sp0),z=Date.now()-H,D=V.headers.get("content-type")??"",L=q;if(D.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=$.status>=400,E=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof E==="string"&&E?E:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${$.status} ${$.statusText}`.trim():U?`Response body truncated to ${Sp0} bytes`:void 0,C=RD1(L),P=Hx6(q);if(P)Object.assign(C,P);await ED1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:T,durationMs:z})}catch(q){let U=Date.now()-H;await ED1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:U})}})()}return $}catch($){let F=$,V=Date.now()-H;throw await ED1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:F.message,durationMs:V}),$}}}var Sp0=262144;var ID1=k(()=>{KY()});var BP;var _p0=k(()=>{QS();ID1();BP=class BP extends $v{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,$=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let F="error"in Y,V=F?Y.error:Y.result,q=F?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record($,{"connection.id":J,"tool.name":W,status:F?"error":"success"}),F)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(F&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:q,duration:$,isError:Boolean(F)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:$}=Y;if(!$n().enabled)return;let V=Q.organization?.id;if(!V)return;let q=kp0(Z),U=RD1(Z),z=TD1(W),D=CD1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:$,errorMessage:q,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:D})}catch(L){console.error("[MonitoringTransport] Failed to log to database:",L)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var yp0=k(()=>{jp0();_p0()});async function fp0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!aK(K))throw Error("STDIO connection missing parameters");let W=Tp0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=Fv(W,(Z)=>new qP(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new BP(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),$x6(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Hv(Y,Q,X);console.log("[EventBus:Debug] outbound HTTP client",{connectionId:J,url:Y.connection_url,superUser:X,headerKeys:Object.keys(K)});let W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new bV(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Hv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new SD(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var $x6;var bp0=k(()=>{b$();Rn();AR();wD1();AD1();Cp0();yp0();$x6=Vr()});function ZB(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function gp0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function qv(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var jD1,pH9,iH,hp0,xp0;var VF=k(()=>{i1();jD1=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),pH9=B.object({"tool.fn":B.string().describe("JavaScript ES module code that exports a default async function")}),iH=B.object({id:B.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description of what the tool does"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:jD1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:B.string().describe("When the virtual tool was created"),updated_at:B.string().describe("When the virtual tool was last updated")}),hp0=B.object({name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema for output"),annotations:jD1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),xp0=B.object({name:B.string().min(1).max(255).optional().describe("New tool name"),description:B.string().nullable().optional().describe("New description (null to clear)"),inputSchema:B.record(B.string(),B.unknown()).optional().describe("New input schema"),outputSchema:B.record(B.string(),B.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:jD1.nullable().optional().describe("New annotations (null to clear)"),code:B.string().optional().describe("New JavaScript code"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function FO(Y){return(Q)=>{if(Q instanceof u0&&Q.code===o0.MethodNotFound)return Y;throw Q}}var SD1=k(()=>{vQ()});class up0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function UP(Y){return new up0(Y)}function Fx6(Y,Q,X){let J=new G5({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=_5(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return VO(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,$,F)=>{return(await K()).callTool(H,$,F)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,$)=>{return(await K()).getPrompt(H,$)},J.readResource=async(H,$)=>{return(await K()).readResource(H,$)},J.callStreamableTool=async(H,$)=>{let F=await K();if("callStreamableTool"in F&&typeof F.callStreamableTool==="function")return F.callStreamableTool(H,$);let V=await F.callTool({name:H,arguments:$});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function Vx6(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,Fx6(G,Q,X));return J}async function mp0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var zP;var kD1=k(()=>{DP();SD1();qz();Qr();VF();zP=class zP extends G5{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=Vx6(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=UP(()=>this.loadToolsCache()),this._cachedResources=UP(()=>this.loadCache("resources")),this._cachedPrompts=UP(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((F)=>F.tools),$=this._selectionMap.get(W);if($?.selected_tools?.length){let F=new Set($.selected_tools);H=H.filter((V)=>F.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,F=this._connections.get(Z)?.title??"";for(let V of H){let q=V.name;if(J.has(q))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:F,...V?._meta}};X.push(U),J.set(q,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(FO({resources:[]})).then((F)=>F.resources):await W.listPrompts().catch(FO({prompts:[]})).then((F)=>F.prompts),H=this._selectionMap.get(K),$=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[$]?.length){let F=new Set(H[$]);return{connectionId:K,data:Z.filter((V)=>F.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,$=this._connections.get(W)?.title??"";for(let F of Z){let V=F.name??F.uri;if(G.has(V))continue;let q={...F,_meta:{connectionId:W,connectionTitle:$,...F?._meta}};J.push(q),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=gp0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let $=J.get(H);if(!$)continue;W[Z]=async(F)=>{let V=await $.callTool({name:Z,arguments:F});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let q=V.content;if(q?.[0]?.type==="text"&&q[0].text)try{return JSON.parse(q[0].text)}catch{return q[0].text}return V}}try{let H=`
1324
1324
  const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
1325
1325
  export default async (tools) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/mesh",
3
- "version": "2.123.1",
3
+ "version": "2.123.2",
4
4
  "description": "MCP Mesh - Self-hostable MCP Gateway for managing AI connections and tools",
5
5
  "author": "Deco team",
6
6
  "license": "MIT",