@decocms/mesh 2.59.0 → 2.59.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/cli.js +2 -2
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
package/dist/server/cli.js
CHANGED
|
@@ -1179,13 +1179,13 @@ ${Y.stack}`;return X}if(typeof Y==="object"&&Y!==null){let X=Y,Q="";if(typeof X.
|
|
|
1179
1179
|
${X.stack}`;return Q}try{let G=JSON.stringify(X,null,2);if(G!=="{}"&&G.length<1000){if(typeof X.stack==="string"&&X.stack&&X.stack.length<2000)return`${G}
|
|
1180
1180
|
|
|
1181
1181
|
Stack trace:
|
|
1182
|
-
${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);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 nD(Y,X){switch(typeof X){case"string":return Y.newString(X);case"number":return Y.newNumber(X);case"boolean":return X?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(X===null)return Y.null;if(Array.isArray(X)){let J=Y.newArray();return X.forEach((G,K)=>{let W=nD(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let Q=Y.newObject();for(let[J,G]of Object.entries(X)){let K=nD(Y,G);try{Y.setProp(Q,J,K)}finally{K.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(Q,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=X(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=nD(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=cD(F),$=Y.newString(`Promise resolution error: ${V}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=cD(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return nD(Y,W)}catch(K){let W=cD(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(X.toString());case"symbol":return Y.newString(X.toString());default:try{return Y.newString(String(X))}catch{return Y.undefined}}}var KD6=()=>{};function FD6(Y){let X=Y.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function HD6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){FD6(Y);let K=await Promise.race([G,L91(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function g50({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await WD6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=gG(W,J.newContext({interruptAfterMs:Q}),0);const K=gG(W,vU6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),$=G.unwrapResult(V),q=nD(G,Y);G.setProp(G.global,"tools",q);let B=G.runtime.hasPendingJob()?G.unwrapResult(await HD6(G,$,Q)):$;if(B!==$)$.dispose();let D=G.getProp(B,"default"),O=G.typeof(D);if(O!=="function")return{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,q),w=G.unwrapResult(L),I=await HD6(G,w,Q),T=G.unwrapResult(I);if(G.runtime.hasPendingJob())FD6(G);return{returnValue:G.dump(T),consoleLogs:K.logs}}catch(V){return console.log(V),{error:cD(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{PW(W,H,F)}}var L91=(Y)=>new Promise((X)=>setTimeout(X,Y));var VD6=S(()=>{ZD6();KD6()});var $D6=S(()=>{VD6()});async function w91(Y,X){let Q=Y.connections.map((K)=>K.connection_id),J=[];for(let K of Q){let W=await X.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 qD6(Y,X){return(await X.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function M91(Y,X){let Q=new Map;for(let q of Y)Q.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 B=await X.createMCPProxy(q);return{connection:q,proxy:B}}catch(B){return console.error(`[code-execution] Failed to create proxy for connection ${q.id}:`,B),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,B])=>{try{let O=(await B.proxy.listTools()).tools,L=Q.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);O=O.filter((I)=>w.has(I.name))}return{connectionId:q,connectionTitle:B.connection.title,tools:O}}catch(D){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,D),null}})),Z=new Set,H=[],F=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:B,connectionTitle:D,tools:O}=q.value;for(let L of O){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:B,connectionTitle:D}}),F.set(L.name,B)}}let V=async(q,B)=>{let D=F.get(q);if(!D)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let O=G.get(D);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await O.proxy.callTool({name:q,arguments:B})},$=[];for(let[,q]of G)$.push(q.proxy.close().catch(()=>{}));return await Promise.all($),{tools:H,callTool:V}}async function iD(Y){let X=h6(Y),Q;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)Q=await w91(J,Y);else Q=await qD6(X.id,Y)}else Q=await qD6(X.id,Y);return M91(Q,Y)}function A91(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function T91(Y,X){let Q=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),K=(X._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(K.includes(W))Q+=1}return Q}function hx(Y,X,Q){let J=A91(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:T91(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function bx(Y,X){let Q=new Map(X.map((G)=>[G.name,G]));return{tools:Y.map((G)=>Q.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)=>!Q.has(G))}}async function xx(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return g50({code:Y,tools:J,timeoutMs:Q})}function oP(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function C3(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function XK(Y){let X=new Set(P91);return Y.filter((Q)=>!X.has(Q.name))}var P91;var g$=S(()=>{$D6();P91=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var m50;var zD6=S(()=>{z4();aP();g$();m50=J6({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.",inputSchema:CU6,outputSchema:IU6,handler:async(Y,X)=>{D6(X),h6(X),await X.access.check();let Q=await iD(X),J=hx(Y.query,Q.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:Q.tools.length}}})});var l50;var BD6=S(()=>{z4();aP();g$();l50=J6({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.",inputSchema:RU6,outputSchema:jU6,handler:async(Y,X)=>{D6(X),h6(X),await X.access.check();let Q=await iD(X);return bx(Y.tools,Q.tools)}})});var d50;var UD6=S(()=>{z4();aP();g$();d50=J6({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.',inputSchema:SU6,outputSchema:kU6,handler:async(Y,X)=>{D6(X),h6(X),await X.access.check();let Q=await iD(X);return await xx(Y.code,Q,Y.timeoutMs)}})});var DD6=S(()=>{zD6();BD6();UD6();aP()});var C91,I91,p50;var OD6=S(()=>{j5();n0();z4();Sx();sZ();C91=z.object({data:KB6.describe("Data for the new connection (id is auto-generated if not provided)")}),I91=z.object({item:S5.describe("The created connection entity")}),p50=J6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:C91,outputSchema:I91,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=s8(X);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=Tx(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await X.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Px(H)}let K=await lD({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?.length?K:null,Z=await X.storage.connections.create({...G,tools:W});return await X.eventBus.publish(Q.id,MJ.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function sP(Y,X){if(Y===X)return!0;if(Y==null||X==null)return Y===X;if(typeof Y!==typeof X)return!1;if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return!1;return Y.every((Q,J)=>sP(Q,X[J]))}if(typeof Y==="object"&&typeof X==="object"){let Q=Object.keys(Y),J=Object.keys(X);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&sP(Y[G],X[G]))}return!1}function o91(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>sP(Q,G)))return!1;return X.push(Q),!0})}}function ux(Y,X){return Y.safeParse(X).success}function cY(Y){if(typeof Y==="boolean")return Y?z.any():z.never();let X={};for(let G of VY1)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||z.string());if(X.number!==!1)Q.push(X.number||z.number());if(X.boolean!==!1)Q.push(X.boolean||z.boolean());if(X.null!==!1)Q.push(X.null||z.null());if(X.array!==!1)Q.push(X.array||z.array(z.any()));if(X.tuple!==!1&&X.tuple!==void 0)Q.push(X.tuple);if(X.object!==!1)if(X.object)Q.push(X.object);else{let G=z.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");Q.push(G)}if(X.file!==!1&&X.file!==void 0)Q.push(X.file);let J;if(Q.length===0)J=z.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=z.any();else J=z.union(Q);for(let G of $Y1)J=G.apply(J,Y);return J}var R91=class{apply(Y,X){if(!X.type)return;let Q=Array.isArray(X.type)?X.type:[X.type],J=new Set(Q);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||z.number();if(G instanceof z.ZodNumber)Y.number=G.int()}}},j91=class{apply(Y,X){if(X.const===void 0)return;let Q=X.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof Q==="string")Y.string=z.literal(Q);else if(typeof Q==="number")Y.number=z.literal(Q);else if(typeof Q==="boolean")Y.boolean=z.literal(Q);else if(Q===null)Y.null=z.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},S91=class{apply(Y,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let Q={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(Q.string,"string"),Y.number=this.createTypeSchema(Q.number,"number"),Y.boolean=this.createTypeSchema(Q.boolean,"boolean"),Y.null=Q.null.length>0?z.null():!1,Y.array=Q.array.length>0?void 0:!1,Y.object=Q.object.length>0?void 0:!1}createTypeSchema(Y,X){if(Y.length===0)return!1;if(Y.length===1)return z.literal(Y[0]);if(X==="string")return z.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return z.union([z.literal(Q),z.literal(J),...G.map((K)=>z.literal(K))])}if(X==="boolean")return z.union([z.literal(!0),z.literal(!1)]);return!1}},k91=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=z.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);Y.file=J,Y.string=!1}}},v91=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(Y.string===void 0)Y.string=z.string()}}},_91=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||z.string();if(J instanceof z.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},y91=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||z.string();if(J instanceof z.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},f91=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||z.string();if(J instanceof z.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},h91=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)Y.number=J.min(Q.minimum)}}},b91=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)Y.number=J.max(Q.maximum)}}},x91=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},u91=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},g91=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)Y.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let K=G/Q.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},m91=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(Y.array===void 0)Y.array=z.array(z.any())}}},l91=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||z.array(z.any())).min(Q.minItems)}},d91=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||z.array(z.any())).max(Q.maxItems)}},p91=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||z.array(z.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=cY(Q.items),G=z.array(J);if(Y.array&&Y.array instanceof z.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)Y.array=z.array(z.any()).max(0);else Y.array=Y.array||z.array(z.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||z.array(z.any());else if(Q.prefixItems)Y.array=Y.array||z.array(z.any())}},c91=class{apply(Y,X){if(X.type!=="array")return;let Q=X;if(!Array.isArray(Q.items))return;if(Y.array===!1)return;let J=Q.items.map((K)=>cY(K)),G;if(J.length===0)G=z.tuple([]);else G=z.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},n91=class{apply(Y,X){let Q=X;if(Y.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)Y.object=Y.object||z.object({}).passthrough()}},i91=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(Y.object===void 0)Y.object=z.object({}).passthrough()}}},a91=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||z.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},r91=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||z.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},s91=class{apply(Y,X){if(!X.not)return Y;let Q=cY(X.not);return Y.refine((J)=>!ux(Q,J),{message:"Value must not match the 'not' schema"})}},t91=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(o91(),{message:"Array items must be unique"})}},e91=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>cY(J)).reduce((J,G)=>z.intersection(J,G),Y)}},YY1=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?cY(X.anyOf[0]):z.union([cY(X.anyOf[0]),cY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>cY(J))]);return z.intersection(Y,Q)}},XY1=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>cY(J));return Y.refine((J)=>{let G=0;for(let K of Q)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},QY1=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>cY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!ux(G[W],K[W]))return!1;if(K.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let W=cY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!ux(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},JY1=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof z.ZodObject||Y instanceof z.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=cY(K)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return z.object(J);else return z.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!cY(K).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},GY1=class{apply(Y,X){if(!X.enum||X.enum.length===0)return Y;let Q=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>sP(J,G))},{message:"Value must match one of the enum values"})}},WY1=class{apply(Y,X){if(X.const===void 0)return Y;let Q=X.const;if(typeof Q!=="object"||Q===null)return Y;return Y.refine((J)=>sP(J,Q),{message:"Value must equal the const value"})}},ZY1=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},KY1=class{apply(Y,X){var Q;let J=X;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||X.type!==void 0)return Y;return z.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,X){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return X.every((Q)=>Object.prototype.hasOwnProperty.call(Y,Q))}},HY1=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=cY(J.contains),K=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let F of Z)if(ux(G,F))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},FY1=class{apply(Y,X){let{default:Q}=X;if(Q===void 0)return Y;if(!Y.safeParse(Q).success)return Y;return Y.default(Q)}},VY1,$Y1;var ND6=S(()=>{Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();VY1=[new j91,new S91,new R91,new k91,new v91,new m91,new i91,new _91,new y91,new f91,new h91,new b91,new x91,new u91,new g91,new c91,new l91,new d91,new p91,new a91,new r91,new n91],$Y1=[new KY1,new GY1,new WY1,new e91,new YY1,new XY1,new QY1,new JY1,new HY1,new s91,new t91,new FY1,new ZY1]});class c50{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{this._socket=new WebSocket(this._url,qY1),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=wJ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((X,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),X()})}}var qY1="mcp";var LD6=S(()=>{OX()});function zY1(Y){let X=Y;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Q=X?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var n50;var wD6=S(()=>{fP();n50=class n50 extends A3{constructor(Y,X){super(Y,X)}send(Y,X){let Q=zY1(Y);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(Y,X)}}});var MD6,AD6=async(Y,X,Q)=>{let J=BY1(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new MD6({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(Q);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[$,q]of Object.entries(Y.connection.headers??{}))H.set($,q);let F=new URL(Y.connection.url),V=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${V}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},BY1=(Y,X,Q)=>{if(Y.type==="Websocket")return new c50(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...Q??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:X}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new f$(new URL(Y.url),K)}return new n50(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var TD6=S(()=>{CD();Ix();LD6();OX();wD6();MD6=class MD6 extends R5{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},GP,X)}}});function ED6(Y){let X=(Q)=>{if("connection"in Y)return AD6({connection:Y.connection},void 0,Q);return Y.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return Z;async function G(H,F=J){let V=Y?.debugId?.(),$=V?{"x-trace-debug-id":V}:void 0,{client:q,callStreamableTool:B}=await X($);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:D,isError:O,content:L}=await q.callTool({name:String(F),arguments:H});if(O){let w=L?.[0]?.text,I=typeof w==="string"?UY1(w):null,T=I?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(I.code,I.message,I.traceId):null;if(T)throw T;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(D??L)}`)}return D}async function K(){let{client:H}=await X(),{tools:F}=await H.listTools();return F}async function W(){if(!("connection"in Y))return K();let H=Y.connection,F=JSON.stringify(H);try{if(!gx.has(F))gx.set(F,K());return await gx.get(F)}catch(V){console.error("Failed to list tools",V),gx.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>PD6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return PD6(F,G)},G}})}var UY1=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},gx,PD6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?cY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?cY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var CD6=S(()=>{ND6();TD6();gx=new Map});function mx(Y){return ED6(Y)}var cV8;var ID6=S(()=>{CD6();cV8=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>mx({connection:Q});return global[X]}})});function lx(Y){return{isImplementedBy:(X)=>{for(let Q of Y){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=X.find((K)=>J.test(K.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var m$=(Y)=>{return{...lx(Y),forClient:(X)=>{return mx({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return mx({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var tP=S(()=>{ID6()});var i50,oV8;var RD6=S(()=>{_T();i50=f4(vT(),1),oV8=i50.createContext(null)});function JK(Y){return z.object({items:z.array(Y).describe("Array of collection items"),totalCount:z.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:z.boolean().optional().describe("Whether there are more items available")})}function Y2(Y){return z.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function NY1(Y){return z.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function LY1(Y){return z.object({item:Y.describe("The created entity with generated id")})}function wY1(Y){return z.object({id:z.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function MY1(Y){return z.object({item:Y.describe("The updated entity")})}function Q2(Y){return z.object({item:Y.describe("The deleted entity")})}function rD(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:QK,outputSchema:JK(X)},{name:`COLLECTION_${J}_GET`,inputSchema:eP,outputSchema:Y2(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:NY1(X),outputSchema:LY1(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:wY1(X),outputSchema:MY1(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:X2,outputSchema:Q2(X),opt:!0});return K}var aD,DY1,jD6,OY1,QK,eP,X2;var k5=S(()=>{n0();aD=z.object({id:z.string().describe("Unique identifier for the entity"),title:z.string().describe("Human-readable title for the entity"),description:z.string().nullish().describe("Description of the entity"),created_at:z.string().datetime(),updated_at:z.string().datetime(),created_by:z.string().optional(),updated_by:z.string().optional()}),DY1=z.object({field:z.array(z.string()),operator:z.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:z.unknown()}),jD6=z.lazy(()=>z.union([DY1,z.object({operator:z.enum(["and","or","not"]),conditions:z.array(jD6)})])),OY1=z.object({field:z.array(z.string()),direction:z.enum(["asc","desc"]),nulls:z.enum(["first","last"]).optional()}),QK=z.object({where:jD6.optional().describe("Filter expression"),orderBy:z.array(OY1).optional().describe("Sort expressions"),limit:z.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:z.number().int().min(0).optional().describe("Number of items to skip")});eP=z.object({id:z.string().describe("ID of the entity to retrieve")});X2=z.object({id:z.string().describe("ID of the entity to delete")})});var AY1,SD6,J$8;var kD6=S(()=>{n0();k5();AY1=z.object({id:z.string(),name:z.string(),description:z.string().optional(),inputSchema:z.record(z.string(),z.unknown()),outputSchema:z.record(z.string(),z.unknown()).optional()}),SD6=aD.extend({_meta:z.object({"io.decocms":z.object({id:z.string(),verified:z.boolean(),scopeName:z.string(),appName:z.string(),friendlyName:z.string().nullable().optional(),metadata:z.record(z.string(),z.unknown()).nullable().optional(),publishedAt:z.string().datetime().optional(),updatedAt:z.string().datetime().optional(),tools:z.array(AY1).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:z.object({$schema:z.string().optional(),_meta:z.record(z.string(),z.unknown()).optional(),name:z.string().describe("The server name (scope/app)"),title:z.string().optional().describe("User-friendly title"),description:z.string().optional().describe("Server description"),icons:z.array(z.object({src:z.string(),mimeType:z.string().optional(),sizes:z.array(z.string()).optional(),theme:z.enum(["light","dark"]).optional()})).optional(),remotes:z.array(z.object({type:z.enum(["http","stdio","sse"]),url:z.string().optional(),headers:z.array(z.unknown()).optional()})).optional(),packages:z.array(z.unknown()).optional(),repository:z.object({url:z.string(),source:z.string().optional(),subfolder:z.string().optional()}).optional(),version:z.string().optional(),websiteUrl:z.string().optional()})}),J$8=rD("registry_app",SD6,{readOnly:!0})});var vD6,_D6,yD6,fD6,hD6,a50;var bD6=S(()=>{n0();tP();vD6=z.object({specversion:z.literal("1.0").describe("CloudEvents specification version"),id:z.string().describe("Unique identifier for this event (UUID recommended)"),source:z.string().describe("Connection ID of the event publisher"),type:z.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:z.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:z.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:z.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:z.string().url().optional().describe("URI to the schema for the data attribute"),data:z.unknown().optional().describe("Event payload (any JSON value)")}),_D6=z.object({events:z.array(vD6).min(1).describe("Batch of CloudEvents to process")}),yD6=z.object({success:z.boolean().optional().describe("Whether this event was processed successfully"),error:z.string().optional().describe("Error message for this event"),retryAfter:z.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),fD6=z.object({success:z.boolean().optional().describe("Batch success - applies to events not in results"),error:z.string().optional().describe("Batch error message - applies to events not in results"),processedCount:z.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:z.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:z.record(z.string(),yD6).optional().describe("Per-event results keyed by event ID")}),hD6=[{name:"ON_EVENTS",inputSchema:_D6,outputSchema:fD6}],a50=m$(hD6)});var J2,G2,W2,Z2,xD6,uD6,K2,H2,F2,V2,$2,q2,z2,B2,gD6,TY1;var mD6=S(()=>{n0();tP();J2=z.object({type:z.string().min(1).max(255).describe("Event type identifier"),subject:z.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:z.unknown().optional().describe("Event payload"),deliverAt:z.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:z.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),G2=z.object({id:z.string().describe("Unique event ID"),type:z.string().describe("Event type"),source:z.string().describe("Source connection ID"),time:z.string().describe("Event timestamp")}),W2=z.object({eventType:z.string().min(1).max(255).describe("Event type to subscribe to"),publisher:z.string().optional().describe("Filter events by publisher connection ID"),filter:z.string().max(1000).optional().describe("JSONPath filter expression on event data")}),Z2=z.object({subscription:z.object({id:z.string().describe("Subscription ID"),connectionId:z.string().describe("Subscriber connection ID"),eventType:z.string().describe("Event type pattern"),publisher:z.string().nullable().describe("Publisher connection filter"),filter:z.string().nullable().describe("JSONPath filter expression"),enabled:z.boolean().describe("Whether subscription is enabled"),createdAt:z.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:z.string().datetime().describe("Updated timestamp (ISO 8601)")})}),xD6=z.object({eventType:z.string().min(1).max(255).describe("Event type to subscribe to"),publisher:z.string().optional().describe("Filter events by publisher connection ID"),filter:z.string().max(1000).optional().describe("JSONPath filter expression on event data")}),uD6=z.object({id:z.string().describe("Subscription ID"),connectionId:z.string().describe("Subscriber connection ID"),eventType:z.string().describe("Event type pattern"),publisher:z.string().nullable().describe("Publisher connection filter"),filter:z.string().nullable().describe("JSONPath filter expression"),enabled:z.boolean().describe("Whether subscription is enabled"),createdAt:z.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:z.string().datetime().describe("Updated timestamp (ISO 8601)")}),K2=z.object({subscriptions:z.array(xD6).describe("Desired subscriptions - system will create/update/delete to match")}),H2=z.object({created:z.number().int().min(0).describe("Number of subscriptions created"),updated:z.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:z.number().int().min(0).describe("Number of subscriptions removed"),unchanged:z.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:z.array(uD6).describe("Current subscriptions after sync")}),F2=z.object({subscriptionId:z.string().describe("Subscription ID to remove")}),V2=z.object({success:z.boolean().describe("Whether unsubscribe was successful"),subscriptionId:z.string().describe("Subscription ID that was removed")}),$2=z.object({eventId:z.string().describe("Event ID to cancel")}),q2=z.object({success:z.boolean().describe("Whether cancellation was successful"),eventId:z.string().describe("Event ID that was cancelled")}),z2=z.object({eventId:z.string().describe("Event ID to acknowledge")}),B2=z.object({success:z.boolean().describe("Whether ACK was successful"),eventId:z.string().describe("Event ID that was acknowledged")}),gD6=[{name:"EVENT_PUBLISH",inputSchema:J2,outputSchema:G2},{name:"EVENT_SUBSCRIBE",inputSchema:W2,outputSchema:Z2},{name:"EVENT_UNSUBSCRIBE",inputSchema:F2,outputSchema:V2},{name:"EVENT_CANCEL",inputSchema:$2,outputSchema:q2},{name:"EVENT_ACK",inputSchema:z2,outputSchema:B2},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:K2,outputSchema:H2}],TY1=m$(gD6)});var PY1,EY1,CY1,IY1,RY1,jY1,SY1,kY1,vY1,_Y1,yY1,fY1,U2;var dx=S(()=>{n0();PY1=z.object({prefix:z.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:z.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:z.string().optional().describe("Token for pagination from previous response"),delimiter:z.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),EY1=z.object({objects:z.array(z.object({key:z.string().describe("Object key/path"),size:z.number().describe("Object size in bytes"),lastModified:z.string().describe("Last modified timestamp"),etag:z.string().describe("Entity tag for the object")})),nextContinuationToken:z.string().optional().describe("Token for fetching next page of results"),isTruncated:z.boolean().describe("Whether there are more results available"),commonPrefixes:z.array(z.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),CY1=z.object({key:z.string().describe("Object key/path to get metadata for")}),IY1=z.object({contentType:z.string().optional().describe("MIME type of the object"),contentLength:z.number().describe("Size of the object in bytes"),lastModified:z.string().describe("Last modified timestamp"),etag:z.string().describe("Entity tag for the object"),metadata:z.record(z.string(),z.string()).optional().describe("Custom metadata key-value pairs")}),RY1=z.object({key:z.string().describe("Object key/path to generate URL for"),expiresIn:z.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),jY1=z.object({url:z.string().describe("Presigned URL for downloading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),SY1=z.object({key:z.string().describe("Object key/path for the upload"),expiresIn:z.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:z.string().optional().describe("MIME type for the object being uploaded")}),kY1=z.object({url:z.string().describe("Presigned URL for uploading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),vY1=z.object({key:z.string().describe("Object key/path to delete")}),_Y1=z.object({success:z.boolean().describe("Whether the deletion was successful"),key:z.string().describe("The key that was deleted")}),yY1=z.object({keys:z.array(z.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),fY1=z.object({deleted:z.array(z.string()).describe("Array of successfully deleted keys"),errors:z.array(z.object({key:z.string(),message:z.string()})).describe("Array of errors for failed deletions")}),U2=[{name:"LIST_OBJECTS",inputSchema:PY1,outputSchema:EY1},{name:"GET_OBJECT_METADATA",inputSchema:CY1,outputSchema:IY1},{name:"GET_PRESIGNED_URL",inputSchema:RY1,outputSchema:jY1},{name:"PUT_PRESIGNED_URL",inputSchema:SY1,outputSchema:kY1},{name:"DELETE_OBJECT",inputSchema:vY1,outputSchema:_Y1},{name:"DELETE_OBJECTS",inputSchema:yY1,outputSchema:fY1}]});var px=S(()=>{tP();RD6();kD6();bD6();mD6();dx()});var hY1,bY1,lD6;var dD6=S(()=>{n0();k5();hY1=aD.extend({avatar:z.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:z.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:z.string().describe("Virtual MCP ID to use for this assistant"),model:z.object({id:z.string().describe("Model ID"),connectionId:z.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),bY1=rD("assistant",hY1),lD6=[...bY1]});var D2,GK,cD6,xY1,uY1,nD6,gY1,mY1,lY1,dY1,pY1,cY1,iD6,nY1,iY1,aY1,rY1,oY1,sY1,tY1,eY1,YX1,XX1,S$8,QX1,k$8,pD6,JX1,GX1,r50,O2;var cx=S(()=>{n0();tP();k5();D2=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),D2),z.array(D2)])),GK=z.record(z.string(),z.record(z.string(),D2)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),cD6=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerOptions:GK}),xY1=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),uY1=z.string().describe("File data as URL string"),nD6=z.object({type:z.literal("file"),filename:z.string().optional().describe("Optional filename of the file"),data:uY1,mediaType:z.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:GK}),gY1=z.object({type:z.literal("file"),mediaType:z.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:z.string().describe("Generated file data as base64 encoded string")}),mY1=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerOptions:GK}),lY1=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),dY1=z.object({type:z.literal("tool-call"),toolCallId:z.string().describe("ID of the tool call, used to match with tool result"),toolName:z.string().describe("Name of the tool being called"),input:z.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:z.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:GK}),pY1=z.object({type:z.literal("tool-call"),toolCallId:z.string().describe("ID of the tool call"),toolName:z.string().describe("Name of the tool being called"),input:z.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:z.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),cY1=z.union([z.object({type:z.literal("text"),value:z.string()}),z.object({type:z.literal("json"),value:D2}),z.object({type:z.literal("error-text"),value:z.string()}),z.object({type:z.literal("error-json"),value:D2}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string().describe("Text content")}),z.object({type:z.literal("media"),data:z.string().describe("Base-64 encoded media data"),mediaType:z.string().describe("IANA media type")})]))})]),iD6=z.object({type:z.literal("tool-result"),toolCallId:z.string().describe("ID of the tool call that this result is associated with"),toolName:z.string().describe("Name of the tool that generated this result"),output:cY1.describe("Result of the tool call"),result:z.unknown().describe("Unknown result of the tool call"),providerOptions:GK}),nY1=z.object({type:z.literal("tool-result"),toolCallId:z.string().describe("ID of the tool call that this result is associated with"),toolName:z.string().describe("Name of the tool that generated this result"),result:z.any().describe("Result of the tool call (JSON-serializable)"),isError:z.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:z.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),iY1=z.union([z.object({type:z.literal("source"),sourceType:z.literal("url"),id:z.string().describe("The ID of the source"),url:z.string().describe("The URL of the source"),title:z.string().optional().describe("The title of the source"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),z.object({type:z.literal("source"),sourceType:z.literal("document"),id:z.string().describe("The ID of the source"),mediaType:z.string().describe("IANA media type of the document (e.g., application/pdf)"),title:z.string().describe("The title of the document"),filename:z.string().optional().describe("Optional filename of the document"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")})]),aY1=z.object({role:z.literal("system"),content:z.string().describe("System message content"),providerOptions:GK}),rY1=z.object({role:z.literal("user"),content:z.array(z.union([cD6,nD6])).describe("User message content parts (text or file)"),providerOptions:GK}),oY1=z.object({role:z.literal("assistant"),content:z.array(z.union([cD6,nD6,mY1,dY1,iD6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:GK}),sY1=z.object({role:z.literal("tool"),content:z.array(iD6).describe("Tool message content (tool results)"),providerOptions:GK}),tY1=z.union([aY1,rY1,oY1,sY1]),eY1=z.array(tY1).describe("A list of messages forming the prompt"),YX1=z.object({prompt:eY1.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:z.number().optional().describe("Maximum number of tokens to generate"),temperature:z.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:z.number().optional().describe("Nucleus sampling parameter"),topK:z.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:z.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:z.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:z.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:z.array(z.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:z.union([z.object({type:z.literal("text")}),z.object({type:z.literal("json"),schema:z.any().optional().describe("JSON schema that the generated output should conform to"),name:z.string().optional().describe("Name of output that should be generated"),description:z.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:z.array(z.any()).optional().describe("The tools that are available for the model"),toolChoice:z.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:z.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:z.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:z.any().optional().describe("Additional provider-specific options")}),XX1=z.object({content:z.array(z.union([xY1,gY1,lY1,pY1,nY1,iY1])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:z.looseObject({inputTokens:z.number().optional(),outputTokens:z.number().optional(),totalTokens:z.number().optional(),reasoningTokens:z.number().optional()}).describe("Usage information for the language model call"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata"),request:z.object({body:z.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:z.object({id:z.string().optional().describe("ID for the generated response"),timestamp:z.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:z.string().optional().describe("The ID of the response model that was used"),headers:z.record(z.string(),z.string()).optional().describe("Response headers"),body:z.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:z.array(z.any()).describe("Warnings for the call, e.g. unsupported settings")}),S$8=z.object({stream:z.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:z.object({body:z.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:z.object({headers:z.record(z.string(),z.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),QX1=z.object({supportedUrls:z.record(z.string(),z.array(z.string())).describe("Supported URL patterns by media type for the provider")}),k$8=z.object({modelId:z.string().describe("The ID of the model"),logo:z.string().nullable(),description:z.string().nullable(),capabilities:z.array(z.string()),limits:z.object({contextWindow:z.number(),maxOutputTokens:z.number()}).nullable(),costs:z.object({input:z.number(),output:z.number()}).nullable(),provider:z.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),pD6=z.object({modelId:z.string().describe("The ID of the model"),callOptions:YX1}),JX1=aD.extend({logo:z.string().nullable(),description:z.string().nullable(),capabilities:z.array(z.string()),limits:z.object({contextWindow:z.number(),maxOutputTokens:z.number()}).nullable(),costs:z.object({input:z.number(),output:z.number()}).nullable(),provider:z.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),GX1=rD("llm",JX1,{readOnly:!0}),r50=[{name:"LLM_METADATA",inputSchema:z.object({modelId:z.string().describe("The ID of the model")}),outputSchema:QX1},{name:"LLM_DO_STREAM",inputSchema:pD6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:pD6,outputSchema:XX1},...GX1],O2=m$(r50)});function nx(){return!1}function aD6(Y,X){return Y===MJ.DEV_ASSETS(X)}function ix(Y,X){let Q=hJ0(X,Y),J=new Date().toISOString();return{id:Q.id??MJ.DEV_ASSETS(Y),title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:Q.app_name??null,app_id:Q.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:Q.connection_type,connection_url:Q.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata??null,tools:WX1,bindings:["OBJECT_STORAGE"],status:"active"}}var WX1;var o50=S(()=>{dx();j5();n0();WX1=U2.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:z.toJSONSchema(Y.inputSchema),outputSchema:z.toJSONSchema(Y.outputSchema)}))});function KX1(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function I3(Y){return typeof Y==="string"||typeof Y==="number"}function ax(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>ax(Y,F));case"or":return H.some((F)=>ax(Y,F));case"not":return!H.every((F)=>ax(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=s50(Y,K);switch(J){case"eq":return W===G;case"gt":return I3(W)&&I3(G)&&W>G;case"gte":return I3(W)&&I3(G)&&W>=G;case"lt":return I3(W)&&I3(G)&&W<G;case"lte":return I3(W)&&I3(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=KX1(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 s50(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function HX1(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=s50(Q,K),Z=s50(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 ZX1,FX1,VX1,t50;var rD6=S(()=>{px();dD6();k5();cx();dx();j5();n0();z4();o50();sZ();ZX1={LLM:r50,ASSISTANTS:lD6,OBJECT_STORAGE:U2};FX1=QK.extend({binding:z.union([z.object({}).passthrough(),z.string()]).optional()}),VX1=JK(S5),t50=J6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:FX1,outputSchema:VX1,handler:async(Y,X)=>{await X.access.check();let Q=h6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=ZX1[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?lx(J):void 0,K=await X.storage.connections.list(Q.id);if(nx()){let B=t5(),D=MJ.DEV_ASSETS(Q.id);if(!K.some((O)=>O.id===D)){let O=ix(Q.id,B);K.unshift(O)}}let W=K.filter((B)=>B.connection_type!=="VIRTUAL"),Z=G?await Promise.all(W.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((O)=>({name:O.name,inputSchema:O.inputSchema,outputSchema:O.outputSchema})))?B:null})).then((B)=>B.filter((D)=>D!==null)):W;if(Y.where)Z=Z.filter((B)=>ax(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=HX1(Z,Y.orderBy);let H=Z.length,F=Y.offset??0,V=Y.limit??100,$=Z.slice(F,F+V),q=F+V<H;return{items:$,totalCount:H,hasMore:q}}})});var $X1,e50;var oD6=S(()=>{k5();z4();o50();sZ();$X1=Y2(S5),e50=J6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:eP,outputSchema:$X1,handler:async(Y,X)=>{let Q=h6(X);if(await X.access.check(),nx()&&aD6(Y.id,Q.id))return{item:ix(Q.id,t5())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var rx=(Y,X)=>{if(X===null||X===void 0)return;let Q=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function sD6(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return X}function qX1(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function zX1(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function YG0(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=qX1(J);if(!G)continue;let[K,W]=G,Z=rx(K,Y),H=zX1(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function tD6(Y,X){let Q=YG0(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var XG0=()=>{};class WK{db;vault;constructor(Y,X){this.db=Y;this.vault=X}async get(Y){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Y){let X=new Date().toISOString(),Q=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:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:X}).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:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=B9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:X,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,X=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-X<Date.now()}async decryptToken(Y){let X=await this.vault.decrypt(Y.accessToken),Q=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:X,refreshToken:Q,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var ox=S(()=>{tZ()});async function DX1(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=sD6(K),Z=rx(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=tD6(Y,X);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var BX1,UX1,QG0;var eD6=S(()=>{XG0();ox();n0();z4();Sx();sZ();BX1=z.object({id:z.string().describe("ID of the connection to update"),data:HB6.describe("Partial connection data to update")}),UX1=z.object({item:S5.describe("The updated connection entity")});QG0=J6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:BX1,outputSchema:UX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);if(await X.access.check(),!s8(X))throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let A=Tx(H);if(!A)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let R=await X.storage.virtualMcps.findById(A);if(!R)throw Error(`Virtual MCP not found: ${A}`);if(R.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=Px(A)}let F=K.configuration_state??W.configuration_state,V=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state;else if(F===null)F={};if(K.configuration_scopes!==void 0)V=K.configuration_scopes??[];if(V.length>0&&F)await DX1(F,V,Q.id,X)}let $=K.connection_token??W.connection_token;if(!$)try{let R=await new WK(X.db,X.vault).get(G);if(R?.accessToken)$=R.accessToken}catch{}let q=await lD({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:$,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=q?.length?q:null,D={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:V},O=await X.storage.connections.update(G,D);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&V.length>0)try{let L=[];try{const A=gG(L,await X.createMCPProxy(G),1);await A.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:V}});await A.close().catch(console.error)}catch(w){var I=w,T=1}finally{var P=PW(L,I,T);P&&await P}}catch(A){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",A)}return{item:O}}})});var JG0;var YO6=S(()=>{k5();z4();sZ();JG0=J6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:X2,outputSchema:Q2(S5),handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");return await X.storage.connections.delete(Y.id),{item:J}}})});var GG0;var XO6=S(()=>{n0();z4();GG0=J6({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:z.object({id:z.string()}),outputSchema:z.object({id:z.string(),healthy:z.boolean(),latencyMs:z.number()}),handler:async(Y,X)=>{let Q=h6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var QO6=S(()=>{OD6();rD6();oD6();eD6();YO6();XO6()});import{sql as K1}from"kysely";function JO6(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function LX1(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,JO6(X[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,X.length)-1;G>=0;G--){let K=J[G],W=JO6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function GO6(Y){return Y.replace(/-/g,"_")}function MX1(Y){return`app_${GO6(Y)}`}function AX1(Y){return`app_role_${GO6(Y)}`}function TX1(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),Q=Y.code;return Q==="3F000"||Q==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function PX1(Y,X,Q){if(await K1`CREATE SCHEMA IF NOT EXISTS ${K1.id(X)}`.execute(Y),!(await K1`
|
|
1182
|
+
${X.stack}`;return G}}catch{}if(typeof X.toString==="function")try{let G=X.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(X);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 nD(Y,X){switch(typeof X){case"string":return Y.newString(X);case"number":return Y.newNumber(X);case"boolean":return X?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(X===null)return Y.null;if(Array.isArray(X)){let J=Y.newArray();return X.forEach((G,K)=>{let W=nD(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let Q=Y.newObject();for(let[J,G]of Object.entries(X)){let K=nD(Y,G);try{Y.setProp(Q,J,K)}finally{K.dispose?.()}}return Q}case"function":{let Q=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(Q,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=X(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let F=nD(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=cD(F),$=Y.newString(`Promise resolution error: ${V}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=cD(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return nD(Y,W)}catch(K){let W=cD(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(X.toString());case"symbol":return Y.newString(X.toString());default:try{return Y.newString(String(X))}catch{return Y.undefined}}}var KD6=()=>{};function FD6(Y){let X=Y.runtime.executePendingJobs(100);try{if("unwrap"in X&&typeof X.unwrap==="function")X.unwrap()}finally{if("dispose"in X&&typeof X.dispose==="function")X.dispose()}}async function HD6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){FD6(Y);let K=await Promise.race([G,L91(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>Q)throw Error(`Timed out after ${Q}ms while awaiting a QuickJS promise`)}}async function g50({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await WD6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=gG(W,J.newContext({interruptAfterMs:Q}),0);const K=gG(W,vU6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),$=G.unwrapResult(V),q=nD(G,Y);G.setProp(G.global,"tools",q);let B=G.runtime.hasPendingJob()?G.unwrapResult(await HD6(G,$,Q)):$;if(B!==$)$.dispose();let D=G.getProp(B,"default"),O=G.typeof(D);if(O!=="function")return{error:`Code must export default a function (tools). Got ${O}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(D,G.undefined,q),w=G.unwrapResult(L),I=await HD6(G,w,Q),T=G.unwrapResult(I);if(G.runtime.hasPendingJob())FD6(G);return{returnValue:G.dump(T),consoleLogs:K.logs}}catch(V){return console.log(V),{error:cD(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{PW(W,H,F)}}var L91=(Y)=>new Promise((X)=>setTimeout(X,Y));var VD6=S(()=>{ZD6();KD6()});var $D6=S(()=>{VD6()});async function w91(Y,X){let Q=Y.connections.map((K)=>K.connection_id),J=[];for(let K of Q){let W=await X.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 qD6(Y,X){return(await X.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function M91(Y,X){let Q=new Map;for(let q of Y)Q.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 B=await X.createMCPProxy(q);return{connection:q,proxy:B}}catch(B){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,B),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,B])=>{try{let O=(await B.proxy.listTools()).tools,L=Q.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);O=O.filter((I)=>w.has(I.name))}return{connectionId:q,connectionTitle:B.connection.title,tools:O}}catch(D){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,D),null}})),Z=new Set,H=[],F=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:B,connectionTitle:D,tools:O}=q.value;for(let L of O){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:B,connectionTitle:D}}),F.set(L.name,B)}}let V=async(q,B)=>{let D=F.get(q);if(!D)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let O=G.get(D);if(!O)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await O.proxy.callTool({name:q,arguments:B})},$=[];for(let[,q]of G)$.push(q.proxy.close().catch(()=>{}));return await Promise.all($),{tools:H,callTool:V}}async function iD(Y){let X=h6(Y),Q;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)Q=await w91(J,Y);else Q=await qD6(X.id,Y)}else Q=await qD6(X.id,Y);return M91(Q,Y)}function A91(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function T91(Y,X){let Q=0,J=X.name.toLowerCase(),G=(X.description??"").toLowerCase(),K=(X._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)Q+=10;else if(J.includes(W))Q+=3;if(G.includes(W))Q+=2;if(K.includes(W))Q+=1}return Q}function hx(Y,X,Q){let J=A91(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:T91(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function bx(Y,X){let Q=new Map(X.map((G)=>[G.name,G]));return{tools:Y.map((G)=>Q.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)=>!Q.has(G))}}async function xx(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return g50({code:Y,tools:J,timeoutMs:Q})}function oP(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function C3(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function XK(Y){let X=new Set(P91);return Y.filter((Q)=>!X.has(Q.name))}var P91;var g$=S(()=>{$D6();P91=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var m50;var zD6=S(()=>{z4();aP();g$();m50=J6({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.",inputSchema:CU6,outputSchema:IU6,handler:async(Y,X)=>{D6(X),h6(X),await X.access.check();let Q=await iD(X),J=hx(Y.query,Q.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:Q.tools.length}}})});var l50;var BD6=S(()=>{z4();aP();g$();l50=J6({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.",inputSchema:RU6,outputSchema:jU6,handler:async(Y,X)=>{D6(X),h6(X),await X.access.check();let Q=await iD(X);return bx(Y.tools,Q.tools)}})});var d50;var UD6=S(()=>{z4();aP();g$();d50=J6({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.',inputSchema:SU6,outputSchema:kU6,handler:async(Y,X)=>{D6(X),h6(X),await X.access.check();let Q=await iD(X);return await xx(Y.code,Q,Y.timeoutMs)}})});var DD6=S(()=>{zD6();BD6();UD6();aP()});var C91,I91,p50;var OD6=S(()=>{j5();n0();z4();Sx();sZ();C91=z.object({data:KB6.describe("Data for the new connection (id is auto-generated if not provided)")}),I91=z.object({item:S5.describe("The created connection entity")}),p50=J6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:C91,outputSchema:I91,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=s8(X);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:Q.id,created_by:J};if(G.connection_type==="VIRTUAL"){let H=Tx(G.connection_url);if(!H)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await X.storage.virtualMcps.findById(H);if(!F)throw Error(`Virtual MCP not found: ${H}`);if(F.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Px(H)}let K=await lD({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?.length?K:null,Z=await X.storage.connections.create({...G,tools:W});return await X.eventBus.publish(Q.id,MJ.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function sP(Y,X){if(Y===X)return!0;if(Y==null||X==null)return Y===X;if(typeof Y!==typeof X)return!1;if(Array.isArray(Y)&&Array.isArray(X)){if(Y.length!==X.length)return!1;return Y.every((Q,J)=>sP(Q,X[J]))}if(typeof Y==="object"&&typeof X==="object"){let Q=Object.keys(Y),J=Object.keys(X);if(Q.length!==J.length)return!1;return Q.every((G)=>J.includes(G)&&sP(Y[G],X[G]))}return!1}function o91(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>sP(Q,G)))return!1;return X.push(Q),!0})}}function ux(Y,X){return Y.safeParse(X).success}function cY(Y){if(typeof Y==="boolean")return Y?z.any():z.never();let X={};for(let G of VY1)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||z.string());if(X.number!==!1)Q.push(X.number||z.number());if(X.boolean!==!1)Q.push(X.boolean||z.boolean());if(X.null!==!1)Q.push(X.null||z.null());if(X.array!==!1)Q.push(X.array||z.array(z.any()));if(X.tuple!==!1&&X.tuple!==void 0)Q.push(X.tuple);if(X.object!==!1)if(X.object)Q.push(X.object);else{let G=z.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");Q.push(G)}if(X.file!==!1&&X.file!==void 0)Q.push(X.file);let J;if(Q.length===0)J=z.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=z.any();else J=z.union(Q);for(let G of $Y1)J=G.apply(J,Y);return J}var R91=class{apply(Y,X){if(!X.type)return;let Q=Array.isArray(X.type)?X.type:[X.type],J=new Set(Q);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||z.number();if(G instanceof z.ZodNumber)Y.number=G.int()}}},j91=class{apply(Y,X){if(X.const===void 0)return;let Q=X.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof Q==="string")Y.string=z.literal(Q);else if(typeof Q==="number")Y.number=z.literal(Q);else if(typeof Q==="boolean")Y.boolean=z.literal(Q);else if(Q===null)Y.null=z.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},S91=class{apply(Y,X){if(!X.enum)return;if(X.enum.length===0){if(!X.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let Q={string:X.enum.filter((J)=>typeof J==="string"),number:X.enum.filter((J)=>typeof J==="number"),boolean:X.enum.filter((J)=>typeof J==="boolean"),null:X.enum.filter((J)=>J===null),array:X.enum.filter((J)=>Array.isArray(J)),object:X.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(Q.string,"string"),Y.number=this.createTypeSchema(Q.number,"number"),Y.boolean=this.createTypeSchema(Q.boolean,"boolean"),Y.null=Q.null.length>0?z.null():!1,Y.array=Q.array.length>0?void 0:!1,Y.object=Q.object.length>0?void 0:!1}createTypeSchema(Y,X){if(Y.length===0)return!1;if(Y.length===1)return z.literal(Y[0]);if(X==="string")return z.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return z.union([z.literal(Q),z.literal(J),...G.map((K)=>z.literal(K))])}if(X==="boolean")return z.union([z.literal(!0),z.literal(!1)]);return!1}},k91=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=z.file();if(Q.minLength!==void 0)J=J.min(Q.minLength);if(Q.maxLength!==void 0)J=J.max(Q.maxLength);if(Q.contentMediaType!==void 0)J=J.mime(Q.contentMediaType);Y.file=J,Y.string=!1}}},v91=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if(Y.string===void 0)Y.string=z.string()}}},_91=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||z.string();if(J instanceof z.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},y91=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||z.string();if(J instanceof z.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},f91=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||z.string();if(J instanceof z.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},h91=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)Y.number=J.min(Q.minimum)}}},b91=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)Y.number=J.max(Q.maximum)}}},x91=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},u91=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},g91=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||z.number();if(J instanceof z.ZodNumber)Y.number=J.refine((G)=>{if(Q.multipleOf===0)return!1;let K=G/Q.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},m91=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if(Y.array===void 0)Y.array=z.array(z.any())}}},l91=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||z.array(z.any())).min(Q.minItems)}},d91=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||z.array(z.any())).max(Q.maxItems)}},p91=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||z.array(z.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=cY(Q.items),G=z.array(J);if(Y.array&&Y.array instanceof z.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)Y.array=z.array(z.any()).max(0);else Y.array=Y.array||z.array(z.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||z.array(z.any());else if(Q.prefixItems)Y.array=Y.array||z.array(z.any())}},c91=class{apply(Y,X){if(X.type!=="array")return;let Q=X;if(!Array.isArray(Q.items))return;if(Y.array===!1)return;let J=Q.items.map((K)=>cY(K)),G;if(J.length===0)G=z.tuple([]);else G=z.tuple(J);if(Q.minItems!==void 0&&Q.minItems>J.length)G=!1;if(Q.maxItems!==void 0&&Q.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},n91=class{apply(Y,X){let Q=X;if(Y.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)Y.object=Y.object||z.object({}).passthrough()}},i91=class{apply(Y,X){let Q=X;if(X.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if(Y.object===void 0)Y.object=z.object({}).passthrough()}}},a91=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||z.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},r91=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||z.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},s91=class{apply(Y,X){if(!X.not)return Y;let Q=cY(X.not);return Y.refine((J)=>!ux(Q,J),{message:"Value must not match the 'not' schema"})}},t91=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(o91(),{message:"Array items must be unique"})}},e91=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>cY(J)).reduce((J,G)=>z.intersection(J,G),Y)}},YY1=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?cY(X.anyOf[0]):z.union([cY(X.anyOf[0]),cY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>cY(J))]);return z.intersection(Y,Q)}},XY1=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>cY(J));return Y.refine((J)=>{let G=0;for(let K of Q)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},QY1=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>cY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!ux(G[W],K[W]))return!1;if(K.length>G.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let W=cY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!ux(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},JY1=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof z.ZodObject||Y instanceof z.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=cY(K)}if(Q.required&&Array.isArray(Q.required)){let G=new Set(Q.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(Q.additionalProperties===!1)return z.object(J);else return z.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!cY(K).safeParse(J[G]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let G of Q.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let G=new Set(Object.keys(Q.properties));for(let K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},GY1=class{apply(Y,X){if(!X.enum||X.enum.length===0)return Y;let Q=X.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(Q.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return Q.some((G)=>sP(J,G))},{message:"Value must match one of the enum values"})}},WY1=class{apply(Y,X){if(X.const===void 0)return Y;let Q=X.const;if(typeof Q!=="object"||Q===null)return Y;return Y.refine((J)=>sP(J,Q),{message:"Value must equal the const value"})}},ZY1=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},KY1=class{apply(Y,X){var Q;let J=X;if(!((Q=J.required)==null?void 0:Q.includes("__proto__"))||X.type!==void 0)return Y;return z.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,X){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return X.every((Q)=>Object.prototype.hasOwnProperty.call(Y,Q))}},HY1=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=cY(J.contains),K=(Q=J.minContains)!=null?Q:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let F of Z)if(ux(G,F))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},FY1=class{apply(Y,X){let{default:Q}=X;if(Q===void 0)return Y;if(!Y.safeParse(Q).success)return Y;return Y.default(Q)}},VY1,$Y1;var ND6=S(()=>{Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();Q1();VY1=[new j91,new S91,new R91,new k91,new v91,new m91,new i91,new _91,new y91,new f91,new h91,new b91,new x91,new u91,new g91,new c91,new l91,new d91,new p91,new a91,new r91,new n91],$Y1=[new KY1,new GY1,new WY1,new e91,new YY1,new XY1,new QY1,new JY1,new HY1,new s91,new t91,new FY1,new ZY1]});class c50{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,X)=>{this._socket=new WebSocket(this._url,qY1),this._socket.onerror=(Q)=>{let J="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);X(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let J;try{J=wJ.parse(JSON.parse(Q.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((X,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),X()})}}var qY1="mcp";var LD6=S(()=>{OX()});function zY1(Y){let X=Y;if(!X||typeof X!=="object"||!("method"in X))return null;switch(X.method){case"initialize":{let Q=X?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:X.jsonrpc??"2.0",id:X.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var n50;var wD6=S(()=>{fP();n50=class n50 extends A3{constructor(Y,X){super(Y,X)}send(Y,X){let Q=zY1(Y);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send(Y,X)}}});var MD6,AD6=async(Y,X,Q)=>{let J=BY1(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new MD6({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(Q);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[$,q]of Object.entries(Y.connection.headers??{}))H.set($,q);let F=new URL(Y.connection.url),V=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${V}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},BY1=(Y,X,Q)=>{if(Y.type==="Websocket")return new c50(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...Q??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:X}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:X})}};return new f$(new URL(Y.url),K)}return new n50(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var TD6=S(()=>{CD();Ix();LD6();OX();wD6();MD6=class MD6 extends R5{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},GP,X)}}});function ED6(Y){let X=(Q)=>{if("connection"in Y)return AD6({connection:Y.connection},void 0,Q);return Y.client};return new Proxy({},{get(Q,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return Z;async function G(H,F=J){let V=Y?.debugId?.(),$=V?{"x-trace-debug-id":V}:void 0,{client:q,callStreamableTool:B}=await X($);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:D,isError:O,content:L}=await q.callTool({name:String(F),arguments:H});if(O){let w=L?.[0]?.text,I=typeof w==="string"?UY1(w):null,T=I?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(I.code,I.message,I.traceId):null;if(T)throw T;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(D??L)}`)}return D}async function K(){let{client:H}=await X(),{tools:F}=await H.listTools();return F}async function W(){if(!("connection"in Y))return K();let H=Y.connection,F=JSON.stringify(H);try{if(!gx.has(F))gx.set(F,K());return await gx.get(F)}catch(V){console.error("Failed to list tools",V),gx.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>PD6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return PD6(F,G)},G}})}var UY1=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},gx,PD6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?cY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?cY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var CD6=S(()=>{ND6();TD6();gx=new Map});function mx(Y){return ED6(Y)}var cV8;var ID6=S(()=>{CD6();cV8=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>mx({connection:Q});return global[X]}})});function lx(Y){return{isImplementedBy:(X)=>{for(let Q of Y){let J=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,G=X.find((K)=>J.test(K.name));if(!G&&Q.opt)continue;if(!G)return!1}return!0}}}var m$=(Y)=>{return{...lx(Y),forClient:(X)=>{return mx({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return mx({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var tP=S(()=>{ID6()});var i50,oV8;var RD6=S(()=>{_T();i50=f4(vT(),1),oV8=i50.createContext(null)});function JK(Y){return z.object({items:z.array(Y).describe("Array of collection items"),totalCount:z.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:z.boolean().optional().describe("Whether there are more items available")})}function Y2(Y){return z.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function NY1(Y){return z.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function LY1(Y){return z.object({item:Y.describe("The created entity with generated id")})}function wY1(Y){return z.object({id:z.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function MY1(Y){return z.object({item:Y.describe("The updated entity")})}function Q2(Y){return z.object({item:Y.describe("The deleted entity")})}function rD(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:QK,outputSchema:JK(X)},{name:`COLLECTION_${J}_GET`,inputSchema:eP,outputSchema:Y2(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:NY1(X),outputSchema:LY1(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:wY1(X),outputSchema:MY1(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:X2,outputSchema:Q2(X),opt:!0});return K}var aD,DY1,jD6,OY1,QK,eP,X2;var k5=S(()=>{n0();aD=z.object({id:z.string().describe("Unique identifier for the entity"),title:z.string().describe("Human-readable title for the entity"),description:z.string().nullish().describe("Description of the entity"),created_at:z.string().datetime(),updated_at:z.string().datetime(),created_by:z.string().optional(),updated_by:z.string().optional()}),DY1=z.object({field:z.array(z.string()),operator:z.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:z.unknown()}),jD6=z.lazy(()=>z.union([DY1,z.object({operator:z.enum(["and","or","not"]),conditions:z.array(jD6)})])),OY1=z.object({field:z.array(z.string()),direction:z.enum(["asc","desc"]),nulls:z.enum(["first","last"]).optional()}),QK=z.object({where:jD6.optional().describe("Filter expression"),orderBy:z.array(OY1).optional().describe("Sort expressions"),limit:z.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:z.number().int().min(0).optional().describe("Number of items to skip")});eP=z.object({id:z.string().describe("ID of the entity to retrieve")});X2=z.object({id:z.string().describe("ID of the entity to delete")})});var AY1,SD6,J$8;var kD6=S(()=>{n0();k5();AY1=z.object({id:z.string(),name:z.string(),description:z.string().optional(),inputSchema:z.record(z.string(),z.unknown()),outputSchema:z.record(z.string(),z.unknown()).optional()}),SD6=aD.extend({_meta:z.object({"io.decocms":z.object({id:z.string(),verified:z.boolean(),scopeName:z.string(),appName:z.string(),friendlyName:z.string().nullable().optional(),metadata:z.record(z.string(),z.unknown()).nullable().optional(),publishedAt:z.string().datetime().optional(),updatedAt:z.string().datetime().optional(),tools:z.array(AY1).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:z.object({$schema:z.string().optional(),_meta:z.record(z.string(),z.unknown()).optional(),name:z.string().describe("The server name (scope/app)"),title:z.string().optional().describe("User-friendly title"),description:z.string().optional().describe("Server description"),icons:z.array(z.object({src:z.string(),mimeType:z.string().optional(),sizes:z.array(z.string()).optional(),theme:z.enum(["light","dark"]).optional()})).optional(),remotes:z.array(z.object({type:z.enum(["http","stdio","sse"]),url:z.string().optional(),headers:z.array(z.unknown()).optional()})).optional(),packages:z.array(z.unknown()).optional(),repository:z.object({url:z.string(),source:z.string().optional(),subfolder:z.string().optional()}).optional(),version:z.string().optional(),websiteUrl:z.string().optional()})}),J$8=rD("registry_app",SD6,{readOnly:!0})});var vD6,_D6,yD6,fD6,hD6,a50;var bD6=S(()=>{n0();tP();vD6=z.object({specversion:z.literal("1.0").describe("CloudEvents specification version"),id:z.string().describe("Unique identifier for this event (UUID recommended)"),source:z.string().describe("Connection ID of the event publisher"),type:z.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:z.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:z.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:z.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:z.string().url().optional().describe("URI to the schema for the data attribute"),data:z.unknown().optional().describe("Event payload (any JSON value)")}),_D6=z.object({events:z.array(vD6).min(1).describe("Batch of CloudEvents to process")}),yD6=z.object({success:z.boolean().optional().describe("Whether this event was processed successfully"),error:z.string().optional().describe("Error message for this event"),retryAfter:z.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),fD6=z.object({success:z.boolean().optional().describe("Batch success - applies to events not in results"),error:z.string().optional().describe("Batch error message - applies to events not in results"),processedCount:z.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:z.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:z.record(z.string(),yD6).optional().describe("Per-event results keyed by event ID")}),hD6=[{name:"ON_EVENTS",inputSchema:_D6,outputSchema:fD6}],a50=m$(hD6)});var J2,G2,W2,Z2,xD6,uD6,K2,H2,F2,V2,$2,q2,z2,B2,gD6,TY1;var mD6=S(()=>{n0();tP();J2=z.object({type:z.string().min(1).max(255).describe("Event type identifier"),subject:z.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:z.unknown().optional().describe("Event payload"),deliverAt:z.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:z.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),G2=z.object({id:z.string().describe("Unique event ID"),type:z.string().describe("Event type"),source:z.string().describe("Source connection ID"),time:z.string().describe("Event timestamp")}),W2=z.object({eventType:z.string().min(1).max(255).describe("Event type to subscribe to"),publisher:z.string().optional().describe("Filter events by publisher connection ID"),filter:z.string().max(1000).optional().describe("JSONPath filter expression on event data")}),Z2=z.object({subscription:z.object({id:z.string().describe("Subscription ID"),connectionId:z.string().describe("Subscriber connection ID"),eventType:z.string().describe("Event type pattern"),publisher:z.string().nullable().describe("Publisher connection filter"),filter:z.string().nullable().describe("JSONPath filter expression"),enabled:z.boolean().describe("Whether subscription is enabled"),createdAt:z.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:z.string().datetime().describe("Updated timestamp (ISO 8601)")})}),xD6=z.object({eventType:z.string().min(1).max(255).describe("Event type to subscribe to"),publisher:z.string().optional().describe("Filter events by publisher connection ID"),filter:z.string().max(1000).optional().describe("JSONPath filter expression on event data")}),uD6=z.object({id:z.string().describe("Subscription ID"),connectionId:z.string().describe("Subscriber connection ID"),eventType:z.string().describe("Event type pattern"),publisher:z.string().nullable().describe("Publisher connection filter"),filter:z.string().nullable().describe("JSONPath filter expression"),enabled:z.boolean().describe("Whether subscription is enabled"),createdAt:z.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:z.string().datetime().describe("Updated timestamp (ISO 8601)")}),K2=z.object({subscriptions:z.array(xD6).describe("Desired subscriptions - system will create/update/delete to match")}),H2=z.object({created:z.number().int().min(0).describe("Number of subscriptions created"),updated:z.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:z.number().int().min(0).describe("Number of subscriptions removed"),unchanged:z.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:z.array(uD6).describe("Current subscriptions after sync")}),F2=z.object({subscriptionId:z.string().describe("Subscription ID to remove")}),V2=z.object({success:z.boolean().describe("Whether unsubscribe was successful"),subscriptionId:z.string().describe("Subscription ID that was removed")}),$2=z.object({eventId:z.string().describe("Event ID to cancel")}),q2=z.object({success:z.boolean().describe("Whether cancellation was successful"),eventId:z.string().describe("Event ID that was cancelled")}),z2=z.object({eventId:z.string().describe("Event ID to acknowledge")}),B2=z.object({success:z.boolean().describe("Whether ACK was successful"),eventId:z.string().describe("Event ID that was acknowledged")}),gD6=[{name:"EVENT_PUBLISH",inputSchema:J2,outputSchema:G2},{name:"EVENT_SUBSCRIBE",inputSchema:W2,outputSchema:Z2},{name:"EVENT_UNSUBSCRIBE",inputSchema:F2,outputSchema:V2},{name:"EVENT_CANCEL",inputSchema:$2,outputSchema:q2},{name:"EVENT_ACK",inputSchema:z2,outputSchema:B2},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:K2,outputSchema:H2}],TY1=m$(gD6)});var PY1,EY1,CY1,IY1,RY1,jY1,SY1,kY1,vY1,_Y1,yY1,fY1,U2;var dx=S(()=>{n0();PY1=z.object({prefix:z.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:z.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:z.string().optional().describe("Token for pagination from previous response"),delimiter:z.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),EY1=z.object({objects:z.array(z.object({key:z.string().describe("Object key/path"),size:z.number().describe("Object size in bytes"),lastModified:z.string().describe("Last modified timestamp"),etag:z.string().describe("Entity tag for the object")})),nextContinuationToken:z.string().optional().describe("Token for fetching next page of results"),isTruncated:z.boolean().describe("Whether there are more results available"),commonPrefixes:z.array(z.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),CY1=z.object({key:z.string().describe("Object key/path to get metadata for")}),IY1=z.object({contentType:z.string().optional().describe("MIME type of the object"),contentLength:z.number().describe("Size of the object in bytes"),lastModified:z.string().describe("Last modified timestamp"),etag:z.string().describe("Entity tag for the object"),metadata:z.record(z.string(),z.string()).optional().describe("Custom metadata key-value pairs")}),RY1=z.object({key:z.string().describe("Object key/path to generate URL for"),expiresIn:z.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),jY1=z.object({url:z.string().describe("Presigned URL for downloading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),SY1=z.object({key:z.string().describe("Object key/path for the upload"),expiresIn:z.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:z.string().optional().describe("MIME type for the object being uploaded")}),kY1=z.object({url:z.string().describe("Presigned URL for uploading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),vY1=z.object({key:z.string().describe("Object key/path to delete")}),_Y1=z.object({success:z.boolean().describe("Whether the deletion was successful"),key:z.string().describe("The key that was deleted")}),yY1=z.object({keys:z.array(z.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),fY1=z.object({deleted:z.array(z.string()).describe("Array of successfully deleted keys"),errors:z.array(z.object({key:z.string(),message:z.string()})).describe("Array of errors for failed deletions")}),U2=[{name:"LIST_OBJECTS",inputSchema:PY1,outputSchema:EY1},{name:"GET_OBJECT_METADATA",inputSchema:CY1,outputSchema:IY1},{name:"GET_PRESIGNED_URL",inputSchema:RY1,outputSchema:jY1},{name:"PUT_PRESIGNED_URL",inputSchema:SY1,outputSchema:kY1},{name:"DELETE_OBJECT",inputSchema:vY1,outputSchema:_Y1},{name:"DELETE_OBJECTS",inputSchema:yY1,outputSchema:fY1}]});var px=S(()=>{tP();RD6();kD6();bD6();mD6();dx()});var hY1,bY1,lD6;var dD6=S(()=>{n0();k5();hY1=aD.extend({avatar:z.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:z.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:z.string().describe("Virtual MCP ID to use for this assistant"),model:z.object({id:z.string().describe("Model ID"),connectionId:z.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),bY1=rD("assistant",hY1),lD6=[...bY1]});var D2,GK,cD6,xY1,uY1,nD6,gY1,mY1,lY1,dY1,pY1,cY1,iD6,nY1,iY1,aY1,rY1,oY1,sY1,tY1,eY1,YX1,XX1,S$8,QX1,k$8,pD6,JX1,GX1,r50,O2;var cx=S(()=>{n0();tP();k5();D2=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),D2),z.array(D2)])),GK=z.record(z.string(),z.record(z.string(),D2)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),cD6=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerOptions:GK}),xY1=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),uY1=z.string().describe("File data as URL string"),nD6=z.object({type:z.literal("file"),filename:z.string().optional().describe("Optional filename of the file"),data:uY1,mediaType:z.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:GK}),gY1=z.object({type:z.literal("file"),mediaType:z.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:z.string().describe("Generated file data as base64 encoded string")}),mY1=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerOptions:GK}),lY1=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),dY1=z.object({type:z.literal("tool-call"),toolCallId:z.string().describe("ID of the tool call, used to match with tool result"),toolName:z.string().describe("Name of the tool being called"),input:z.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:z.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:GK}),pY1=z.object({type:z.literal("tool-call"),toolCallId:z.string().describe("ID of the tool call"),toolName:z.string().describe("Name of the tool being called"),input:z.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:z.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),cY1=z.union([z.object({type:z.literal("text"),value:z.string()}),z.object({type:z.literal("json"),value:D2}),z.object({type:z.literal("error-text"),value:z.string()}),z.object({type:z.literal("error-json"),value:D2}),z.object({type:z.literal("content"),value:z.array(z.union([z.object({type:z.literal("text"),text:z.string().describe("Text content")}),z.object({type:z.literal("media"),data:z.string().describe("Base-64 encoded media data"),mediaType:z.string().describe("IANA media type")})]))})]),iD6=z.object({type:z.literal("tool-result"),toolCallId:z.string().describe("ID of the tool call that this result is associated with"),toolName:z.string().describe("Name of the tool that generated this result"),output:cY1.describe("Result of the tool call"),result:z.unknown().describe("Unknown result of the tool call"),providerOptions:GK}),nY1=z.object({type:z.literal("tool-result"),toolCallId:z.string().describe("ID of the tool call that this result is associated with"),toolName:z.string().describe("Name of the tool that generated this result"),result:z.any().describe("Result of the tool call (JSON-serializable)"),isError:z.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:z.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),iY1=z.union([z.object({type:z.literal("source"),sourceType:z.literal("url"),id:z.string().describe("The ID of the source"),url:z.string().describe("The URL of the source"),title:z.string().optional().describe("The title of the source"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),z.object({type:z.literal("source"),sourceType:z.literal("document"),id:z.string().describe("The ID of the source"),mediaType:z.string().describe("IANA media type of the document (e.g., application/pdf)"),title:z.string().describe("The title of the document"),filename:z.string().optional().describe("Optional filename of the document"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")})]),aY1=z.object({role:z.literal("system"),content:z.string().describe("System message content"),providerOptions:GK}),rY1=z.object({role:z.literal("user"),content:z.array(z.union([cD6,nD6])).describe("User message content parts (text or file)"),providerOptions:GK}),oY1=z.object({role:z.literal("assistant"),content:z.array(z.union([cD6,nD6,mY1,dY1,iD6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:GK}),sY1=z.object({role:z.literal("tool"),content:z.array(iD6).describe("Tool message content (tool results)"),providerOptions:GK}),tY1=z.union([aY1,rY1,oY1,sY1]),eY1=z.array(tY1).describe("A list of messages forming the prompt"),YX1=z.object({prompt:eY1.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:z.number().optional().describe("Maximum number of tokens to generate"),temperature:z.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:z.number().optional().describe("Nucleus sampling parameter"),topK:z.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:z.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:z.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:z.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:z.array(z.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:z.union([z.object({type:z.literal("text")}),z.object({type:z.literal("json"),schema:z.any().optional().describe("JSON schema that the generated output should conform to"),name:z.string().optional().describe("Name of output that should be generated"),description:z.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:z.array(z.any()).optional().describe("The tools that are available for the model"),toolChoice:z.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:z.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:z.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:z.any().optional().describe("Additional provider-specific options")}),XX1=z.object({content:z.array(z.union([xY1,gY1,lY1,pY1,nY1,iY1])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:z.looseObject({inputTokens:z.number().optional(),outputTokens:z.number().optional(),totalTokens:z.number().optional(),reasoningTokens:z.number().optional()}).describe("Usage information for the language model call"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata"),request:z.object({body:z.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:z.object({id:z.string().optional().describe("ID for the generated response"),timestamp:z.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:z.string().optional().describe("The ID of the response model that was used"),headers:z.record(z.string(),z.string()).optional().describe("Response headers"),body:z.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:z.array(z.any()).describe("Warnings for the call, e.g. unsupported settings")}),S$8=z.object({stream:z.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:z.object({body:z.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:z.object({headers:z.record(z.string(),z.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),QX1=z.object({supportedUrls:z.record(z.string(),z.array(z.string())).describe("Supported URL patterns by media type for the provider")}),k$8=z.object({modelId:z.string().describe("The ID of the model"),logo:z.string().nullable(),description:z.string().nullable(),capabilities:z.array(z.string()),limits:z.object({contextWindow:z.number(),maxOutputTokens:z.number()}).nullable(),costs:z.object({input:z.number(),output:z.number()}).nullable(),provider:z.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),pD6=z.object({modelId:z.string().describe("The ID of the model"),callOptions:YX1}),JX1=aD.extend({logo:z.string().nullable(),description:z.string().nullable(),capabilities:z.array(z.string()),limits:z.object({contextWindow:z.number(),maxOutputTokens:z.number()}).nullable(),costs:z.object({input:z.number(),output:z.number()}).nullable(),provider:z.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),GX1=rD("llm",JX1,{readOnly:!0}),r50=[{name:"LLM_METADATA",inputSchema:z.object({modelId:z.string().describe("The ID of the model")}),outputSchema:QX1},{name:"LLM_DO_STREAM",inputSchema:pD6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:pD6,outputSchema:XX1},...GX1],O2=m$(r50)});function nx(){return!1}function aD6(Y,X){return Y===MJ.DEV_ASSETS(X)}function ix(Y,X){let Q=hJ0(X,Y),J=new Date().toISOString();return{id:Q.id??MJ.DEV_ASSETS(Y),title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:Q.app_name??null,app_id:Q.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:Q.connection_type,connection_url:Q.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata??null,tools:WX1,bindings:["OBJECT_STORAGE"],status:"active"}}var WX1;var o50=S(()=>{dx();j5();n0();WX1=U2.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:z.toJSONSchema(Y.inputSchema),outputSchema:z.toJSONSchema(Y.outputSchema)}))});function KX1(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function I3(Y){return typeof Y==="string"||typeof Y==="number"}function ax(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>ax(Y,F));case"or":return H.some((F)=>ax(Y,F));case"not":return!H.every((F)=>ax(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=s50(Y,K);switch(J){case"eq":return W===G;case"gt":return I3(W)&&I3(G)&&W>G;case"gte":return I3(W)&&I3(G)&&W>=G;case"lt":return I3(W)&&I3(G)&&W<G;case"lte":return I3(W)&&I3(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=KX1(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 s50(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function HX1(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=s50(Q,K),Z=s50(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 ZX1,FX1,VX1,t50;var rD6=S(()=>{px();dD6();k5();cx();dx();j5();n0();z4();o50();sZ();ZX1={LLM:r50,ASSISTANTS:lD6,OBJECT_STORAGE:U2};FX1=QK.extend({binding:z.union([z.object({}).passthrough(),z.string()]).optional()}),VX1=JK(S5),t50=J6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:FX1,outputSchema:VX1,handler:async(Y,X)=>{await X.access.check();let Q=h6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=ZX1[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?lx(J):void 0,K=await X.storage.connections.list(Q.id);if(nx()){let B=t5(),D=MJ.DEV_ASSETS(Q.id);if(!K.some((O)=>O.id===D)){let O=ix(Q.id,B);K.unshift(O)}}let W=K.filter((B)=>B.connection_type!=="VIRTUAL"),Z=G?await Promise.all(W.map(async(B)=>{if(!B.tools||B.tools.length===0)return null;return G.isImplementedBy(B.tools.map((O)=>({name:O.name,inputSchema:O.inputSchema,outputSchema:O.outputSchema})))?B:null})).then((B)=>B.filter((D)=>D!==null)):W;if(Y.where)Z=Z.filter((B)=>ax(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=HX1(Z,Y.orderBy);let H=Z.length,F=Y.offset??0,V=Y.limit??100,$=Z.slice(F,F+V),q=F+V<H;return{items:$,totalCount:H,hasMore:q}}})});var $X1,e50;var oD6=S(()=>{k5();z4();o50();sZ();$X1=Y2(S5),e50=J6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:eP,outputSchema:$X1,handler:async(Y,X)=>{let Q=h6(X);if(await X.access.check(),nx()&&aD6(Y.id,Q.id))return{item:ix(Q.id,t5())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var rx=(Y,X)=>{if(X===null||X===void 0)return;let Q=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=X;for(let G of Q){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function sD6(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return X}function qX1(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function zX1(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function YG0(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=qX1(J);if(!G)continue;let[K,W]=G,Z=rx(K,Y),H=zX1(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function tD6(Y,X){let Q=YG0(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var XG0=()=>{};class WK{db;vault;constructor(Y,X){this.db=Y;this.vault=X}async get(Y){let X=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!X)return null;return this.decryptToken(X)}async upsert(Y){let X=new Date().toISOString(),Q=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:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:X}).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:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=B9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:Q,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:X,updatedAt:X}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:X,updatedAt:X,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,X=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-X<Date.now()}async decryptToken(Y){let X=await this.vault.decrypt(Y.accessToken),Q=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:X,refreshToken:Q,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var ox=S(()=>{tZ()});async function DX1(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=sD6(K),Z=rx(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=tD6(Y,X);for(let K of G){if(K.endsWith("_self"))continue;let W=await J.storage.connections.findById(K);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${K}`);try{await J.access.check(K)}catch(Z){throw Error(`Access denied to referenced connection: ${K}. ${Z.message}`)}}}var BX1,UX1,QG0;var eD6=S(()=>{XG0();ox();n0();z4();Sx();sZ();BX1=z.object({id:z.string().describe("ID of the connection to update"),data:HB6.describe("Partial connection data to update")}),UX1=z.object({item:S5.describe("The updated connection entity")});QG0=J6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:BX1,outputSchema:UX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);if(await X.access.check(),!s8(X))throw Error("User ID required to update connection");let{id:G,data:K}=Y,W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let Z=K.connection_type??W.connection_type,H=K.connection_url??W.connection_url;if(Z==="VIRTUAL"){let A=Tx(H);if(!A)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let R=await X.storage.virtualMcps.findById(A);if(!R)throw Error(`Virtual MCP not found: ${A}`);if(R.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=Px(A)}let F=K.configuration_state??W.configuration_state,V=K.configuration_scopes??W.configuration_scopes??[];if(K.configuration_state!==void 0||K.configuration_scopes!==void 0){if(K.configuration_state!==void 0)F=K.configuration_state;else if(F===null)F={};if(K.configuration_scopes!==void 0)V=K.configuration_scopes??[];if(V.length>0&&F)await DX1(F,V,Q.id,X)}let $=K.connection_token??W.connection_token;if(!$)try{let R=await new WK(X.db,X.vault).get(G);if(R?.accessToken)$=R.accessToken}catch{}let q=await lD({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:$,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=q?.length?q:null,D={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:V},O=await X.storage.connections.update(G,D);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&V.length>0)try{let L=[];try{const A=gG(L,await X.createMCPProxy(G),1);await A.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:V}});await A.close().catch(console.error)}catch(w){var I=w,T=1}finally{var P=PW(L,I,T);P&&await P}}catch(A){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",A)}return{item:O}}})});var JG0;var YO6=S(()=>{k5();z4();sZ();JG0=J6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:X2,outputSchema:Q2(S5),handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J)throw Error(`Connection not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error("Connection not found in organization");if(J.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");return await X.storage.connections.delete(Y.id),{item:J}}})});var GG0;var XO6=S(()=>{n0();z4();GG0=J6({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:z.object({id:z.string()}),outputSchema:z.object({id:z.string(),healthy:z.boolean(),latencyMs:z.number()}),handler:async(Y,X)=>{let Q=h6(X);await X.access.check();let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)throw Error("Connection not found");let G=await X.storage.connections.testConnection(Y.id);return{id:Y.id,...G}}})});var QO6=S(()=>{OD6();rD6();oD6();eD6();YO6();XO6()});import{sql as K1}from"kysely";function JO6(Y){if(Y===null||Y===void 0)return"NULL";if(typeof Y==="number")return String(Y);if(typeof Y==="boolean")return Y?"TRUE":"FALSE";if(typeof Y==="string")return`'${Y.replace(/'/g,"''")}'`;if(Y instanceof Date)return`'${Y.toISOString()}'`;return`'${JSON.stringify(Y).replace(/'/g,"''")}'`}function LX1(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,JO6(X[G-1]))}let J=[];for(let G=0;G<Q.length;G++)if(Q[G]==="?")J.push(G);for(let G=Math.min(J.length,X.length)-1;G>=0;G--){let K=J[G],W=JO6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function GO6(Y){return Y.replace(/-/g,"_")}function MX1(Y){return`app_${GO6(Y)}`}function AX1(Y){return`app_role_${GO6(Y)}`}function TX1(Y){if(Y instanceof Error){let X=Y.message.toLowerCase(),Q=Y.code;return Q==="3F000"||Q==="42704"||X.includes("schema")&&X.includes("does not exist")||X.includes("role")&&X.includes("does not exist")}return!1}async function PX1(Y,X,Q){if(await K1`CREATE SCHEMA IF NOT EXISTS ${K1.id(X)}`.execute(Y),!(await K1`
|
|
1183
1183
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
1184
1184
|
`.execute(Y)).rows[0]?.exists)await K1`CREATE ROLE ${K1.id(Q)} NOLOGIN`.execute(Y);await K1`GRANT ${K1.id(Q)} TO CURRENT_USER`.execute(Y),await K1`GRANT USAGE, CREATE ON SCHEMA ${K1.id(X)} TO ${K1.id(Q)}`.execute(Y),await K1`GRANT ALL ON ALL TABLES IN SCHEMA ${K1.id(X)} TO ${K1.id(Q)}`.execute(Y),await K1`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${K1.id(X)} TO ${K1.id(Q)}`.execute(Y),await K1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${K1.id(X)} GRANT ALL ON TABLES TO ${K1.id(Q)}`.execute(Y),await K1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${K1.id(X)} GRANT ALL ON SEQUENCES TO ${K1.id(Q)}`.execute(Y),await K1`REVOKE ALL ON SCHEMA public FROM ${K1.id(Q)}`.execute(Y)}async function EX1(Y,X,Q,J){try{return await Y.transaction().execute(async(G)=>{return await K1`SET LOCAL ROLE ${K1.id(Q)}`.execute(G),await K1`SET LOCAL search_path TO ${K1.id(X)}`.execute(G),await K1.raw(J).execute(G)})}catch(G){if(TX1(G))return await PX1(Y,X,Q),await Y.transaction().execute(async(K)=>{return await K1`SET LOCAL ROLE ${K1.id(Q)}`.execute(K),await K1`SET LOCAL search_path TO ${K1.id(X)}`.execute(K),await K1.raw(J).execute(K)});throw G}}var NX1,wX1,WO6;var ZO6=S(()=>{n0();z4();NX1=z.object({results:z.array(z.unknown()).optional(),success:z.boolean().optional()});wX1=z.object({sql:z.string().describe("The SQL query to run"),params:z.array(z.any()).describe("The parameters to pass to the SQL query").optional()});WO6=J6({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:wX1,outputSchema:z.object({result:z.array(NX1)}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=LX1(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=MX1(X.connectionId),G=AX1(X.connectionId);return{result:[{results:(await EX1(X.db,J,G,Q)).rows,success:!0}]}}})});var KO6,IX1,HO6;var ZK=S(()=>{n0();px();KO6=z.object({connectionId:z.string().optional().describe("Filter subscriptions by connection ID (optional)")}),IX1=z.object({id:z.string().describe("Subscription ID"),connectionId:z.string().describe("Subscriber connection ID"),eventType:z.string().describe("Event type pattern"),publisher:z.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:z.string().nullable().describe("JSONPath filter expression"),enabled:z.boolean().describe("Whether subscription is enabled"),createdAt:z.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:z.string().datetime().describe("Updated timestamp (ISO 8601)")}),HO6=z.object({subscriptions:z.array(IX1).describe("List of subscriptions")})});var WG0;var FO6=S(()=>{z4();ZK();WG0=J6({name:"EVENT_PUBLISH",description:"Publish an event to the event bus. Supports immediate, scheduled (deliverAt), and recurring (cron) delivery. The source is automatically set to the caller's connection ID.",inputSchema:J2,outputSchema:G2,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to publish events. Use a connection-scoped token.");let G=await X.eventBus.publish(Q.id,J,{type:Y.type,subject:Y.subject,data:Y.data,deliverAt:Y.deliverAt,cron:Y.cron});return{id:G.id,type:G.type,source:G.source,time:G.time}}})});var ZG0;var VO6=S(()=>{z4();ZK();ZG0=J6({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:W2,outputSchema:Z2,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to subscribe. Use a connection-scoped token.");let G=await X.eventBus.subscribe(Q.id,{connectionId:J,eventType:Y.eventType,publisher:Y.publisher,filter:Y.filter});return{subscription:{id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}})});var KG0;var $O6=S(()=>{z4();ZK();KG0=J6({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:F2,outputSchema:V2,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to unsubscribe. Use a connection-scoped token.");let G=await X.eventBus.getSubscription(Q.id,Y.subscriptionId);if(!G)throw Error(`Subscription not found: ${Y.subscriptionId}`);if(G.connectionId!==J)throw Error("Cannot unsubscribe from a subscription owned by another connection");return{success:(await X.eventBus.unsubscribe(Q.id,Y.subscriptionId)).success,subscriptionId:Y.subscriptionId}}})});var HG0;var qO6=S(()=>{z4();ZK();HG0=J6({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:$2,outputSchema:q2,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to cancel events. Use a connection-scoped token.");if(!await X.eventBus.getEvent(Q.id,Y.eventId))throw Error(`Event not found: ${Y.eventId}`);if(!(await X.eventBus.cancelEvent(Q.id,Y.eventId,J)).success)throw Error("Failed to cancel event. Either the event is already completed/failed, or you are not the publisher.");return{success:!0,eventId:Y.eventId}}})});var FG0;var zO6=S(()=>{z4();ZK();FG0=J6({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:z2,outputSchema:B2,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to acknowledge events. Use a connection-scoped token.");if(!(await X.eventBus.ackEvent(Q.id,Y.eventId,J)).success)throw Error("Failed to acknowledge event. Either the event was not found, already delivered, or you are not a subscriber.");return{success:!0,eventId:Y.eventId}}})});var VG0;var BO6=S(()=>{z4();ZK();VG0=J6({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:KO6,outputSchema:HO6,handler:async(Y,X)=>{D6(X);let Q=h6(X);return await X.access.check(),{subscriptions:(await X.eventBus.listSubscriptions(Q.id,Y.connectionId)).map((G)=>({id:G.id,connectionId:G.connectionId,eventType:G.eventType,publisher:G.publisher,filter:G.filter,enabled:G.enabled,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}))}}})});var $G0;var UO6=S(()=>{z4();ZK();$G0=J6({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:K2,outputSchema:H2,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=X.connectionId;if(!J)throw Error("Connection ID required to sync subscriptions. Use a connection-scoped token.");let G=await X.eventBus.syncSubscriptions(Q.id,{connectionId:J,subscriptions:Y.subscriptions});return{created:G.created,updated:G.updated,deleted:G.deleted,unchanged:G.unchanged,subscriptions:G.subscriptions.map((K)=>({id:K.id,connectionId:K.connectionId,eventType:K.eventType,publisher:K.publisher,filter:K.filter,enabled:K.enabled,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt,updatedAt:K.updatedAt instanceof Date?K.updatedAt.toISOString():K.updatedAt}))}}})});var DO6=S(()=>{FO6();VO6();$O6();qO6();zO6();BO6();UO6();ZK()});var jX1,UW,OO6,NO6;var oD=S(()=>{n0();jX1=z.object({connection_id:z.string().describe("Connection ID"),selected_tools:z.array(z.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:z.array(z.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:z.array(z.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),UW=z.object({id:z.string().nullable().describe("Unique identifier for the virtual MCP (null for synthetic Decopilot agent)"),title:z.string().describe("Human-readable name for the virtual MCP"),description:z.string().nullable().describe("Description of the virtual MCP"),icon:z.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:z.string().describe("When the virtual MCP was created"),updated_at:z.string().describe("When the virtual MCP was last updated"),created_by:z.string().describe("User ID who created the virtual MCP"),updated_by:z.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:z.string().describe("Organization ID this virtual MCP belongs to"),status:z.enum(["active","inactive"]).describe("Current status"),metadata:z.object({instructions:z.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:z.array(jX1).describe("Connections with their selected tools, resources, and prompts")}),OO6=z.object({title:z.string().min(1).max(255).describe("Name for the virtual MCP"),description:z.string().nullable().optional().describe("Optional description"),icon:z.string().nullable().optional().describe("Optional icon URL"),status:z.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:z.object({instructions:z.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:z.array(z.object({connection_id:z.string().describe("Connection ID"),selected_tools:z.array(z.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools included)"),selected_resources:z.array(z.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources included)"),selected_prompts:z.array(z.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts included)")})).describe("Connections to include with their selected tools/resources/prompts")}),NO6=z.object({title:z.string().min(1).max(255).optional().describe("New name"),description:z.string().nullable().optional().describe("New description (null to clear)"),icon:z.string().nullable().optional().describe("New icon URL (null to clear)"),status:z.enum(["active","inactive"]).optional().describe("New status"),metadata:z.object({instructions:z.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:z.array(z.object({connection_id:z.string().describe("Connection ID"),selected_tools:z.array(z.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools included)"),selected_resources:z.array(z.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources included)"),selected_prompts:z.array(z.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts included)")})).optional().describe("New connections (replaces existing)")})});var SX1,kX1,qG0;var LO6=S(()=>{n0();z4();oD();SX1=z.object({data:OO6.describe("Data for the new virtual MCP")}),kX1=z.object({item:UW.describe("The created virtual MCP entity")}),qG0=J6({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:SX1,outputSchema:kX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=s8(X);if(!J)throw Error("User ID required to create virtual MCP");return{item:await X.storage.virtualMcps.create(Q.id,J,Y.data)}}})});function vX1(Y){let X=[],Q=0;while(Q<Y.length){let J=Y[Q];if(J==="%")X.push(".*");else if(J==="_")X.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))X.push("\\"+J);else X.push(J);Q++}return X.join("")}function R3(Y){return typeof Y==="string"||typeof Y==="number"}function zG0(Y,X){let Q=X.split("."),J=Y;for(let G of Q){if(J==null||typeof J!=="object")return;J=J[G]}return J}function _X1(Y,X){return Y.connections.some((Q)=>Q.connection_id===X)}function sx(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>sx(Y,F));case"or":return H.some((F)=>sx(Y,F));case"not":return!H.every((F)=>sx(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join(".");if(K==="connection_id"){if(J!=="eq"||typeof G!=="string")return!1;return _X1(Y,G)}let W=zG0(Y,K);switch(J){case"eq":return W===G;case"gt":return R3(W)&&R3(G)&&W>G;case"gte":return R3(W)&&R3(G)&&W>=G;case"lt":return R3(W)&&R3(G)&&W<G;case"lte":return R3(W)&&R3(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=vX1(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 yX1(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=zG0(Q,K),Z=zG0(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 fX1,hX1,BG0;var wO6=S(()=>{k5();z4();oD();fX1=QK,hX1=JK(UW),BG0=J6({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:fX1,outputSchema:hX1,handler:async(Y,X)=>{await X.access.check();let Q=h6(X),J=Y.where&&!("conditions"in Y.where)&&Y.where.field.join(".")==="connection_id"&&Y.where.operator==="eq"&&typeof Y.where.value==="string"?Y.where.value:void 0,K=J?await X.storage.virtualMcps.listByConnectionId(Q.id,J):await X.storage.virtualMcps.list(Q.id);if(Y.where)K=K.filter(($)=>sx($,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=yX1(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,F=K.slice(Z,Z+H),V=Z+H<W;return{items:F,totalCount:W,hasMore:V}}})});var bX1,xX1,UG0;var MO6=S(()=>{n0();z4();oD();bX1=z.object({id:z.string().describe("ID of the virtual MCP to retrieve")}),xX1=z.object({item:UW.nullable().describe("The retrieved virtual MCP, or null if not found")}),UG0=J6({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:bX1,outputSchema:xX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.id);if(J&&J.organization_id!==Q.id)return{item:null};if(!J)return{item:null};return{item:J}}})});var uX1,gX1,DG0;var AO6=S(()=>{n0();z4();oD();uX1=z.object({id:z.string().describe("ID of the virtual MCP to update"),data:NO6.describe("Partial virtual MCP data to update")}),gX1=z.object({item:UW.describe("The updated virtual MCP entity")}),DG0=J6({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:uX1,outputSchema:gX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=s8(X);if(!J)throw Error("User ID required to update virtual MCP");let G=await X.storage.virtualMcps.findById(Y.id);if(!G)throw Error(`Virtual MCP not found: ${Y.id}`);if(G.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.id}`);return{item:await X.storage.virtualMcps.update(Y.id,J,Y.data)}}})});var mX1,lX1,OG0;var TO6=S(()=>{n0();z4();oD();mX1=z.object({id:z.string().describe("ID of the virtual MCP to delete")}),lX1=z.object({item:UW.describe("The deleted virtual MCP entity")}),OG0=J6({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:mX1,outputSchema:lX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=await X.storage.virtualMcps.findById(Y.id);if(!J)throw Error(`Virtual MCP not found: ${Y.id}`);if(J.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y.id}`);return await X.storage.virtualMcps.delete(Y.id),{item:J}}})});var PO6=S(()=>{LO6();wO6();MO6();AO6();TO6()});var pX1,NG0;var EO6=S(()=>{z4();n0();pX1=z.object({id:z.string().optional().describe("Unique log identifier"),organizationId:z.string().describe("Organization ID"),connectionId:z.string().describe("Connection ID"),connectionTitle:z.string().describe("Connection display name"),toolName:z.string().describe("Name of the tool that was called"),input:z.record(z.string(),z.unknown()).describe("Redacted tool input"),output:z.record(z.string(),z.unknown()).describe("Redacted tool output"),isError:z.boolean().describe("Whether the call resulted in an error"),errorMessage:z.string().nullish().describe("Error message if applicable"),durationMs:z.number().describe("Call duration in milliseconds"),timestamp:z.string().describe("ISO 8601 timestamp of the call"),userId:z.string().nullish().describe("User who triggered the call"),requestId:z.string().describe("Unique request identifier"),userAgent:z.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:z.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:z.record(z.string(),z.string()).nullish().describe("Custom key-value metadata attached to the log")}),NG0=J6({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:z.object({connectionId:z.string().optional().describe("Filter by connection ID"),virtualMcpId:z.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:z.string().optional().describe("Filter by tool name"),isError:z.boolean().optional().describe("Filter by error status"),startDate:z.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:z.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:z.number().default(20).describe("Maximum number of results"),offset:z.number().default(0).describe("Offset for pagination"),properties:z.record(z.string(),z.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:z.array(z.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:z.record(z.string(),z.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:z.object({logs:z.array(pX1).describe("Array of monitoring logs"),total:z.number().describe("Total number of logs matching filters"),offset:z.number().describe("Current offset for pagination"),limit:z.number().describe("Current limit for pagination")}),handler:async(Y,X)=>{let Q=h6(X),G=Y.properties||Y.propertyKeys||Y.propertyPatterns?{properties:Y.properties,propertyKeys:Y.propertyKeys,propertyPatterns:Y.propertyPatterns}:void 0,K={organizationId:Q.id,connectionId:Y.connectionId,virtualMcpId:Y.virtualMcpId,toolName:Y.toolName,isError:Y.isError,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0,limit:Y.limit,offset:Y.offset,propertyFilters:G},W=await X.storage.monitoring.query(K);return{logs:W.logs.map((Z)=>({...Z,timestamp:Z.timestamp instanceof Date?Z.timestamp.toISOString():Z.timestamp})),total:W.total,offset:Y.offset,limit:Y.limit}}})});var LG0;var CO6=S(()=>{z4();n0();LG0=J6({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:z.object({startDate:z.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:z.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:z.object({totalCalls:z.number().describe("Total number of tool calls"),errorRate:z.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:z.number().describe("Average call duration in milliseconds"),errorRatePercent:z.string().describe("Error rate as a percentage string")}),handler:async(Y,X)=>{let J={organizationId:h6(X).id,startDate:Y.startDate?new Date(Y.startDate):void 0,endDate:Y.endDate?new Date(Y.endDate):void 0},G=await X.storage.monitoring.getStats(J);return{...G,errorRatePercent:(G.errorRate*100).toFixed(2)}}})});var IO6=S(()=>{EO6();CO6()});var wG0;var RO6=S(()=>{n0();z4();wG0=J6({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:z.object({slug:z.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:z.string().min(1).max(255),description:z.string().optional()}),outputSchema:z.object({id:z.string(),name:z.string(),slug:z.string(),logo:z.string().nullable().optional(),metadata:z.any().optional(),createdAt:z.string().datetime().describe("ISO 8601 timestamp"),members:z.array(z.any()).optional()}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=s8(X);if(!Q)throw Error("User ID required to create organization");let J=await X.boundAuth.organization.create({name:Y.name,slug:Y.slug,metadata:Y.description?{description:Y.description}:void 0,userId:Q});if(!J)throw Error("Failed to create organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var MG0;var jO6=S(()=>{n0();z4();MG0=J6({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:z.object({userId:z.string().optional()}),outputSchema:z.object({organizations:z.array(z.object({id:z.string(),name:z.string(),slug:z.string(),logo:z.string().nullable().optional(),metadata:z.any().optional(),createdAt:z.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=s8(X),J=Y.userId||Q;if(!J)throw Error("User ID required to list organizations");return{organizations:(await X.boundAuth.organization.list(J)).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var AG0;var SO6=S(()=>{n0();z4();AG0=J6({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:z.object({}),outputSchema:z.object({id:z.string(),name:z.string(),slug:z.string(),logo:z.string().nullable().optional(),metadata:z.any().optional(),createdAt:z.string().datetime().describe("ISO 8601 timestamp"),members:z.array(z.any()).optional(),invitations:z.array(z.any()).optional()}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=await X.boundAuth.organization.get();if(!Q)throw Error("No active organization found");let J=new Date,G=Q.invitations?.filter((K)=>new Date(K.expiresAt)>J);return{...Q,invitations:G,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt}}})});var TG0;var kO6=S(()=>{n0();z4();TG0=J6({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:z.object({id:z.string(),slug:z.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:z.string().min(1).max(255).optional(),description:z.string().optional()}),outputSchema:z.object({id:z.string(),name:z.string(),slug:z.string(),logo:z.string().nullable().optional(),metadata:z.any().optional(),createdAt:z.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q={};if(Y.name)Q.name=Y.name;if(Y.slug)Q.slug=Y.slug;if(Y.description)Q.metadata={description:Y.description};let J=await X.boundAuth.organization.update({organizationId:Y.id,data:Q});if(!J)throw Error("Failed to update organization");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var PG0;var vO6=S(()=>{n0();z4();PG0=J6({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:z.object({id:z.string()}),outputSchema:z.object({success:z.boolean(),id:z.string()}),handler:async(Y,X)=>{return D6(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var N2;var EG0=S(()=>{n0();N2=z.object({title:z.string(),url:z.string(),icon:z.string()})});var CG0;var _O6=S(()=>{n0();z4();EG0();CG0=J6({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:z.object({}),outputSchema:z.object({organizationId:z.string(),sidebar_items:z.array(N2).nullable().optional(),enabled_plugins:z.array(z.string()).nullable().optional(),createdAt:z.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:z.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.storage.organizationSettings.get(Q);if(!J)return{organizationId:Q};return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt,updatedAt:J.updatedAt instanceof Date?J.updatedAt.toISOString():J.updatedAt}}})});var IG0;var yO6=S(()=>{n0();z4();EG0();IG0=J6({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:z.object({organizationId:z.string(),sidebar_items:z.array(N2).optional(),enabled_plugins:z.array(z.string()).optional()}),outputSchema:z.object({organizationId:z.string(),sidebar_items:z.array(N2).nullable().optional(),enabled_plugins:z.array(z.string()).nullable().optional(),createdAt:z.string().datetime().describe("ISO 8601 timestamp"),updatedAt:z.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{if(D6(X),await X.access.check(),X.organization&&X.organization.id!==Y.organizationId)throw Error("Cannot update settings for a different organization");let Q=await X.storage.organizationSettings.upsert(Y.organizationId,{sidebar_items:Y.sidebar_items,enabled_plugins:Y.enabled_plugins});return{...Q,createdAt:Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,updatedAt:Q.updatedAt instanceof Date?Q.updatedAt.toISOString():Q.updatedAt}}})});var RG0;var fO6=S(()=>{n0();z4();RG0=J6({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:z.object({organizationId:z.string().optional(),userId:z.string(),role:z.array(z.string())}),outputSchema:z.object({id:z.string(),organizationId:z.string(),userId:z.string(),role:z.union([z.string(),z.array(z.string())]),createdAt:z.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.addMember({organizationId:Q,userId:Y.userId,role:Y.role});if(!J)throw Error("Failed to add member");return{...J,role:J.role,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var jG0;var hO6=S(()=>{n0();z4();jG0=J6({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:z.object({organizationId:z.string().optional(),memberIdOrEmail:z.string()}),outputSchema:z.object({success:z.boolean(),memberIdOrEmail:z.string()}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return await X.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:Y.memberIdOrEmail}),{success:!0,memberIdOrEmail:Y.memberIdOrEmail}}})});var SG0;var bO6=S(()=>{n0();z4();SG0=J6({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:z.object({limit:z.number().optional(),offset:z.number().optional()}),outputSchema:z.object({members:z.array(z.object({id:z.string(),organizationId:z.string(),userId:z.string(),role:z.string(),createdAt:z.string().datetime().describe("ISO 8601 timestamp"),user:z.object({id:z.string(),name:z.string(),email:z.string(),image:z.string().optional()}).optional()}))}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.listMembers({organizationId:Q,limit:Y.limit,offset:Y.offset});return{members:(Array.isArray(J)?J:[]).map((K)=>({...K,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}))}}})});var kG0;var xO6=S(()=>{n0();z4();kG0=J6({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:z.object({organizationId:z.string().optional(),memberId:z.string(),role:z.array(z.string())}),outputSchema:z.object({id:z.string(),organizationId:z.string(),userId:z.string(),role:z.union([z.literal("admin"),z.literal("member"),z.literal("owner")]),createdAt:z.string().datetime().describe("ISO 8601 timestamp"),user:z.object({email:z.string(),name:z.string(),image:z.string().optional()})}),handler:async(Y,X)=>{D6(X),await X.access.check();let Q=Y.organizationId||X.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let J=await X.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:Y.memberId,role:Y.role});if(!J)throw Error("Failed to update member role");return{...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}}})});var uO6=S(()=>{RO6();jO6();SO6();kO6();vO6();_O6();yO6();fO6();hO6();bO6();xO6()});var gO6,DW,mO6,lO6;var l$=S(()=>{n0();gO6=z.object({id:z.string().describe("Unique message ID"),threadId:z.string().describe("ID of the parent thread"),metadata:z.unknown().optional().describe("Optional message metadata"),parts:z.array(z.record(z.string(),z.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:z.enum(["user","assistant","system"]).describe("Message role"),createdAt:z.string().datetime().describe("Timestamp of creation"),updatedAt:z.string().datetime().describe("Timestamp of last update")}),DW=z.object({id:z.string().describe("Unique thread ID"),organizationId:z.string().describe("Organization this thread belongs to"),title:z.string().describe("Thread title"),description:z.string().nullable().describe("Thread description"),createdAt:z.string().datetime().describe("Timestamp of creation"),updatedAt:z.string().datetime().describe("Timestamp of last update"),hidden:z.boolean().optional().describe("Whether the thread is hidden"),createdBy:z.string().describe("User ID who created the thread"),updatedBy:z.string().nullable().describe("User ID who last updated the thread")}),mO6=z.object({id:z.string().optional().describe("Optional custom ID for the thread"),title:z.string().describe("Thread title"),description:z.string().nullish().describe("Thread description")}),lO6=z.object({title:z.string().optional().describe("New thread title"),description:z.string().nullish().describe("New thread description"),hidden:z.boolean().optional().describe("Whether the thread is hidden")})});var iX1,aX1,vG0;var dO6=S(()=>{n0();z4();l$();tZ();iX1=z.object({data:mO6.describe("Data for the new thread (id is auto-generated if not provided)")}),aX1=z.object({item:DW.describe("The created thread entity")}),vG0=J6({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:iX1,outputSchema:aX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=s8(X);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??B9("thrd"),K=await X.storage.threads.create({id:G,organizationId:Q.id,title:Y.data.title,description:Y.data.description,createdBy:J});return{item:{...K,hidden:K.hidden??!1}}}})});var rX1,oX1,_G0;var pO6=S(()=>{k5();z4();l$();n0();rX1=QK.extend({where:z.object({created_by:z.string().optional()}).optional()}),oX1=JK(DW),_G0=J6({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:rX1,outputSchema:oX1,handler:async(Y,X)=>{await X.access.check();let Q=X.auth.user?.id;if(!Q)throw Error("User ID required to list threads");let J=h6(X),G=Y.offset??0,K=Y.limit??100,{threads:W,total:Z}=await X.storage.threads.list(J.id,Q,{limit:K,offset:G}),H=G+K<Z;return{items:W.map((F)=>({...F,hidden:F.hidden??!1})),totalCount:Z,hasMore:H}}})});var sX1,yG0;var cO6=S(()=>{k5();z4();l$();sX1=Y2(DW),yG0=J6({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:eP,outputSchema:sX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J||J.organizationId!==Q.id)return{item:null};return{item:{...J,hidden:J.hidden??!1}}}})});var tX1,eX1,fG0;var nO6=S(()=>{n0();z4();l$();tX1=z.object({id:z.string().describe("ID of the thread to update"),data:lO6.describe("Partial thread data to update")}),eX1=z.object({item:DW.describe("The updated thread entity")}),fG0=J6({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:tX1,outputSchema:eX1,handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=s8(X);if(!J)throw Error("User ID required to update thread");let{id:G,data:K}=Y,W=await X.storage.threads.get(G);if(!W||W.organizationId!==Q.id)throw Error("Thread not found in organization");let Z=await X.storage.threads.update(G,{title:K.title,description:K.description,hidden:K.hidden,updatedBy:J});return{item:{...Z,hidden:Z.hidden??!1}}}})});var hG0;var iO6=S(()=>{k5();z4();l$();hG0=J6({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:X2,outputSchema:Q2(DW),handler:async(Y,X)=>{D6(X);let Q=h6(X);await X.access.check();let J=await X.storage.threads.get(Y.id);if(!J)throw Error(`Thread not found: ${Y.id}`);if(J.organizationId!==Q.id)throw Error(`Thread not found: ${Y.id}`);return await X.storage.threads.delete(Y.id),{item:{...J,hidden:J.hidden??!1}}}})});function aO6(Y){if(!Y)return null;if("field"in Y&&Y.field[0]==="threadId"&&Y.operator==="eq")return String(Y.value);if("conditions"in Y)for(let X of Y.conditions){let Q=aO6(X);if(Q)return Q}return null}var YQ1,bG0;var rO6=S(()=>{k5();z4();l$();YQ1=JK(gO6),bG0=J6({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:QK,outputSchema:YQ1,handler:async(Y,X)=>{let Q=h6(X);await X.access.check();let J=aO6(Y.where);if(!J)throw Error("threadId filter is required in where clause");let G=await X.storage.threads.get(J);if(!G||G.organizationId!==Q.id)throw Error("Thread not found in organization");let K=Y.offset??0,W=Y.limit??100,{messages:Z,total:H}=await X.storage.threads.listMessages(J,{limit:W,offset:K}),F=K+W<H;return{items:Z,totalCount:H,hasMore:F}}})});var oO6=S(()=>{dO6();pO6();cO6();nO6();iO6();rO6()});var QQ1,JQ1,xG0;var sO6=S(()=>{n0();z4();QQ1=z.object({id:z.string().min(1)}),JQ1=z.object({user:z.object({id:z.string(),name:z.string(),email:z.string(),image:z.string().nullable()}).nullable()}),xG0=J6({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:QQ1,outputSchema:JQ1,handler:async(Y,X)=>{await X.access.check(),D6(X);let Q=s8(X);if(!Q)throw Error("Authentication required");let J=await X.storage.users.findById(Y.id,Q);if(!J)return{user:null};return{user:{id:J.id,name:J.name,email:J.email,image:J.image??null}}}})});var tO6=S(()=>{sO6()});var YN6={};o6(YN6,{managementMCP:()=>uG0,ALL_TOOLS:()=>eO6});var WQ1,ZQ1,eO6,uG0=async(Y)=>{let X=null;if(Y.organization)X=(await Y.storage.organizationSettings.get(Y.organization.id))?.enabled_plugins??null;let J=TH0(eO6,X).map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema,outputSchema:K.outputSchema,handler:async(W)=>{return Y.access.setToolName(K.name),await K.execute(W,Y)}}));return VU6({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var gG0=S(()=>{$U6();$R();EU6();DD6();QO6();ZO6();DO6();PO6();IO6();uO6();oO6();tO6();WQ1=[wG0,MG0,AG0,TG0,PG0,CG0,IG0,RG0,jG0,SG0,kG0,p50,t50,e50,QG0,JG0,GG0,qG0,BG0,UG0,DG0,OG0,WO6,NG0,LG0,N50,w50,M50,L50,WG0,ZG0,KG0,HG0,FG0,VG0,$G0,xG0,m50,l50,d50,vG0,_G0,yG0,fG0,hG0,bG0],ZQ1=PH0(),eO6=[...WQ1,...ZQ1]});function KQ1(Y){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:X}=await Promise.resolve().then(() => (gG0(),YN6));return X.map((Q)=>{return{name:Q.name,inputSchema:z.toJSONSchema(Q.inputSchema,{unrepresentable:"any"}),outputSchema:Q.outputSchema?z.toJSONSchema(Q.outputSchema,{unrepresentable:"any"}):void 0,description:Q.description}})},data:fJ0(t5(),Y)},{data:yJ0()},{data:_J0(Y)}]}async function XN6(Y,X){try{let Q=O$(),J=new k$(process.env.ENCRYPTION_KEY||""),G=new mP(Q.db,J),K=KQ1(Y);await Promise.all(K.map(async(W)=>{let Z=null;if(W.permissions)Z=(await SG.api.createApiKey({body:{name:`${W.data.app_name??crypto.randomUUID()}-mcp`,userId:X,permissions:W.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Y},purpose:"default-org-connections"}}}))?.key;let H=await W.getTools?.()??await lD({id:"pending",title:W.data.title,connection_type:W.data.connection_type,connection_url:W.data.connection_url,connection_token:W.data.connection_token,connection_headers:W.data.connection_headers}).catch(()=>null),F=W.data.id?W.data.id.startsWith(`${Y}_`)?W.data.id:`${Y}_${W.data.id}`:void 0;await G.create({...W.data,id:F,tools:H,organization_id:Y,created_by:X,connection_token:W.data.connection_token??Z})}))}catch(Q){console.error("Error creating default MCP connections:",Q)}}var QN6=S(()=>{j5();kT();Ax();rJ0();Sx();n0();sD()});var mG0,JN6;var lG0=S(()=>{mG0=["owner","admin","user"],JN6=["owner","admin"]});var HQ1=(Y)=>{return{defaultSSO:[{domain:Y.domain,providerId:Y.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Y.MS_CLIENT_ID,clientSecret:Y.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Y.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Y.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},GN6=(Y)=>{if(Y.providerId==="microsoft")return HQ1(Y);throw Error(`Unsupported provider: ${Y.providerId}`)};function FQ1(Y){return Y.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function VQ1(){let Y=Math.floor(Math.random()*ZN6.length),X=Math.floor(Math.random()*WN6.length),Q=ZN6[Y]??"deco",J=WN6[X]??"studio";return`${Q}-${J}`}var WN6,ZN6,$Q1,qQ1,tx,zQ1,BQ1,UQ1,KN6,U9,HN6=void 0,DQ1,OQ1,NQ1,SG;var sD=S(()=>{On();KM0();iA0();Zo();Ss();uT0();Ev();iT0();kT();uY0();xK6();QN6();lG0();WN6=["labs","agent","studio","workspace","systems","core","cloud","works"],ZN6=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];$Q1=Object.values(IL()).map((Y)=>Y.map((X)=>X.name)).flat(),qQ1={...Fv,self:["*",...$Q1]},tx=v7(qQ1),zQ1=tx.newRole({self:["*"],...WM.statements}),BQ1=tx.newRole({self:["*"],...WM.statements}),UQ1=tx.newRole({self:["*"],...WM.statements}),KN6=Object.values(IL()).map((Y)=>Y.map((X)=>`self:${X.name}`)).flat(),U9=BM.auth;if(U9.inviteEmailProviderId&&U9.emailProviders&&U9.emailProviders.length>0){let Y=Rh(U9.emailProviders,U9.inviteEmailProviderId);if(Y){let X=Ih(Y);HN6=async(Q)=>{let J=Q.inviter.user?.name||Q.inviter.user?.email,G=`${t5()}/auth/accept-invitation?invitationId=${Q.invitation.id}`;await X({to:Q.email,subject:`Invitation to join ${Q.organization.name}`,html:`
|
|
1185
1185
|
<h2>You've been invited!</h2>
|
|
1186
1186
|
<p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
|
|
1187
1187
|
<p><a href="${G}">Click here to accept the invitation</a></p>
|
|
1188
|
-
`})}}}DQ1=[Gs({organizationCreation:{afterCreate:async(Y)=>{await XN6(Y.organization.id,Y.member.userId)}},ac:tx,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:JN6,resourceNameValidation:(Y)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Y)}}},roles:{user:zQ1,admin:BQ1,owner:UQ1},sendInvitationEmail:HN6}),Es({loginPage:"/login",oidcConfig:{scopes:KN6,metadata:{scopes_supported:KN6},loginPage:"/login"}}),Ps({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Y)=>{if(Y.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=Y.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),$s({defaultRole:"user",adminRoles:["admin","owner"]}),js(),Bs({jwt:{expirationTime:"5m"}}),ZM0(U9.ssoConfig?GN6(U9.ssoConfig):void 0),...U9.magicLinkConfig&&U9.emailProviders&&U9.emailProviders.length>0?[Rs(bK6(U9.magicLinkConfig,U9.emailProviders))]:[]],OQ1=hY0(),NQ1=fK6(OQ1),SG=Wo({baseURL:t5(),database:NQ1,emailAndPassword:{enabled:!0},...U9,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:DQ1,databaseHooks:{user:{create:{after:async(Y)=>{if(BM.autoCreateOrganizationOnSignup===!1)return;let X=Y.name?Y.name.split(" ")[0]:Y.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${X} ${VQ1()}`,K=FQ1(G);try{await SG.api.createOrganization({body:{name:G,slug:K,userId:Y.id}});return}catch(W){if(!(W instanceof Error&&("body"in W)&&W.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",W);return}}}}}}}})});async function FN6(){console.log("\uD83D\uDD10 Running Better Auth migrations...");try{let{toBeAdded:Y,toBeCreated:X,runMigrations:Q}=await CL(SG.options);if(!Y.length&&!X.length){console.log("\u2705 Better Auth schema is up to date (no migrations needed)");return}console.log("\uD83D\uDCCB Better Auth will create/update the following tables:");for(let J of[...X,...Y])console.log(` - ${J.table}`);await Q(),console.log("\u2705 Better Auth migrations completed successfully")}catch(Y){console.warn("\u26A0\uFE0F Better Auth migration failed (tables may be created on first use):",Y)}}var VN6=S(()=>{xV0();sD()});var zN6={};o6(zN6,{runSeed:()=>dp,runKyselyMigrations:()=>qN6,migrateToLatest:()=>LQ1,migrateDown:()=>wQ1});import{Migrator as $N6}from"kysely";async function qN6(Y){let X=new $N6({db:Y,provider:{getMigrations:()=>Promise.resolve(UR)}}),{error:Q,results:J}=await X.migrateToLatest();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" executed successfully`);else if(G.status==="Error")console.error(`\u274C Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q}async function LQ1(Y){let{keepOpen:X=!1,database:Q,skipBetterAuth:J=!1,seed:G}=Y??{};if(!J&&!Q)await FN6();let K=Q??O$(),W=async()=>{if(!X&&!Q)console.log("\uD83D\uDD12 Closing database connection..."),await hK6(K).catch((Z)=>{console.warn("Warning: Error closing database:",Z)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await qN6(K.db),console.log("\uD83C\uDF89 All Kysely migrations completed successfully");let Z;if(G)Z=await dp(K.db,G);return await W(),{seedResult:Z}}catch(Z){throw await W(),Z}}async function wQ1(){let Y=O$(),X=new $N6({db:Y.db,provider:{getMigrations:()=>Promise.resolve(UR)}}),{error:Q,results:J}=await X.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var BN6=S(()=>{lp();oH0();VN6();kT()});var j3;var L2=S(()=>{j3=class extends Error{res;status;constructor(Y=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Y}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var UN6,MQ1,AQ1=(Y,X)=>{if(!Y)return{};let Q=new Headers(Y.headers);if(X){let J=Q.get("connection");if(J){let G=J.split(",").map((W)=>W.trim()),K=G.filter((W)=>!MQ1.test(W));if(K.length>0)throw new j3(400,{message:`Invalid Connection header value: ${K.join(", ")}`});G.forEach((W)=>{Q.delete(W)})}}return UN6.forEach((J)=>{Q.delete(J)}),{method:Y.method,body:Y.body,duplex:Y.body?"half":void 0,headers:Q,signal:Y.signal}},TQ1=(Y)=>{if(!Y.headers||Array.isArray(Y.headers)||Y.headers instanceof Headers)return Y;let X=new Headers;for(let[Q,J]of Object.entries(Y.headers))if(J==null)X.delete(Q);else X.set(Q,J);return Y.headers=X,Y},DN6=async(Y,X)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...K}=X instanceof Request?{raw:X}:X??{},W=new Request(Y,{...AQ1(Q,G),...TQ1(K)});W.headers.delete("accept-encoding");let Z=await(J||fetch)(W),H=new Headers(Z.headers);if(UN6.forEach((F)=>{H.delete(F)}),H.has("content-encoding"))H.delete("content-encoding"),H.delete("content-length");return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:H})};var ON6=S(()=>{L2();UN6=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],MQ1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});var NN6=(Y)=>(X)=>{let Q=new URL(X.req.raw.url),J=new URL(Y);return J.pathname=Q.pathname,J.search=Q.search,DN6(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};var LN6=S(()=>{ON6()});import{resolve as w2,dirname as PQ1,join as EQ1,extname as CQ1}from"path";function jQ1(Y,X){let Q=w2(X),J=w2(Y);return J===Q||J.startsWith(Q+"/")}function SQ1({requestPath:Y,clientDir:X}){let Q=Y.startsWith("/")?Y.slice(1):Y,J=w2(X,Q);if(!jQ1(J,X))return null;return J}function wN6(Y,X="../client"){let Q=new URL(Y),J=PQ1(Q.pathname);return w2(J,X)}function MN6(Y={}){let{env:X="production",devServerUrl:Q=IQ1,clientDir:J=RQ1,isServerPath:G=()=>!1}=Y;if(X==="development"){let K=NN6(Q);return async function(Z){let H=new URL(Z.url);if(G(H.pathname))return null;let F={req:{raw:Z,url:Z.url}};return K(F)}}return async function(W){if(W.method!=="GET")return null;let Z=new URL(W.url),H;try{H=decodeURIComponent(Z.pathname)}catch{return null}if(G(H))return null;let F=SQ1({requestPath:H,clientDir:J});if(!F)return null;let V=EQ1(F,"index.html"),$=w2(J,"index.html"),q=W.headers.get("accept"),D=q?.includes("text/html")||q?.includes("*/*")&&["",".html"].includes(CQ1(F))?[V,$]:[];for(let O of[F,...D])try{let L=Bun.file(O);if(await L.exists())return new Response(L)}catch{}return null}}var IQ1="http://localhost:4000",RQ1="./dist/client";var AN6=S(()=>{LN6()});function PN6(Y){if(!Y)return!1;try{return new URL(Y).host==="api.decocms.com"&&Y!=="https://api.decocms.com/mcp/registry"}catch{return!1}}var TN6="https://api.decocms.com/mcp/registry";var dG0=(Y,X,Q)=>{return(J,G)=>{let K=-1;return W(0);async function W(Z){if(Z<=K)throw Error("next() called multiple times");K=Z;let H,F=!1,V;if(Y[Z])V=Y[Z][0][0],J.req.routeIndex=Z;else V=Z===Y.length&&G||void 0;if(V)try{H=await V(J,()=>W(Z+1))}catch($){if($ instanceof Error&&X)J.error=$,H=await X($,J),F=!0;else throw $}else if(J.finalized===!1&&Q)H=await Q(J);if(H&&(J.finalized===!1||F))J.res=H;return J}}};var EN6=()=>{};var CN6;var IN6=S(()=>{CN6=Symbol()});async function kQ1(Y,X){let Q=await Y.formData();if(Q)return vQ1(Q,X);return{}}function vQ1(Y,X){let Q=Object.create(null);if(Y.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Q[G]=J;else _Q1(Q,G,J)}),X.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))yQ1(Q,J,G),delete Q[J]});return Q}var RN6=async(Y,X=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=X,K=(Y instanceof ex?Y.raw.headers:Y.headers).get("Content-Type");if(K?.startsWith("multipart/form-data")||K?.startsWith("application/x-www-form-urlencoded"))return kQ1(Y,{all:Q,dot:J});return{}},_Q1=(Y,X,Q)=>{if(Y[X]!==void 0)if(Array.isArray(Y[X]))Y[X].push(Q);else Y[X]=[Y[X],Q];else if(!X.endsWith("[]"))Y[X]=Q;else Y[X]=[Q]},yQ1=(Y,X,Q)=>{let J=Y,G=X.split(".");G.forEach((K,W)=>{if(W===G.length-1)J[K]=Q;else{if(!J[K]||typeof J[K]!=="object"||Array.isArray(J[K])||J[K]instanceof File)J[K]=Object.create(null);J=J[K]}})};var jN6=S(()=>{pG0()});var nG0=(Y)=>{let X=Y.split("/");if(X[0]==="")X.shift();return X},SN6=(Y)=>{let{groups:X,path:Q}=fQ1(Y),J=nG0(Q);return hQ1(J,X)},fQ1=(Y)=>{let X=[];return Y=Y.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return X.push([G,Q]),G}),{groups:X,path:Y}},hQ1=(Y,X)=>{for(let Q=X.length-1;Q>=0;Q--){let[J]=X[Q];for(let G=Y.length-1;G>=0;G--)if(Y[G].includes(J)){Y[G]=Y[G].replace(J,X[Q][1]);break}}return Y},Yu,kN6=(Y,X)=>{if(Y==="*")return"*";let Q=Y.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${Y}#${X}`;if(!Yu[J])if(Q[2])Yu[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${X})`)]:[Y,Q[1],new RegExp(`^${Q[2]}$`)];else Yu[J]=[Y,Q[1],!0];return Yu[J]}return null},tD=(Y,X)=>{try{return X(Y)}catch{return Y.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return X(Q)}catch{return Q}})}},bQ1=(Y)=>tD(Y,decodeURI),iG0=(Y)=>{let X=Y.url,Q=X.indexOf("/",X.indexOf(":")+4),J=Q;for(;J<X.length;J++){let G=X.charCodeAt(J);if(G===37){let K=X.indexOf("?",J),W=X.slice(Q,K===-1?void 0:K);return bQ1(W.includes("%25")?W.replace(/%25/g,"%2525"):W)}else if(G===63)break}return X.slice(Q,J)},vN6=(Y)=>{let X=iG0(Y);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},d$=(Y,X,...Q)=>{if(Q.length)X=d$(X,...Q);return`${Y?.[0]==="/"?"":"/"}${Y}${X==="/"?"":`${Y?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},Xu=(Y)=>{if(Y.charCodeAt(Y.length-1)!==63||!Y.includes(":"))return null;let X=Y.split("/"),Q=[],J="";return X.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Q.length===0&&J==="")Q.push("/");else Q.push(J);let K=G.replace("?","");J+="/"+K,Q.push(J)}else J+="/"+G}),Q.filter((G,K,W)=>W.indexOf(G)===K)},cG0=(Y)=>{if(!/[%+]/.test(Y))return Y;if(Y.indexOf("+")!==-1)Y=Y.replace(/\+/g," ");return Y.indexOf("%")!==-1?tD(Y,M2):Y},_N6=(Y,X,Q)=>{let J;if(!Q&&X&&!/[%+]/.test(X)){let W=Y.indexOf("?",8);if(W===-1)return;if(!Y.startsWith(X,W+1))W=Y.indexOf(`&${X}`,W+1);while(W!==-1){let Z=Y.charCodeAt(W+X.length+1);if(Z===61){let H=W+X.length+2,F=Y.indexOf("&",H);return cG0(Y.slice(H,F===-1?void 0:F))}else if(Z==38||isNaN(Z))return"";W=Y.indexOf(`&${X}`,W+1)}if(J=/[%+]/.test(Y),!J)return}let G={};J??=/[%+]/.test(Y);let K=Y.indexOf("?",8);while(K!==-1){let W=Y.indexOf("&",K+1),Z=Y.indexOf("=",K);if(Z>W&&W!==-1)Z=-1;let H=Y.slice(K+1,Z===-1?W===-1?void 0:W:Z);if(J)H=cG0(H);if(K=W,H==="")continue;let F;if(Z===-1)F="";else if(F=Y.slice(Z+1,W===-1?void 0:W),J)F=cG0(F);if(Q){if(!(G[H]&&Array.isArray(G[H])))G[H]=[];G[H].push(F)}else G[H]??=F}return X?G[X]:G},yN6,fN6=(Y,X)=>{return _N6(Y,X,!0)},M2;var p$=S(()=>{Yu={},yN6=_N6,M2=decodeURIComponent});var hN6=(Y)=>tD(Y,M2),ex;var pG0=S(()=>{L2();IN6();jN6();p$();ex=class{raw;#Y;#X;routeIndex=0;path;bodyCache={};constructor(Y,X="/",Q=[[]]){this.raw=Y,this.path=X,this.#X=Q,this.#Y={}}param(Y){return Y?this.#Q(Y):this.#J()}#Q(Y){let X=this.#X[0][this.routeIndex][1][Y],Q=this.#W(X);return Q&&/\%/.test(Q)?hN6(Q):Q}#J(){let Y={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let Q of X){let J=this.#W(this.#X[0][this.routeIndex][1][Q]);if(J!==void 0)Y[Q]=/\%/.test(J)?hN6(J):J}return Y}#W(Y){return this.#X[1]?this.#X[1][Y]:Y}query(Y){return yN6(this.url,Y)}queries(Y){return fN6(this.url,Y)}header(Y){if(Y)return this.raw.headers.get(Y)??void 0;let X={};return this.raw.headers.forEach((Q,J)=>{X[J]=Q}),X}async parseBody(Y){return this.bodyCache.parsedBody??=await RN6(this,Y)}#G=(Y)=>{let{bodyCache:X,raw:Q}=this,J=X[Y];if(J)return J;let G=Object.keys(X)[0];if(G)return X[G].then((K)=>{if(G==="json")K=JSON.stringify(K);return new Response(K)[Y]()});return X[Y]=Q[Y]()};json(){return this.#G("text").then((Y)=>JSON.parse(Y))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(Y,X){this.#Y[Y]=X}valid(Y){return this.#Y[Y]}get url(){return this.raw.url}get method(){return this.raw.method}get[CN6](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Y]])=>Y)}get routePath(){return this.#X[0].map(([[,Y]])=>Y)[this.routeIndex].path}}});var Qu,xQ1=(Y,X)=>{let Q=new String(Y);return Q.isEscaped=!0,Q.callbacks=X,Q},A2=async(Y,X,Q,J,G)=>{if(typeof Y==="object"&&!(Y instanceof String)){if(!(Y instanceof Promise))Y=Y.toString();if(Y instanceof Promise)Y=await Y}let K=Y.callbacks;if(!K?.length)return Promise.resolve(Y);if(G)G[0]+=Y;else G=[Y];let W=Promise.all(K.map((Z)=>Z({phase:X,buffer:G,context:J}))).then((Z)=>Promise.all(Z.filter(Boolean).map((H)=>A2(H,X,!1,J,G))).then(()=>G[0]));if(Q)return xQ1(await W,K);else return W};var aG0=S(()=>{Qu={Stringify:1,BeforeStream:2,Stream:3}});var bN6="text/plain; charset=UTF-8",rG0=(Y,X)=>{return{"Content-Type":Y,...X}},xN6=class{#Y;#X;env={};#Q;finalized=!1;error;#J;#W;#G;#K;#Z;#F;#H;#$;#q;constructor(Y,X){if(this.#Y=Y,X)this.#W=X.executionCtx,this.env=X.env,this.#F=X.notFoundHandler,this.#q=X.path,this.#$=X.matchResult}get req(){return this.#X??=new ex(this.#Y,this.#q,this.#$),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#H??=new Headers})}set res(Y){if(this.#G&&Y){Y=new Response(Y.body,Y);for(let[X,Q]of this.#G.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let J=this.#G.headers.getSetCookie();Y.headers.delete("set-cookie");for(let G of J)Y.headers.append("set-cookie",G)}else Y.headers.set(X,Q)}}this.#G=Y,this.finalized=!0}render=(...Y)=>{return this.#Z??=(X)=>this.html(X),this.#Z(...Y)};setLayout=(Y)=>this.#K=Y;getLayout=()=>this.#K;setRenderer=(Y)=>{this.#Z=Y};header=(Y,X,Q)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#H??=new Headers;if(X===void 0)J.delete(Y);else if(Q?.append)J.append(Y,X);else J.set(Y,X)};status=(Y)=>{this.#J=Y};set=(Y,X)=>{this.#Q??=new Map,this.#Q.set(Y,X)};get=(Y)=>{return this.#Q?this.#Q.get(Y):void 0};get var(){if(!this.#Q)return{};return Object.fromEntries(this.#Q)}#V(Y,X,Q){let J=this.#G?new Headers(this.#G.headers):this.#H??new Headers;if(typeof X==="object"&&"headers"in X){let K=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[W,Z]of K)if(W.toLowerCase()==="set-cookie")J.append(W,Z);else J.set(W,Z)}if(Q)for(let[K,W]of Object.entries(Q))if(typeof W==="string")J.set(K,W);else{J.delete(K);for(let Z of W)J.append(K,Z)}let G=typeof X==="number"?X:X?.status??this.#J;return new Response(Y,{status:G,headers:J})}newResponse=(...Y)=>this.#V(...Y);body=(Y,X,Q)=>this.#V(Y,X,Q);text=(Y,X,Q)=>{return!this.#H&&!this.#J&&!X&&!Q&&!this.finalized?new Response(Y):this.#V(Y,X,rG0(bN6,Q))};json=(Y,X,Q)=>{return this.#V(JSON.stringify(Y),X,rG0("application/json",Q))};html=(Y,X,Q)=>{let J=(G)=>this.#V(G,X,rG0("text/html; charset=UTF-8",Q));return typeof Y==="object"?A2(Y,Qu.Stringify,!1,{}).then(J):J(Y)};redirect=(Y,X)=>{let Q=String(Y);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,X??302)};notFound=()=>{return this.#F??=()=>new Response,this.#F(this)}};var Ju=S(()=>{pG0();aG0()});var H8="ALL",uN6="all",gN6,Gu="Can not add a route since the matcher is already built.",Wu;var c$=S(()=>{gN6=["get","post","put","delete","options","patch"],Wu=class extends Error{}});var mN6="__COMPOSED_HANDLER";var lN6=()=>{};var uQ1=(Y)=>{return Y.text("404 Not Found",404)},dN6=(Y,X)=>{if("getResponse"in Y){let Q=Y.getResponse();return X.newResponse(Q.body,Q)}return console.error(Y),X.text("Internal Server Error",500)},pN6=class Y{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Y="/";routes=[];constructor(X={}){[...gN6,uN6].forEach((K)=>{this[K]=(W,...Z)=>{if(typeof W==="string")this.#Y=W;else this.#J(K,this.#Y,W);return Z.forEach((H)=>{this.#J(K,this.#Y,H)}),this}}),this.on=(K,W,...Z)=>{for(let H of[W].flat()){this.#Y=H;for(let F of[K].flat())Z.map((V)=>{this.#J(F.toUpperCase(),this.#Y,V)})}return this},this.use=(K,...W)=>{if(typeof K==="string")this.#Y=K;else this.#Y="*",W.unshift(K);return W.forEach((Z)=>{this.#J(H8,this.#Y,Z)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??iG0:vN6}#X(){let X=new Y({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#Q=this.#Q,X.routes=this.routes,X}#Q=uQ1;errorHandler=dN6;route(X,Q){let J=this.basePath(X);return Q.routes.map((G)=>{let K;if(Q.errorHandler===dN6)K=G.handler;else K=async(W,Z)=>(await dG0([],Q.errorHandler)(W,()=>G.handler(W,Z))).res,K[mN6]=G.handler;J.#J(G.method,G.path,K)}),this}basePath(X){let Q=this.#X();return Q._basePath=d$(this._basePath,X),Q}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#Q=X,this};mount(X,Q,J){let G,K;if(J)if(typeof J==="function")K=J;else if(K=J.optionHandler,J.replaceRequest===!1)G=(H)=>H;else G=J.replaceRequest;let W=K?(H)=>{let F=K(H);return Array.isArray(F)?F:[F]}:(H)=>{let F=void 0;try{F=H.executionCtx}catch{}return[H.env,F]};G||=(()=>{let H=d$(this._basePath,X),F=H==="/"?0:H.length;return(V)=>{let $=new URL(V.url);return $.pathname=$.pathname.slice(F)||"/",new Request($,V)}})();let Z=async(H,F)=>{let V=await Q(G(H.req.raw),...W(H));if(V)return V;await F()};return this.#J(H8,d$(X,"*"),Z),this}#J(X,Q,J){X=X.toUpperCase(),Q=d$(this._basePath,Q);let G={basePath:this._basePath,path:Q,method:X,handler:J};this.router.add(X,Q,[J,G]),this.routes.push(G)}#W(X,Q){if(X instanceof Error)return this.errorHandler(X,Q);throw X}#G(X,Q,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(X,Q,J,"GET")))();let K=this.getPath(X,{env:J}),W=this.router.match(G,K),Z=new xN6(X,{path:K,matchResult:W,env:J,executionCtx:Q,notFoundHandler:this.#Q});if(W[0].length===1){let F;try{F=W[0][0][0][0](Z,async()=>{Z.res=await this.#Q(Z)})}catch(V){return this.#W(V,Z)}return F instanceof Promise?F.then((V)=>V||(Z.finalized?Z.res:this.#Q(Z))).catch((V)=>this.#W(V,Z)):F??this.#Q(Z)}let H=dG0(W[0],this.errorHandler,this.#Q);return(async()=>{try{let F=await H(Z);if(!F.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return F.res}catch(F){return this.#W(F,Z)}})()}fetch=(X,...Q)=>{return this.#G(X,Q[1],Q[0],X.method)};request=(X,Q,J,G)=>{if(X instanceof Request)return this.fetch(Q?new Request(X,Q):X,J,G);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${d$("/",X)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var cN6=S(()=>{EN6();Ju();c$();lN6();p$()});function Zu(Y,X){let Q=this.buildAllMatchers(),J=(G,K)=>{let W=Q[G]||Q[H8],Z=W[2][K];if(Z)return Z;let H=K.match(W[0]);if(!H)return[[],T2];let F=H.indexOf("",1);return[W[1][F],H]};return this.match=J,J(Y,X)}var T2;var oG0=S(()=>{c$();T2=[]});function mQ1(Y,X){if(Y.length===1)return X.length===1?Y<X?-1:1:-1;if(X.length===1)return 1;if(Y===P2||Y===E2)return 1;else if(X===P2||X===E2)return-1;if(Y===Ku)return 1;else if(X===Ku)return-1;return Y.length===X.length?Y<X?-1:1:X.length-Y.length}var Ku="[^/]+",P2=".*",E2="(?:|/.*)",n$,gQ1,nN6=class Y{#Y;#X;#Q=Object.create(null);insert(X,Q,J,G,K){if(X.length===0){if(this.#Y!==void 0)throw n$;if(K)return;this.#Y=Q;return}let[W,...Z]=X,H=W==="*"?Z.length===0?["","",P2]:["","",Ku]:W==="/*"?["","",E2]:W.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),F;if(H){let V=H[1],$=H[2]||Ku;if(V&&H[2]){if($===".*")throw n$;if($=$.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test($))throw n$}if(F=this.#Q[$],!F){if(Object.keys(this.#Q).some((q)=>q!==P2&&q!==E2))throw n$;if(K)return;if(F=this.#Q[$]=new Y,V!=="")F.#X=G.varIndex++}if(!K&&V!=="")J.push([V,F.#X])}else if(F=this.#Q[W],!F){if(Object.keys(this.#Q).some((V)=>V.length>1&&V!==P2&&V!==E2))throw n$;if(K)return;F=this.#Q[W]=new Y}F.insert(Z,Q,J,G,K)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(mQ1).map((J)=>{let G=this.#Q[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:gQ1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#Y==="number")Q.unshift(`#${this.#Y}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var sG0=S(()=>{n$=Symbol(),gQ1=new Set(".\\+*[^]$()")});var iN6=class{#Y={varIndex:0};#X=new nN6;insert(Y,X,Q){let J=[],G=[];for(let W=0;;){let Z=!1;if(Y=Y.replace(/\{[^}]+\}/g,(H)=>{let F=`@\\${W}`;return G[W]=[F,H],W++,Z=!0,F}),!Z)break}let K=Y.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let W=G.length-1;W>=0;W--){let[Z]=G[W];for(let H=K.length-1;H>=0;H--)if(K[H].indexOf(Z)!==-1){K[H]=K[H].replace(Z,G[W][1]);break}}return this.#X.insert(K,X,J,this.#Y,Q),J}buildRegExp(){let Y=this.#X.buildRegExpStr();if(Y==="")return[/^$/,[],[]];let X=0,Q=[],J=[];return Y=Y.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,K,W)=>{if(K!==void 0)return Q[++X]=Number(K),"$()";if(W!==void 0)return J[Number(W)]=++X,"";return""}),[new RegExp(`^${Y}`),Q,J]}};var aN6=S(()=>{sG0()});function oN6(Y){return rN6[Y]??=new RegExp(Y==="*"?"":`^${Y.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function dQ1(){rN6=Object.create(null)}function pQ1(Y){let X=new iN6,Q=[];if(Y.length===0)return lQ1;let J=Y.map((F)=>[!/\*|\/:/.test(F[0]),...F]).sort(([F,V],[$,q])=>F?1:$?-1:V.length-q.length),G=Object.create(null);for(let F=0,V=-1,$=J.length;F<$;F++){let[q,B,D]=J[F];if(q)G[B]=[D.map(([L])=>[L,Object.create(null)]),T2];else V++;let O;try{O=X.insert(B,V,q)}catch(L){throw L===n$?new Wu(B):L}if(q)continue;Q[V]=D.map(([L,w])=>{let I=Object.create(null);w-=1;for(;w>=0;w--){let[T,P]=O[w];I[T]=P}return[L,I]})}let[K,W,Z]=X.buildRegExp();for(let F=0,V=Q.length;F<V;F++)for(let $=0,q=Q[F].length;$<q;$++){let B=Q[F][$]?.[1];if(!B)continue;let D=Object.keys(B);for(let O=0,L=D.length;O<L;O++)B[D[O]]=Z[B[D[O]]]}let H=[];for(let F in W)H[F]=Q[W[F]];return[K,H,G]}function eD(Y,X){if(!Y)return;for(let Q of Object.keys(Y).sort((J,G)=>G.length-J.length))if(oN6(Q).test(X))return[...Y[Q]];return}var lQ1,rN6,Hu=class{name="RegExpRouter";#Y;#X;constructor(){this.#Y={[H8]:Object.create(null)},this.#X={[H8]:Object.create(null)}}add(Y,X,Q){let J=this.#Y,G=this.#X;if(!J||!G)throw Error(Gu);if(!J[Y])[J,G].forEach((Z)=>{Z[Y]=Object.create(null),Object.keys(Z[H8]).forEach((H)=>{Z[Y][H]=[...Z[H8][H]]})});if(X==="/*")X="*";let K=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let Z=oN6(X);if(Y===H8)Object.keys(J).forEach((H)=>{J[H][X]||=eD(J[H],X)||eD(J[H8],X)||[]});else J[Y][X]||=eD(J[Y],X)||eD(J[H8],X)||[];Object.keys(J).forEach((H)=>{if(Y===H8||Y===H)Object.keys(J[H]).forEach((F)=>{Z.test(F)&&J[H][F].push([Q,K])})}),Object.keys(G).forEach((H)=>{if(Y===H8||Y===H)Object.keys(G[H]).forEach((F)=>Z.test(F)&&G[H][F].push([Q,K]))});return}let W=Xu(X)||[X];for(let Z=0,H=W.length;Z<H;Z++){let F=W[Z];Object.keys(G).forEach((V)=>{if(Y===H8||Y===V)G[V][F]||=[...eD(J[V],F)||eD(J[H8],F)||[]],G[V][F].push([Q,K-H+Z+1])})}}match=Zu;buildAllMatchers(){let Y=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Y)).forEach((X)=>{Y[X]||=this.#Q(X)}),this.#Y=this.#X=void 0,dQ1(),Y}#Q(Y){let X=[],Q=Y===H8;if([this.#Y,this.#X].forEach((J)=>{let G=J[Y]?Object.keys(J[Y]).map((K)=>[K,J[Y][K]]):[];if(G.length!==0)Q||=!0,X.push(...G);else if(Y!==H8)X.push(...Object.keys(J[H8]).map((K)=>[K,J[H8][K]]))}),!Q)return null;else return pQ1(X)}};var tG0=S(()=>{c$();p$();oG0();sG0();aN6();lQ1=[/^$/,[],Object.create(null)],rN6=Object.create(null)});var cQ1=class{name="PreparedRegExpRouter";#Y;#X;constructor(Y,X){this.#Y=Y,this.#X=X}#Q(Y,X){let Q=this.#Y[Y];Q[1].forEach((J)=>J&&J.push(X)),Object.values(Q[2]).forEach((J)=>J[0].push(X))}#J(Y,X,Q,J,G){let K=this.#Y[Y];if(!G)K[2][X][0].push([Q,{}]);else J.forEach((W)=>{if(typeof W==="number")K[1][W].push([Q,G]);else K[2][W||X][0].push([Q,G])})}add(Y,X,Q){if(!this.#Y[Y]){let G=this.#Y[H8],K={};for(let W in G[2])K[W]=[G[2][W][0].slice(),T2];this.#Y[Y]=[G[0],G[1].map((W)=>Array.isArray(W)?W.slice():0),K]}if(X==="/*"||X==="*"){let G=[Q,{}];if(Y===H8)for(let K in this.#Y)this.#Q(K,G);else this.#Q(Y,G);return}let J=this.#X[X];if(!J)throw Error(`Path ${X} is not registered`);for(let[G,K]of J)if(Y===H8)for(let W in this.#Y)this.#J(W,X,Q,G,K);else this.#J(Y,X,Q,G,K)}buildAllMatchers(){return this.#Y}match=Zu};var sN6=S(()=>{c$();oG0();tG0()});var tN6=S(()=>{tG0();sN6()});var eG0=class{name="SmartRouter";#Y=[];#X=[];constructor(Y){this.#Y=Y.routers}add(Y,X,Q){if(!this.#X)throw Error(Gu);this.#X.push([Y,X,Q])}match(Y,X){if(!this.#X)throw Error("Fatal error");let Q=this.#Y,J=this.#X,G=Q.length,K=0,W;for(;K<G;K++){let Z=Q[K];try{for(let H=0,F=J.length;H<F;H++)Z.add(...J[H]);W=Z.match(Y,X)}catch(H){if(H instanceof Wu)continue;throw H}this.match=Z.match.bind(Z),this.#Y=[Z],this.#X=void 0;break}if(K===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,W}get activeRouter(){if(this.#X||this.#Y.length!==1)throw Error("No active router has been determined yet.");return this.#Y[0]}};var eN6=S(()=>{c$()});var YL6=S(()=>{eN6()});var C2,XL6=class Y{#Y;#X;#Q;#J=0;#W=C2;constructor(X,Q,J){if(this.#X=J||Object.create(null),this.#Y=[],X&&Q){let G=Object.create(null);G[X]={handler:Q,possibleKeys:[],score:0},this.#Y=[G]}this.#Q=[]}insert(X,Q,J){this.#J=++this.#J;let G=this,K=SN6(Q),W=[];for(let Z=0,H=K.length;Z<H;Z++){let F=K[Z],V=K[Z+1],$=kN6(F,V),q=Array.isArray($)?$[0]:F;if(q in G.#X){if(G=G.#X[q],$)W.push($[1]);continue}if(G.#X[q]=new Y,$)G.#Q.push($),W.push($[1]);G=G.#X[q]}return G.#Y.push({[X]:{handler:J,possibleKeys:W.filter((Z,H,F)=>F.indexOf(Z)===H),score:this.#J}}),G}#G(X,Q,J,G){let K=[];for(let W=0,Z=X.#Y.length;W<Z;W++){let H=X.#Y[W],F=H[Q]||H[H8],V={};if(F!==void 0){if(F.params=Object.create(null),K.push(F),J!==C2||G&&G!==C2)for(let $=0,q=F.possibleKeys.length;$<q;$++){let B=F.possibleKeys[$],D=V[F.score];F.params[B]=G?.[B]&&!D?G[B]:J[B]??G?.[B],V[F.score]=!0}}}return K}search(X,Q){let J=[];this.#W=C2;let K=[this],W=nG0(Q),Z=[];for(let H=0,F=W.length;H<F;H++){let V=W[H],$=H===F-1,q=[];for(let B=0,D=K.length;B<D;B++){let O=K[B],L=O.#X[V];if(L)if(L.#W=O.#W,$){if(L.#X["*"])J.push(...this.#G(L.#X["*"],X,O.#W));J.push(...this.#G(L,X,O.#W))}else q.push(L);for(let w=0,I=O.#Q.length;w<I;w++){let T=O.#Q[w],P=O.#W===C2?{}:{...O.#W};if(T==="*"){let f=O.#X["*"];if(f)J.push(...this.#G(f,X,O.#W)),f.#W=P,q.push(f);continue}let[A,R,j]=T;if(!V&&!(j instanceof RegExp))continue;let k=O.#X[A],y=W.slice(H).join("/");if(j instanceof RegExp){let f=j.exec(y);if(f){if(P[R]=f[0],J.push(...this.#G(k,X,O.#W,P)),Object.keys(k.#X).length){k.#W=P;let h=f[0].match(/\//)?.length??0;(Z[h]||=[]).push(k)}continue}}if(j===!0||j.test(V))if(P[R]=V,$){if(J.push(...this.#G(k,X,P,O.#W)),k.#X["*"])J.push(...this.#G(k.#X["*"],X,P,O.#W))}else k.#W=P,q.push(k)}}K=q.concat(Z.shift()??[])}if(J.length>1)J.sort((H,F)=>{return H.score-F.score});return[J.map(({handler:H,params:F})=>[H,F])]}};var QL6=S(()=>{c$();p$();C2=Object.create(null)});var Y70=class{name="TrieRouter";#Y;constructor(){this.#Y=new XL6}add(Y,X,Q){let J=Xu(X);if(J){for(let G=0,K=J.length;G<K;G++)this.#Y.insert(Y,J[G],Q);return}this.#Y.insert(Y,X,Q)}match(Y,X){return this.#Y.search(Y,X)}};var JL6=S(()=>{p$();QL6()});var GL6=S(()=>{JL6()});var D9;var WL6=S(()=>{cN6();tN6();YL6();GL6();D9=class extends pN6{constructor(Y={}){super(Y);this.router=Y.router??new eG0({routers:[new Hu,new Y70]})}}});var kG=S(()=>{WL6()});var nQ1,iQ1,X70=(Y,X)=>{if(X&&Y.indexOf(X)===-1)return{};let Q=Y.trim().split(";"),J={};for(let G of Q){G=G.trim();let K=G.indexOf("=");if(K===-1)continue;let W=G.substring(0,K).trim();if(X&&X!==W||!nQ1.test(W))continue;let Z=G.substring(K+1).trim();if(Z.startsWith('"')&&Z.endsWith('"'))Z=Z.slice(1,-1);if(iQ1.test(Z)){if(J[W]=Z.indexOf("%")!==-1?tD(Z,M2):Z,X)break}}return J};var ZL6=S(()=>{p$();nQ1=/^[\w!#$%&'*.^`|~+-]+$/,iQ1=/^[ !#-:<-[\]-~]*$/});var KL6=(Y,X,Q)=>{let J=Y.req.raw.headers.get("Cookie");if(typeof X==="string"){if(!J)return;let K=X;if(Q==="secure")K="__Secure-"+X;else if(Q==="host")K="__Host-"+X;return X70(J,K)[K]}if(!J)return{};return X70(J)};var HL6=S(()=>{ZL6()});var FL6=(Y)=>{let Q={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Y},J=((K)=>{if(typeof K==="string")if(K==="*")return()=>K;else return(W)=>K===W?W:null;else if(typeof K==="function")return K;else return(W)=>K.includes(W)?W:null})(Q.origin),G=((K)=>{if(typeof K==="function")return K;else if(Array.isArray(K))return()=>K;else return()=>[]})(Q.allowMethods);return async function(W,Z){function H(V,$){W.res.headers.set(V,$)}let F=await J(W.req.header("origin")||"",W);if(F)H("Access-Control-Allow-Origin",F);if(Q.credentials)H("Access-Control-Allow-Credentials","true");if(Q.exposeHeaders?.length)H("Access-Control-Expose-Headers",Q.exposeHeaders.join(","));if(W.req.method==="OPTIONS"){if(Q.origin!=="*")H("Vary","Origin");if(Q.maxAge!=null)H("Access-Control-Max-Age",Q.maxAge.toString());let V=await G(W.req.header("origin")||"",W);if(V.length)H("Access-Control-Allow-Methods",V.join(","));let $=Q.allowHeaders;if(!$?.length){let q=W.req.header("Access-Control-Request-Headers");if(q)$=q.split(/\s*,\s*/)}if($?.length)H("Access-Control-Allow-Headers",$.join(",")),W.res.headers.append("Vary","Access-Control-Request-Headers");return W.res.headers.delete("Content-Length"),W.res.headers.delete("Content-Type"),new Response(null,{headers:W.res.headers,status:204,statusText:"No Content"})}if(await Z(),Q.origin!=="*")W.header("Vary","Origin",{append:!0})}};var VL6=()=>{};function aQ1(){let{process:Y,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Y!==void 0?"NO_COLOR"in Y?.env:!1)}async function $L6(){let{navigator:Y}=globalThis,X="cloudflare:workers";return!(Y!==void 0&&Y.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!aQ1())}var qL6=()=>{};async function zL6(Y,X,Q,J,G=0,K){let W=X==="<--"?`${X} ${Q} ${J}`:`${X} ${Q} ${J} ${await sQ1(G)} ${K}`;Y(W)}var rQ1=(Y)=>{let[X,Q]=[",","."];return Y.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Q)},oQ1=(Y)=>{let X=Date.now()-Y;return rQ1([X<1000?X+"ms":Math.round(X/1000)+"s"])},sQ1=async(Y)=>{if(await $L6())switch(Y/100|0){case 5:return`\x1B[31m${Y}\x1B[0m`;case 4:return`\x1B[33m${Y}\x1B[0m`;case 3:return`\x1B[36m${Y}\x1B[0m`;case 2:return`\x1B[32m${Y}\x1B[0m`}return`${Y}`},BL6=(Y=console.log)=>{return async function(Q,J){let{method:G,url:K}=Q.req,W=K.slice(K.indexOf("/",8));await zL6(Y,"<--",G,W);let Z=Date.now();await J(),await zL6(Y,"-->",G,W,Q.res.status,oQ1(Z))}};var UL6=S(()=>{qL6()});var DL6=()=>{try{return performance.now()}catch{}return Date.now()},Q70=(Y)=>{let X={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...Y};return async function(J,G){let K=[],W=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:K,timers:W}),X.total)YO(J,"total",X.totalDescription);if(await G(),X.total)i$(J,"total");if(X.autoEnd)W.forEach((H,F)=>i$(J,F));if(typeof X.enabled==="function"?X.enabled(J):X.enabled){J.res.headers.append("Server-Timing",K.join(","));let H=typeof X.crossOrigin==="function"?X.crossOrigin(J):X.crossOrigin;if(H)J.res.headers.append("Timing-Allow-Origin",typeof H==="string"?H:"*")}}},OL6=(Y,X,Q,J,G)=>{let K=Y.get("metric");if(!K){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Q==="number"){let W=Q.toFixed(G||1),Z=J?`${X};dur=${W};desc="${J}"`:`${X};dur=${W}`;K.headers.push(Z)}else{let W=Q?`${X};desc="${Q}"`:`${X}`;K.headers.push(W)}},YO=(Y,X,Q)=>{let J=Y.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(X,{description:Q,start:DL6()})},i$=(Y,X,Q)=>{let J=Y.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(X);if(!G){console.warn(`Timer "${X}" does not exist!`);return}let{description:K,start:W}=G,Z=DL6()-W;OL6(Y,X,Z,K,Q),J.timers.delete(X)};var NL6=S(()=>{Ju()});var LL6=S(()=>{NL6()});import{randomBytes as tQ1}from"crypto";function wL6(){if(I2)return I2;let Y=process.env.MESH_JWT_SECRET??U9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)I2=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),I2=new Uint8Array(tQ1(32));return I2}async function ML6(Y,X="5m"){let Q=wL6();return await new VQ(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(X).sign(Q)}async function AL6(Y){try{let X=wL6(),{payload:Q}=await U8(Y,X);return Q}catch{return}}var I2=null;var J70=S(()=>{nQ();sD()});class G70{db;constructor(Y){this.db=Y}async create(Y,X,Q){let J=B9("vir"),G=new Date().toISOString();if(await this.db.insertInto("connections").values({id:J,organization_id:Y,created_by:X,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${J}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,tools:null,bindings:null,status:Q.status??"active",created_at:G,updated_at:G}).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((W)=>({id:B9("agg"),parent_connection_id:J,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,created_at:G}))).execute();let K=await this.findById(J);if(!K)throw Error(`Failed to create virtual MCP with id: ${J}`);return K}async findById(Y,X){if(Y&&oZ(Y)){let Q=Y.match(/^decopilot_(.+)$/),J;if(X)J=X;else if(Q&&Q[1])J=Q[1];else throw Error(`Invalid Decopilot ID format: ${Y}. Expected decopilot_{orgId} or provide organizationId`);let G=await this.db.selectFrom("connections").selectAll().where("organization_id","=",J).where("status","!=","inactive").where("status","!=","error").execute();return{...hP(J),connections:G.map((K)=>({connection_id:K.id,selected_tools:null,selected_resources:null,selected_prompts:null}))}}if(!Y){if(!X)throw Error("organizationId is required when id is null (Decopilot agent)");let Q=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).where("status","!=","inactive").where("status","!=","error").execute();return{...hP(X),connections:Q.map((J)=>({connection_id:J.id,selected_tools:null,selected_resources:null,selected_prompts:null}))}}return this.findByIdInternal(this.db,Y)}async findByIdInternal(Y,X){let Q=await Y.selectFrom("connections").selectAll().where("id","=",X).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let J=await Y.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",X).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(Y){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute(),Q=X.map((K)=>K.id);if(Q.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).execute(),G=new Map;for(let K of J){let W=G.get(K.parent_connection_id)??[];W.push(K),G.set(K.parent_connection_id,W)}return X.map((K)=>this.deserializeVirtualMCPEntity(K,G.get(K.id)??[]))}async listByConnectionId(Y,X){let J=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",X).execute()).map((H)=>H.parent_connection_id);if(J.length===0)return[];let G=await this.db.selectFrom("connections").selectAll().where("id","in",J).where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute();if(G.length===0)return[];let K=G.map((H)=>H.id),W=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",K).execute(),Z=new Map;for(let H of W){let F=Z.get(H.parent_connection_id)??[];F.push(H),Z.set(H.parent_connection_id,F)}return G.map((H)=>this.deserializeVirtualMCPEntity(H,Z.get(H.id)??[]))}async update(Y,X,Q){let J=new Date().toISOString(),G={updated_at:J};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(Q.metadata!==void 0)G.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(await this.db.updateTable("connections").set(G).where("id","=",Y).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((W)=>({id:B9("agg"),parent_connection_id:Y,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,created_at:J}))).execute()}let K=await this.findById(Y);if(!K)throw Error("Virtual MCP not found after update");return K}async delete(Y){await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).execute(),await this.db.deleteFrom("connections").where("id","=",Y).where("connection_type","=","VIRTUAL").execute()}deserializeVirtualMCPEntity(Y,X){let Q=Y.created_at instanceof Date?Y.created_at.toISOString():Y.created_at,J=Y.updated_at instanceof Date?Y.updated_at.toISOString():Y.updated_at,G=Y.status==="active"?"active":"inactive";return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,icon:Y.icon,status:G,created_at:Q,updated_at:J,created_by:Y.created_by,updated_by:void 0,metadata:this.parseJson(Y.metadata),connections:X.map((K)=>({connection_id:K.child_connection_id,selected_tools:this.parseJson(K.selected_tools),selected_resources:this.parseJson(K.selected_resources),selected_prompts:this.parseJson(K.selected_prompts)}))}}parseJson(Y){if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y}}var TL6=S(()=>{tZ();j5()});class W70{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(Y){if(Y===null||Y===void 0)return Y;if(typeof Y==="string")return this.redactString(Y);if(Array.isArray(Y))return Y.map((X)=>this.redact(X));if(typeof Y==="object"){let X={};for(let[Q,J]of Object.entries(Y)){let G=this.redactString(Q);X[G]=this.redact(J)}return X}return Y}redactString(Y){let X=Y;for(let Q of this.patterns)X=X.replace(Q.regex,`[REDACTED:${Q.type}]`);return X}}import{sql as Fu}from"kysely";class Z70{db;redactor;databaseType;constructor(Y,X="sqlite"){this.db=Y;this.redactor=new W70,this.databaseType=X}jsonExtract(Y,X){if(this.databaseType==="postgres")return Fu`(${Fu.ref(Y)}::jsonb)->>${X}`;let Q=`$.${X}`;return Fu`json_extract(${Fu.ref(Y)}, ${Q})`}async log(Y){await this.logBatch([Y])}async logBatch(Y){if(Y.length===0)return;let X=Y.map((Q)=>({...Q,input:this.redactor.redact(Q.input),output:this.redactor.redact(Q.output)}));await this.db.transaction().execute(async(Q)=>{await Q.insertInto("monitoring_logs").values(X.map((J)=>this.toDbRow(J))).execute()})}async query(Y){let X=this.db.selectFrom("monitoring_logs").selectAll(),Q=this.db.selectFrom("monitoring_logs").select((Z)=>Z.fn.count("id").as("count"));if(Y.organizationId)X=X.where("organization_id","=",Y.organizationId),Q=Q.where("organization_id","=",Y.organizationId);if(Y.connectionId)X=X.where("connection_id","=",Y.connectionId),Q=Q.where("connection_id","=",Y.connectionId);if(Y.virtualMcpId)X=X.where("virtual_mcp_id","=",Y.virtualMcpId),Q=Q.where("virtual_mcp_id","=",Y.virtualMcpId);if(Y.toolName)X=X.where("tool_name","=",Y.toolName),Q=Q.where("tool_name","=",Y.toolName);if(Y.isError!==void 0)X=X.where("is_error","=",Y.isError?1:0),Q=Q.where("is_error","=",Y.isError?1:0);if(Y.startDate)X=X.where("timestamp",">=",Y.startDate.toISOString()),Q=Q.where("timestamp",">=",Y.startDate.toISOString());if(Y.endDate)X=X.where("timestamp","<=",Y.endDate.toISOString()),Q=Q.where("timestamp","<=",Y.endDate.toISOString());if(Y.propertyFilters){let{properties:Z,propertyKeys:H,propertyPatterns:F}=Y.propertyFilters;if(Z)for(let[V,$]of Object.entries(Z)){let q=this.jsonExtract("properties",V);X=X.where(q,"=",$),Q=Q.where(q,"=",$)}if(H&&H.length>0)for(let V of H){let $=this.jsonExtract("properties",V);X=X.where($,"is not",null),Q=Q.where($,"is not",null)}if(F)for(let[V,$]of Object.entries(F)){let q=this.jsonExtract("properties",V),B=this.databaseType==="postgres"?"ilike":"like";X=X.where(q,B,$),Q=Q.where(q,B,$)}}if(X=X.orderBy("timestamp","desc"),Y.limit)X=X.limit(Y.limit);if(Y.offset)X=X.offset(Y.offset);let[J,G]=await Promise.all([X.execute(),Q.executeTakeFirst()]),K=Number(G?.count||0);return{logs:J.map((Z)=>this.fromDbRow(Z)),total:K}}async getStats(Y){let X=this.db.selectFrom("monitoring_logs").where("organization_id","=",Y.organizationId);if(Y.startDate)X=X.where("timestamp",">=",Y.startDate.toISOString());if(Y.endDate)X=X.where("timestamp","<=",Y.endDate.toISOString());let Q=await X.select([(W)=>W.fn.count("id").as("total_count"),(W)=>W.fn.sum(W.ref("is_error")).as("error_count"),(W)=>W.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Q?.total_count||0),G=Number(Q?.error_count||0),K=Number(Q?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:K}}toDbRow(Y){return{id:Y.id||B9("log"),organization_id:Y.organizationId,connection_id:Y.connectionId,connection_title:Y.connectionTitle,tool_name:Y.toolName,input:JSON.stringify(Y.input),output:JSON.stringify(Y.output),is_error:Y.isError?1:0,error_message:Y.errorMessage||null,duration_ms:Y.durationMs,timestamp:Y.timestamp instanceof Date?Y.timestamp.toISOString():Y.timestamp,user_id:Y.userId||null,request_id:Y.requestId,user_agent:Y.userAgent||null,virtual_mcp_id:Y.virtualMcpId||null,properties:Y.properties?JSON.stringify(Y.properties):null}}fromDbRow(Y){let X=typeof Y.input==="string"?JSON.parse(Y.input):Y.input,Q=typeof Y.output==="string"?JSON.parse(Y.output):Y.output,J=typeof Y.timestamp==="string"?new Date(Y.timestamp):Y.timestamp,G=Y.properties?typeof Y.properties==="string"?JSON.parse(Y.properties):Y.properties:null;return{id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,connectionTitle:Y.connection_title,toolName:Y.tool_name,input:X,output:Q,isError:Y.is_error===1,errorMessage:Y.error_message,durationMs:Y.duration_ms,timestamp:J,userId:Y.user_id,requestId:Y.request_id,userAgent:Y.user_agent,virtualMcpId:Y.virtual_mcp_id,properties:G}}}var PL6=S(()=>{tZ()});class K70{db;constructor(Y){this.db=Y}async get(Y){let X=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Y).executeTakeFirst();if(!X)return null;return{organizationId:X.organizationId,sidebar_items:X.sidebar_items?typeof X.sidebar_items==="string"?JSON.parse(X.sidebar_items):X.sidebar_items:null,enabled_plugins:X.enabled_plugins?typeof X.enabled_plugins==="string"?JSON.parse(X.enabled_plugins):X.enabled_plugins:null,createdAt:X.createdAt,updatedAt:X.updatedAt}}async upsert(Y,X){let Q=new Date().toISOString(),J=X?.sidebar_items?JSON.stringify(X.sidebar_items):null,G=X?.enabled_plugins?JSON.stringify(X.enabled_plugins):null;await this.db.insertInto("organization_settings").values({organizationId:Y,sidebar_items:J,enabled_plugins:G,createdAt:Q,updatedAt:Q}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,enabled_plugins:G?G:void 0,updatedAt:Q})).execute();let K=await this.get(Y);if(!K)return{organizationId:Y,sidebar_items:X?.sidebar_items??null,enabled_plugins:X?.enabled_plugins??null,createdAt:Q,updatedAt:Q};return K}}class H70{db;constructor(Y){this.db=Y}async findById(Y,X){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",Y).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",Y).where("m2.userId","=",X))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}var EL6="mcp.mesh";var CL6,F70,S3;var Vu=S(()=>{CL6=class CL6 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};F70=class F70 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};S3=class S3{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,X,Q,J,G,K="self",W){this.userId=X;this.toolName=Q;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 CL6("Authentication required. Please provide a valid OAuth token or API key.")}let X=Y.length>0?Y:this.toolName?[this.toolName]:[];if(X.length===0)throw new F70("No resources specified for access check");for(let Q of X)if(await this.checkResource(Q)){this.grant();return}throw new F70(`Access denied to: ${X.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 X={};if(this.connectionId)X[this.connectionId]=[Y];return this.boundAuth.hasPermission(X)}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 Q=Y[EL6]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}});async function IL6(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 X=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)X.set("client_secret",Y.clientSecret);if(Y.scope)X.set("scope",Y.scope);let Q=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:X.toString()});if(!Q.ok){let G=await Q.text();console.error(`[TokenRefresh] Failed to refresh token: ${Q.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${Q.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Q.status}`}}}let J=await Q.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(X){return console.error("[TokenRefresh] Error refreshing token:",X),{success:!1,error:X instanceof Error?X.message:"Token refresh failed"}}}async function R2(Y,X,Q){let J=Y.id,G=YG0(Y.configuration_state,Y.configuration_scopes),K=X.auth.user?.id??X.auth.apiKey?.userId??(Q?Y.created_by:void 0),[W,Z]=K?await ML6({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??X.baseUrl,connectionId:J,organizationId:X.organization?.id},permissions:G}).then((B)=>[B,null]).catch((B)=>[null,B]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=X.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...X.metadata.wellKnownForwardableHeaders??{},"x-request-id":X.metadata.requestId},V=null,$=new WK(X.db,X.vault),q=await $.get(J);if(q){let B=!!q.refreshToken&&!!q.tokenEndpoint;if($.isExpired(q,B?300000:0))if(B){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let O=await IL6(q);if(O.success&&O.accessToken)await $.upsert({connectionId:J,accessToken:O.accessToken,refreshToken:O.refreshToken??q.refreshToken,scope:O.scope??q.scope,expiresAt:O.expiresIn?new Date(Date.now()+O.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),V=O.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await $.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${O.error}`)}else await $.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else V=q.accessToken}if(!V&&Y.connection_token)V=Y.connection_token;if(V)F.Authorization=`Bearer ${V}`;if(W)F["x-mesh-token"]=W;return F}var V70=S(()=>{XG0();J70();ox()});function RL6(Y){let X=new nP({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),Q=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return X.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${Q}]\x1B[0m`)}),X}var jL6=S(()=>{D50()});async function SL6(Y,X,Q=!1){let J=Y.id;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 G=Y.connection_headers;if(!v$(G))throw Error("STDIO connection missing parameters");let K=RL6({id:J,name:Y.title,command:G.command,args:G.args,env:G.envVars,cwd:G.cwd});return X.getOrCreateClient(K,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let G=await R2(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new A3(new URL(Y.connection_url),{requestInit:{headers:G}});return X.getOrCreateClient(W,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let G=await R2(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new f$(new URL(Y.connection_url),{requestInit:{headers:G}});return X.getOrCreateClient(W,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var kL6=S(()=>{sZ();Ix();fP();V70();jL6()});class vL6{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,X){return this.getOrCreatePromise().then(Y,X)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function a$(Y){return new vL6(Y)}async function eQ1(Y,X){let Q=await Promise.all(Y.map(async(J)=>{try{let G=await X.createMCPProxy(J);return[J.id,G]}catch(G){return console.error(`[aggregator] Failed to create proxy for connection ${J.id}:`,G),null}}));return new Map(Q.filter((J)=>!!J))}async function _L6(Y){let X=[];for(let[,Q]of Y)X.push(Q.close().catch(()=>{}));await Promise.all(X)}var XO;var $70=S(()=>{CD();XO=class XO extends R5{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,X){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=X;this._selectionMap=new Map;for(let Q of Y.virtualMcp.connections)this._selectionMap.set(Q.connection_id,Q);this._connections=new Map;for(let Q of Y.connections)this._connections.set(Q.id,Q);this._clients=a$(()=>eQ1(this.options.connections,this.ctx)),this._cachedTools=a$(()=>this.loadCache("tools")),this._cachedResources=a$(()=>this.loadCache("resources")),this._cachedPrompts=a$(()=>this.loadCache("prompts"))}async loadCache(Y){let X=await this._clients,Q=await Promise.all(Array.from(X.entries()).map(async([K,W])=>{try{let Z=Y==="tools"?await W.listTools().then((F)=>F.tools):Y==="resources"?await W.listResources().then((F)=>F.resources):await W.listPrompts().then((F)=>F.prompts),H=this._selectionMap.get(K);if(H?.[`selected_${Y}`]?.length){let F=new Set(H[`selected_${Y}`]);Z=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 Q){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let V of Z){let $=V.name;if(G.has($))continue;let q={...V,_meta:{connectionId:W,connectionTitle:F,...V?._meta}};J.push(q),G.set($,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let[X,Q]=await Promise.all([this._cachedTools,this._clients]),J=X.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};let G=Q.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 listResources(){return{resources:(await this._cachedResources).data}}async readResource(Y){let[X,Q]=await Promise.all([this._cachedResources,this._clients]),J=X.mappings.get(Y.uri);if(!J)throw Error(`Resource not found: ${Y.uri}`);let G=Q.get(J);if(!G)throw Error(`Connection not found for resource: ${Y.uri}`);return await G.readResource(Y)}async listPrompts(){return{prompts:(await this._cachedPrompts).data}}async getPrompt(Y){let[X,Q]=await Promise.all([this._cachedPrompts,this._clients]),J=X.mappings.get(Y.name);if(!J)throw Error(`Prompt not found: ${Y.name}`);let G=Q.get(J);if(!G)throw Error(`Connection not found for prompt: ${Y.name}`);return await G.getPrompt(Y)}async callStreamableTool(Y,X){let[Q,J]=await Promise.all([this._cachedTools,this._clients]),G=Q.mappings.get(Y);if(G){let W=J.get(G);if(W)return W.callStreamableTool(Y,X)}let K=await this.callTool({name:Y,arguments:X});return new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}})}async[Symbol.asyncDispose](){let Y=await this._clients;if(Y)await _L6(Y)}async close(){let Y=await this._clients;if(Y)await _L6(Y);await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions}}});var yL6,YJ1,fL6,XJ1,j2;var q70=S(()=>{n0();g$();$70();yL6=z.object({query:z.string().min(1).describe("Search query to find tools by name or description"),limit:z.number().default(10).describe("Maximum number of results to return")}),YJ1=z.toJSONSchema(yL6),fL6=z.object({tools:z.array(z.string()).min(1).describe("Array of tool names to get detailed schemas for")}),XJ1=z.toJSONSchema(fL6);j2=class j2 extends XO{constructor(Y,X){super(Y,X)}getSearchTool(Y){return{name:"GATEWAY_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 GATEWAY_DESCRIBE_TOOLS for detailed schemas. Total tools: ${Y}.`,inputSchema:YJ1}}getDescribeTool(){return{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:XJ1}}async handleSearch(Y){let X=yL6.safeParse(Y);if(!X.success)return C3({error:X.error.flatten()});let Q=await this._cachedTools,J=XK(Q.data),G=hx(X.data.query,J,X.data.limit);return oP({query:X.data.query,results:G.map((K)=>({name:K.name,description:K.description,connection:K._meta.connectionTitle})),totalAvailable:J.length})}async handleDescribe(Y){let X=fL6.safeParse(Y);if(!X.success)return C3({error:X.error.flatten()});let Q=await this._cachedTools,J=XK(Q.data),G=bx(X.data.tools,J);return oP({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,X=XK(Y.data);return{tools:[this.getSearchTool(X.length),this.getDescribeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_SEARCH_TOOLS")return this.handleSearch(Y.arguments??{});if(Y.name==="GATEWAY_DESCRIBE_TOOLS")return this.handleDescribe(Y.arguments??{});return{content:[{type:"text",text:`Unknown tool: ${Y.name}. Available: GATEWAY_SEARCH_TOOLS, GATEWAY_DESCRIBE_TOOLS`}],isError:!0}}async routeToolCall(Y){return XO.prototype.callTool.call(this,Y)}}});var hL6,QJ1,z70;var bL6=S(()=>{n0();g$();q70();hL6=z.object({code:z.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:z.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),QJ1=z.toJSONSchema(hL6);z70=class z70 extends j2{constructor(Y,X){super(Y,X)}getRunCodeTool(){return{name:"GATEWAY_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 GATEWAY_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.',inputSchema:QJ1}}async handleRunCode(Y){let X=hL6.safeParse(Y);if(!X.success)return C3({error:X.error.flatten()});let Q=await this._cachedTools,G={tools:XK(Q.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await xx(X.data.code,G,X.data.timeoutMs);if(K.error)return C3(K);return oP(K)}async listTools(){return{tools:[...(await super.listTools()).tools,this.getRunCodeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_RUN_CODE")return this.handleRunCode(Y.arguments??{});return super.callTool(Y)}}});function uL6(Y){let X=Y.slice().sort().join(","),Q=xL6.get(X);if(!Q){let J=z.object({name:(Y.length>0?z.enum(Y):z.string()).describe("The name of the tool to execute"),arguments:z.record(z.string(),z.unknown()).default({}).describe("Arguments to pass to the tool")});Q={schema:J,jsonSchema:z.toJSONSchema(J)},xL6.set(X,Q)}return Q}var xL6,B70;var gL6=S(()=>{n0();g$();q70();xL6=new Map;B70=class B70 extends j2{constructor(Y,X){super(Y,X)}async getCallTool(){let Y=await this._cachedTools,Q=XK(Y.data).map((G)=>G.name),{jsonSchema:J}=uL6(Q);return{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:J}}async handleCallTool(Y){let X=await this._cachedTools,Q=XK(X.data),J=Q.map((F)=>F.name),{schema:G}=uL6(J),K=G.safeParse(Y);if(!K.success)return C3({error:K.error.flatten()});let{name:W,arguments:Z}=K.data;if(!new Map(Q.map((F)=>[F.name,F])).has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return this.routeToolCall({name:W,arguments:Z})}async listTools(){let Y=await super.listTools(),X=await this.getCallTool();return{tools:[...Y.tools,X]}}async callTool(Y){if(Y.name==="GATEWAY_CALL_TOOL")return this.handleCallTool(Y.arguments??{});return super.callTool(Y)}}});function U70(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function JJ1(Y,X){if(Y.connection_type!=="VIRTUAL")return!1;if(!X||oZ(X))return!1;return Y.id===X}async function mL6(Y,X){let Q=Y.id,J=await X.storage.virtualMcps.findById(Q);if(!J)throw Error(`Virtual MCP not found: ${Q}`);return S2(J,X,"passthrough")}async function S2(Y,X,Q){let G=Y.connections.map((H)=>H.connection_id).map((H)=>X.storage.connections.findById(H)),Z={connections:(await Promise.all(G)).filter((H)=>H!==null&&H.status==="active"&&!JJ1(H,Y.id)),virtualMcp:Y};return Q==="smart_tool_selection"?new B70(Z,X):Q==="code_execution"?new z70(Z,X):new XO(Z,X)}var $u=S(()=>{j5();bL6();$70();gL6()});async function lL6(Y,X,Q=!1){if(Y.connection_type==="VIRTUAL")return mL6(Y,X);return SL6(Y,X,Q)}var dL6=S(()=>{kL6();$u()});async function qu(Y,X){let Q=Y.get("meshContext");try{let J=Y.req.header("x-org-id"),G=Y.req.header("x-org-slug"),K=J?J:G?await Q.db.selectFrom("organization").select("id").where("slug","=",G).executeTakeFirst().then((q)=>q?.id):null,W=await Q.storage.virtualMcps.findById(X??null,K??void 0);if(!W)return Y.json({error:"Agent not found"},404);if(K&&W.organization_id!==K)return Y.json({error:"Agent not found"},404);if(W.status!=="active")return Y.json({error:`Agent is inactive: ${W.id??"Decopilot"}`},503);Q.connectionId=W.id??void 0;let Z=await Q.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",W.organization_id).executeTakeFirst();if(Z)Q.organization={id:Z.id,slug:Z.slug,name:Z.name};let H=U70(Y.req.query("mode")),F=await S2(W,Q,H),V=uP(F,{name:`mcp-virtual-mcp-${W.title??"Decopilot"}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:W.metadata?.instructions??void 0}),$=new h$({enableJsonResponse:Y.req.header("Accept")?.includes("application/json")??!1});return await V.connect($),await $.handleRequest(Y.req.raw)}catch(J){let G=J;return console.error("[virtual-mcp] Error handling virtual MCP request:",G),Y.json({error:"Internal server error",message:G.message},500)}}var D70,pL6;var O70=S(()=>{j5();kx();kG();$u();D70=new D9;D70.all("/gateway/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return qu(Y,X)});D70.all("/virtual-mcp/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return qu(Y,X)});pL6=D70});async function cL6(Y,X){return(await X.storage.connections.findById(Y))?.connection_url??null}function GJ1(Y){let X=Y.toLowerCase();return X.includes("resource_metadata=")||X.includes("invalid_token")||X.includes("oauth")}async function nL6(Y,X={}){try{let Q=await fetch(Y,{method:"POST",headers:{...X,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Q.status===401){let J=Q.headers.get("WWW-Authenticate");if(J){if(GJ1(J))return J}if(await WJ1(Y))return'Bearer realm="mcp"'}return null}catch{return null}}async function WJ1(Y){try{let X=new URL(Y),Q=new URL("/.well-known/oauth-authorization-server",X.origin),J=await fetch(Q.toString(),{method:"GET",headers:{Accept:"application/json"}});if(J.ok){let G=await J.json();if(G.authorization_endpoint||G.token_endpoint||G.issuer)return!0}return!1}catch{return!1}}async function Bu(Y){let Q=new URL(Y).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=new URL(Y);J.pathname=`${Q}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!N70.includes(G.status))return G;let K=new URL(Y);if(K.pathname=`/.well-known/oauth-protected-resource${Q}`,G=await fetch(K.toString(),{method:"GET",headers:{Accept:"application/json"}}),!N70.includes(G.status))return G;let W=new URL(Y);return W.pathname="/.well-known/oauth-protected-resource",G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function ZJ1(Y,X){let Q=await cL6(Y,X);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Bu(Q);if(G.ok){let K=await G.json();if(K.authorization_servers?.[0])return K.authorization_servers[0]}}catch{}return J}async function iL6(Y){let X=Y.get("meshContext");if(!X)X=await k3.create(Y.req.raw),Y.set("meshContext",X);return X}async function aL6({error:Y,reqUrl:X,connectionId:Q,connectionUrl:J,headers:G}){let K=Y.message?.toLowerCase()??"";if(!(Y.status===401||Y.code===401||Y.message?.includes("401")||K.includes("unauthorized")||K.includes("invalid_token")||K.includes("api key required")||K.includes("api-key required")))return null;if(Boolean(await nL6(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${X.origin}/mcp/${Q}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}async function L70(Y){let Q=new URL(Y).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=Q!==""&&Q!=="/",G=[];if(J){let W=new URL(Y);W.pathname=`/.well-known/oauth-authorization-server${Q}`,G.push(W);let Z=new URL(Y);Z.pathname=`/.well-known/openid-configuration${Q}`,G.push(Z);let H=new URL(Y);H.pathname=`${Q}/.well-known/openid-configuration`,G.push(H)}else{let W=new URL(Y);W.pathname="/.well-known/oauth-authorization-server",G.push(W);let Z=new URL(Y);Z.pathname="/.well-known/openid-configuration",G.push(Z)}let K=null;for(let W of G){if(K=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),K.ok)return K;if(K.status!==404&&K.status!==401)return K}return K}var zu,N70,rL6=(Y)=>{if(!(Y.hostname==="localhost"||Y.hostname==="127.0.0.1"))Y.protocol="https:";return Y},oL6=async(Y)=>{let X=Y.req.param("connectionId"),Q=await iL6(Y),J=await cL6(X,Q);if(!J)return Y.json({error:"Connection not found"},404);let G=rL6(new URL(Y.req.url)),K=`${G.origin}/mcp/${X}`,W=`${G.origin}/oauth-proxy/${X}`;try{let Z=await Bu(J);if(!Z.ok&&N70.includes(Z.status)){if(await nL6(J))return new Response(JSON.stringify({resource:K,authorization_servers:[W],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:{"Content-Type":"application/json"}})}if(!Z.ok)return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:{"Content-Type":"application/json"}});let H=await Z.json();if("issuer"in H&&!("resource"in H)&&(("authorization_endpoint"in H)||("token_endpoint"in H))){let $={resource:K,authorization_servers:[W],bearer_methods_supported:["header"],scopes_supported:"scopes_supported"in H&&Array.isArray(H.scopes_supported)&&H.scopes_supported.length>0?H.scopes_supported:["*"]};return new Response(JSON.stringify($),{status:200,headers:{"Content-Type":"application/json"}})}let V={...H,resource:K,authorization_servers:[W]};return new Response(JSON.stringify(V),{status:Z.status,statusText:Z.statusText,headers:{"Content-Type":"application/json"}})}catch(Z){let H=Z;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",H),Y.json({error:"Failed to proxy OAuth metadata",message:H.message},502)}},sL6;var w70=S(()=>{kG();Uu();zu=new D9,N70=[404,401,406];zu.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Y)=>oL6(Y));zu.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Y)=>oL6(Y));zu.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=await iL6(Y),J=await ZJ1(X,Q);if(!J)return Y.json({error:"Connection not found or no auth server"},404);try{let G=await L70(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let K=await G.json(),Z=`${rL6(new URL(Y.req.url)).origin}/oauth-proxy/${X}`,H={...K,authorization_endpoint:K.authorization_endpoint?`${Z}/authorize`:void 0,token_endpoint:K.token_endpoint?`${Z}/token`:void 0,registration_endpoint:K.registration_endpoint?`${Z}/register`:void 0};return new Response(JSON.stringify(H),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let K=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",K),Y.json({error:"Failed to proxy auth server metadata",message:K.message},502)}});sL6=zu});function KJ1(Y){if(!Y.isError)return;let X=Y.content;if(!Array.isArray(X))return;for(let Q of X)if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text;return}function HJ1(Y){if(!Y)return;let X=Y._meta;if(!X||typeof X!=="object"||Array.isArray(X))return;let Q=X.properties;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J={};for(let[G,K]of Object.entries(Q))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function FJ1(Y,X){if(!Y&&!X)return;if(!Y)return X;if(!X)return Y;return{...X,...Y}}function eL6(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let X=Y,Q=X.structuredContent;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return X}return{value:Y}}async function VJ1(Y,X){let Q=Y.body;if(!Q)return{text:"",truncated:!1};let J=Q.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>X){K=!0;let V=X-(W-H.byteLength);if(V>0)Z.push(G.decode(H.slice(0,V),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}async function k2(Y){let{ctx:X,enabled:Q}=Y,J=Y.organizationId??X.organization?.id;if(!Q||!J)return;if(oZ(Y.connectionId))return;let G=HJ1(Y.request.params.arguments),K=FJ1(X.metadata.properties,G);await X.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:X.auth.user?.id||X.auth.apiKey?.userId||null,requestId:X.metadata.requestId,userAgent:X.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function Yw6(Y){let{ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),V=Date.now()-H;return await k2({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:eL6(F),isError:Boolean(F.isError),errorMessage:KJ1(F),durationMs:V}),F}catch(F){let V=F,$=Date.now()-H;throw await k2({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}function Xw6(Y){let{ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),V=X.organization?.id;if(Q&&V){let $=F.clone();(async()=>{try{let{text:q,truncated:B}=await VJ1($,tL6),D=Date.now()-H,O=$.headers.get("content-type")??"",L=q;if(O.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=F.status>=400,I=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof I==="string"&&I?I:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():B?`Response body truncated to ${tL6} bytes`:void 0;await k2({ctx:X,enabled:Q,organizationId:V,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:eL6(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let B=Date.now()-H;await k2({ctx:X,enabled:Q,organizationId:V,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:B})}})()}return F}catch(F){let V=F,$=Date.now()-H;throw await k2({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}var tL6=262144;var Qw6=S(()=>{j5()});function $J1(Y,X,Q){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await Q();return H.find((V)=>V.name===K)?._meta};return await new S3(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,X,W).check(K),await G()}catch(K){return{content:[{type:"text",text:`Authorization failed: ${K.message}`}],isError:!0}}}}function qJ1(Y,X,Q){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await Q();return H.find((V)=>V.name===K)?._meta};return await new S3(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,X,W).check(K),await G()}catch(K){return new Response(JSON.stringify({error:`Authorization failed: ${K.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}function r$(Y){return{client:{callTool:Y.callTool.bind(Y),listTools:Y.listTools.bind(Y)},callStreamableTool:Y.callStreamableTool.bind(Y)}}async function Jw6(Y,X,{superUser:Q}){let J=typeof Y==="string"?await X.storage.connections.findById(Y,X.organization?.id):Y;if(!J)throw Error("Connection not found");let G=J?.id;if(X.organization&&J.organization_id!==X.organization.id)throw Error("Connection does not belong to the active organization");if(X.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let K=await lL6(J,X,Q),W=async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((L)=>({name:L.name,description:L.description,inputSchema:L.inputSchema,outputSchema:L.outputSchema,annotations:L.annotations,_meta:L._meta}))};return await K.listTools()},Z=X.connectionId&&X.connectionId!==G?X.connectionId:void 0,H={enabled:cT0().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:Z,ctx:X},F=async(L)=>{return iP(Yw6(H),Q?async(I,T)=>await T():$J1(X,G,W))(L,async()=>{let I=Date.now(),T={...L.params};if(T.arguments&&"_meta"in T.arguments){let{_meta:P,...A}=T.arguments;T.arguments=A}return await X.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":L.params.name,"request.id":X.metadata.requestId}},async(P)=>{try{let A=await K.callTool(T,void 0,{timeout:M70}),R=Date.now()-I;return X.meter.createHistogram("connection.proxy.duration").record(R,{"connection.id":G,"tool.name":L.params.name,status:"success"}),X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":L.params.name,status:"success"}),P.end(),A}catch(A){let R=A,j=Date.now()-I;throw X.meter.createHistogram("connection.proxy.duration").record(j,{"connection.id":G,"tool.name":L.params.name,status:"error"}),X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":L.params.name,error:R.message}),P.recordException(R),P.end(),A}})})};return{callTool:(L)=>F({method:"tools/call",params:L}),listTools:W,listResources:async()=>{try{return await K.listResources()}catch(L){if(L instanceof $6&&L.code===L6.MethodNotFound)return{resources:[]};throw L}},readResource:async(L)=>K.readResource(L),listResourceTemplates:async()=>{try{return await K.listResourceTemplates()}catch(L){if(L instanceof $6&&L.code===L6.MethodNotFound)return{resourceTemplates:[]};throw L}},listPrompts:async()=>{try{return await K.listPrompts()}catch(L){if(L instanceof $6&&L.code===L6.MethodNotFound)return{prompts:[]};throw L}},getPrompt:async(L)=>K.getPrompt(L),getServerCapabilities:()=>K.getServerCapabilities(),getInstructions:()=>K.getInstructions(),close:()=>K.close(),callStreamableTool:async(L,w)=>{if(J.connection_type==="VIRTUAL"){let A=await F({method:"tools/call",params:{name:L,arguments:w}});return new Response(JSON.stringify(A),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let I=J.connection_url,T={method:"tools/call",params:{name:L,arguments:w}};return iP(Xw6(H),Q?async(A,R)=>await R():qJ1(X,G,W))(T,async()=>{let A=await R2(J,X,Q),R=J.connection_headers;if(R&&"headers"in R)Object.assign(A,R.headers);let j=new URL(I);return j.pathname=j.pathname.replace(/\/$/,"")+`/call-tool/${T.params.name}`,await X.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":T.params.name,"request.id":X.metadata.requestId}},async(k)=>{let y=Date.now();try{let f=await fetch(j.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(T.params.arguments),headers:{...A,"Content-Type":"application/json"}}),h=Date.now()-y;return X.meter.createHistogram("connection.proxy.streamable.duration").record(h,{"connection.id":G,"tool.name":T.params.name,status:f.ok?"success":"error"}),X.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":T.params.name,status:f.ok?"success":"error"}),k.end(),f}catch(f){let h=f,s=Date.now()-y;throw X.meter.createHistogram("connection.proxy.streamable.duration").record(s,{"connection.id":G,"tool.name":T.params.name,status:"error"}),X.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":T.params.name,error:h.message}),k.recordException(h),k.end(),f}})})},[Symbol.asyncDispose]:()=>K.close()}}async function Gw6(Y,X){return Jw6(Y,X,{superUser:!1})}async function Ww6(Y,X){return Jw6(Y,X,{superUser:!0})}var Du,M70=300000,Zw6=(Y,X)=>{if(Y.message.includes("not found"))return X.json({error:Y.message},404);if(Y.message.includes("does not belong to the active organization"))return X.json({error:"Connection not found"},404);if(Y.message.includes("inactive"))return X.json({error:Y.message},503);return X.json({error:"Internal server error",message:Y.message},500)},Kw6;var o$=S(()=>{Ev();dL6();V70();j5();kx();OX();kG();Vu();O70();w70();Qw6();Du=new D9;Du.all("/",async(Y)=>{return qu(Y,void 0)});Du.all("/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=Y.get("meshContext");try{try{let J=await Q.createMCPProxy(X),G=uP(J,{name:"mcp-mesh",version:"1.0.0"}),K=new h$({enableJsonResponse:Y.req.raw.headers.get("Accept")?.includes("application/json")??!1});await G.connect(K);try{return await K.handleRequest(Y.req.raw)}finally{try{await K.close?.()}catch{}}}catch(J){let G=await Q.storage.connections.findById(X,Q.organization?.id);if(G?.connection_url){let K=await aL6({error:J,reqUrl:new URL(Y.req.raw.url),connectionId:X,connectionUrl:G.connection_url,headers:{}});if(K)return K}throw J}}catch(J){return Zw6(J,Y)}});Du.all("/:connectionId/call-tool/:toolName",async(Y)=>{let X=Y.req.param("connectionId"),Q=Y.req.param("toolName"),J=Y.get("meshContext");try{let K=await(await J.createMCPProxy(X)).callTool({name:Q,arguments:await Y.req.json()});if(K instanceof Response)return K;if(K.isError)return new Response(JSON.stringify(K.content),{headers:{"Content-Type":"application/json"},status:500});return new Response(JSON.stringify(K.structuredContent??K.content),{headers:{"Content-Type":"application/json"}})}catch(G){return Zw6(G,Y)}});Kw6=Du});class A70{db;constructor(Y){this.db=Y}async create(Y){let X=Y.id??B9("thrd"),Q=new Date().toISOString();if(!Y.organizationId)throw Error("organizationId is required");if(!Y.createdBy)throw Error("createdBy is required");if(!Y.title)Y.title="New Thread - "+Q;let J={id:X,organization_id:Y.organizationId,title:Y.title,description:Y.description??null,created_at:Q,updated_at:Q,created_by:Y.createdBy,updated_by:Y.updatedBy??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let X=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return X?this.threadFromDbRow(X):null}async update(Y,X){let J={updated_at:new Date().toISOString()};if(X.title!==void 0)J.title=X.title;if(X.description!==void 0)J.description=X.description;if(X.updatedBy!==void 0)J.updated_by=X.updatedBy;if(X.hidden!==void 0)J.hidden=X.hidden;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,X,Q){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(X)J=J.where("created_by","=",X);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(X)G=G.where("created_by","=",X);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let X=new Date().toISOString(),Q=Y[0]?.threadId;if(!Q)throw Error("threadId is required when creating multiple messages");let J=Y.find((K)=>K.threadId!==Q);if(J)throw Error(`All messages must target the same thread. Expected threadId "${Q}", but message "${J.id}" has threadId "${J.threadId}"`);let G=Y.map((K)=>({id:K.id,thread_id:Q,metadata:K.metadata?JSON.stringify(K.metadata):null,parts:JSON.stringify(K.parts),role:K.role,created_at:K.createdAt??X,updated_at:X}));await this.db.transaction().execute(async(K)=>{await K.insertInto("thread_messages").values(G).execute(),await K.updateTable("threads").set({updated_at:X}).where("id","=",Q).execute()})}async listMessages(Y,X){let Q=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at","asc").orderBy("id","asc"),J=this.db.selectFrom("thread_messages").select((W)=>W.fn.count("id").as("count")).where("thread_id","=",Y);if(X?.limit)Q=Q.limit(X.limit);if(X?.offset)Q=Q.offset(X.offset);let[G,K]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{messages:G.map((W)=>this.messageFromDbRow(W)),total:Number(K?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organizationId:Y.organization_id,title:Y.title,description:Y.description,createdAt:typeof Y.created_at==="string"?Y.created_at:Y.created_at.toISOString(),updatedAt:typeof Y.updated_at==="string"?Y.updated_at:Y.updated_at.toISOString(),createdBy:Y.created_by,updatedBy:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let X,Q;try{X=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),X=void 0}try{Q=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),Q=[]}return{id:Y.id,threadId:Y.thread_id,metadata:X,parts:Q,role:Y.role,createdAt:typeof Y.created_at==="string"?Y.created_at:Y.created_at.toISOString(),updatedAt:typeof Y.updated_at==="string"?Y.updated_at:Y.updated_at.toISOString()}}}var Hw6=S(()=>{tZ()});function Fw6(){let Y=new Map;function X(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;let W=new R5({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(X,{[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 Vw6=S(()=>{CD()});function zJ1(Y){if(!Y)return;try{let X=JSON.parse(Y);if(typeof X!=="object"||X===null||Array.isArray(X))return;let Q={};for(let[J,G]of Object.entries(X))if(typeof G==="string")Q[J]=G;return Object.keys(Q).length>0?Q:void 0}catch{return}}function BJ1(Y,X){for(let[Q,J]of Object.entries(X)){let G=Y[Q];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function UJ1(Y){let{auth:X,headers:Q,role:J,permissions:G,userId:K}=Y,W=X.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&mG0.includes(J))return!0;if(G)return BJ1(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:Q,body:{permission:Z}}))?.success===!0)return!0;let F={};for(let $ of Object.keys(Z))F[$]=["*"];return(await W({headers:Q,body:{permission:F}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return X.api.createOrganization({headers:Q,body:Z})},update:async(Z)=>{return X.api.updateOrganization({headers:Q,body:Z})},delete:async(Z)=>{await X.api.deleteOrganization({headers:Q,body:{organizationId:Z}})},get:async(Z)=>{return X.api.getFullOrganization({headers:Q,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return X.api.listOrganizations({headers:Q,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return X.api.addMember({headers:Q,body:Z})},removeMember:async(Z)=>{await X.api.removeMember({headers:Q,body:Z})},listMembers:async(Z)=>{return X.api.listMembers({headers:Q,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return X.api.updateMemberRole({headers:Q,body:Z})}},apiKey:{create:async(Z)=>{return X.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return X.api.listApiKeys({headers:Q})},update:async(Z)=>{return X.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await X.api.deleteApiKey({headers:Q,body:{keyId:Z}})}}}}async function DJ1(Y,X,Q){if(mG0.includes(Q))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",X).where("role","=",Q).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Q}`);return}}async function OJ1(Y,X,Q,J=qw6){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>X.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),F=H?.role,V=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,$;if(H&&F)$=await J.measure("auth_fetch_role_permissions",()=>DJ1(Q,H.organizationId,F));return{user:{id:Z,role:F},role:F,permissions:$,organization:V}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>AL6(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>X.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,F,V=W.key.userId;if(V&&Z?.id)F=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",V).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:F},role:F,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=await J.measure("auth_get_session",()=>X.api.getSession({headers:Y.headers}));if(K){let W,Z;if(K.session.activeOrganizationId){let H=await J.measure("auth_get_full_organization",()=>X.api.getFullOrganization({headers:Y.headers}).catch(()=>null));if(H)W={id:H.id,slug:H.slug,name:H.name},Z=H.members?.find((V)=>V.userId===K.user.id)?.role;else W={id:K.session.activeOrganizationId,slug:"",name:""}}return{user:{id:K.user.id,email:K.user.email,role:Z},role:Z,organization:W}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}async function zw6(Y){let G=[];try{let X=new k$(Y.encryption.key);let Q={connections:new mP(Y.db,X),organizationSettings:new K70(Y.db),monitoring:new Z70(Y.db,Y.databaseType),virtualMcps:new G70(Y.db),users:new H70(Y.db),threads:new A70(Y.db)};const J=gG(G,Fw6(),1);return async(F,V)=>{let $=V?.timings??qw6,q=F?.headers.get("x-caller-id")??void 0,B=F?await OJ1(F,Y.auth,Y.db,$):{user:void 0},D=UJ1({auth:Y.auth,headers:F?.headers??new Headers,role:B.role,permissions:B.permissions,userId:B.user?.id}),O={user:B.user};if(B.apiKeyId)O.apiKey={id:B.apiKeyId,name:"",userId:""};let L=B.organization,w=F?process.env.BASE_URL??`${new URL(F.url).origin}`:t5(),I=new S3(Y.auth,O.user?.id,void 0,D,B.role,"self"),T={timings:$,auth:O,connectionId:q,organization:L,storage:Q,vault:X,authInstance:Y.auth,boundAuth:D,access:I,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:w,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(NJ1.map((P)=>[P,F?.headers.get(P)??null]).filter(([P,A])=>A!==null)),userAgent:F?.headers.get("x-mesh-client")||F?.headers.get("User-Agent")||void 0,ipAddress:(F?.headers.get("CF-Connecting-IP")||F?.headers.get("X-Forwarded-For"))??void 0,properties:zJ1(F?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(P)=>{return await Gw6(P,T)},getOrCreateClient:J};return T}}catch(K){var W=K,Z=1}finally{var H=PW(G,W,Z);H&&await H}}var $w6,k3,qw6,NJ1;var Uu=S(()=>{J70();Ax();rJ0();TL6();PL6();Vu();o$();lG0();Hw6();Vw6();k3={set:(Y)=>{$w6=Y},create:async(Y,X)=>{return await $w6(Y,X)}},qw6={measure:async(Y,X)=>{return await X()}},NJ1=["x-hub-signature-256"]});class Bw6{db;constructor(Y){this.db=Y}async publishEvent(Y){let X=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:X,updated_at:X}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:X,updatedAt:X}}async subscribe(Y){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)X=X.where("publisher","=",Y.publisher);else X=X.where("publisher","is",null);if(Y.filter)X=X.where("filter","=",Y.filter);else X=X.where("filter","is",null);let Q=await X.executeTakeFirst();if(Q)return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,X){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",X).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,X){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(X)Q=Q.where("connection_id","=",X);return(await Q.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,X){let Q=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",X).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((Q)=>Q.or([Q("publisher","is",null),Q("publisher","=",Y.source)])).execute()).map((Q)=>({id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}))}async createDeliveries(Y,X,Q){if(X.length===0)return;let J=new Date().toISOString(),G=Q??null,K=X.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let X=new Date().toISOString(),Q;try{Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];Q=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Q).where("status","=","pending").execute()}if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let X=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:X}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,X,Q=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=Q)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:X,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),F=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:X,status:"pending",next_retry_at:F}).where("id","=",K).execute()}}}async updateEventStatus(Y){let X=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(X.length===0)return;let Q=X.every((K)=>K.status==="delivered"),J=X.some((K)=>K.status==="failed"),G=X.some((K)=>K.status==="pending"||K.status==="processing");if(Q)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,X){let Q=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",X).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,type:Q.type,source:Q.source,specversion:Q.specversion,subject:Q.subject,time:Q.time,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema,data:Q.data?JSON.parse(Q.data):null,cron:Q.cron,status:Q.status,attempts:Q.attempts,lastError:Q.last_error,nextRetryAt:Q.next_retry_at,createdAt:Q.created_at,updatedAt:Q.updated_at}}async findActiveCronEvent(Y,X,Q,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",X).where("source","=",Q).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,X,Q){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",X).where("source","=",Q).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,X){if(Y.length===0)return;let Q=new Date(Date.now()+X).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Q}).where("id","in",Y).execute()}async ackDelivery(Y,X,Q){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",X).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Q).where("event_subscriptions.organization_id","=",X))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:X,connectionId:Q,subscriptions:J}=Y,G=(w,I)=>{return`${w}::${I??""}`},K=await this.listSubscriptions(X,Q),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),F=[],V=[],$=[],q=0;for(let[w,I]of Z){let T=W.get(w);if(!T)F.push({id:crypto.randomUUID(),organization_id:X,connection_id:Q,event_type:I.eventType,publisher:I.publisher??null,filter:I.filter??null,enabled:1,created_at:H,updated_at:H});else{let P=T.filter??null,A=I.filter??null;if(P!==A)V.push({id:T.id,filter:A});else q++}}for(let[w,I]of W)if(!Z.has(w))$.push(I.id);if(F.length>0)await this.db.insertInto("event_subscriptions").values(F).execute();if(V.length>0)await Promise.all(V.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if($.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",$).execute();let B=F.length,D=V.length,O=$.length,L=await this.listSubscriptions(X,Q);return{created:B,updated:D,deleted:O,unchanged:q,subscriptions:L}}}function Uw6(Y){return new Bw6(Y)}function wX(Y,X,Q,J,G,K,W,Z){return wX.fromTZ(wX.tp(Y,X,Q,J,G,K,W),Z)}function T70(Y,X=new Date){let Q=X.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=X.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Q}`)}function LJ1(Y,X){let Q=new Date(Date.parse(Y));if(isNaN(Q))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?wX.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):wX.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),X)}function wJ1(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new v5(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new v5(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function v2(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function MJ1(Y){return v2(Y)}function AJ1(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var P70=32,_2,Lw6,Dw6=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,X){this.pattern=Y,this.timezone=X,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let X=new v5(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",X.getSeconds().toString()),Y[1]=Y[1].replace("?",X.getMinutes().toString()),Y[2]=Y[2].replace("?",X.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",X.getDate().toString())),Y[4]=Y[4].replace("?",(X.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",X.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,_2),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,X,Q,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(X===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+X+") is empty, check for trailing spaces.");if(X==="*")return G.fill(J);let W=X.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],Q,J);else X.indexOf("-")!==-1&&X.indexOf("/")!==-1?this.handleRangeWithStepping(X,Y,Q,J):X.indexOf("-")!==-1?this.handleRange(X,Y,Q,J):X.indexOf("/")!==-1?this.handleStepping(X,Y,Q,J):X!==""&&this.handleNumber(X,Y,Q,J)}throwAtIllegalCharacters(Y){for(let X=0;X<Y.length;X++)if((X===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[X]))throw TypeError("CronPattern: configuration entry "+X+" ("+Y[X]+") contains illegal characters.")}handleNumber(Y,X,Q,J){let G=this.extractNth(Y,X),K=parseInt(G[0],10)+Q;if(isNaN(K))throw TypeError("CronPattern: "+X+" is not a number: '"+Y+"'");this.setPart(X,K,G[1]||J)}setPart(Y,X,Q){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(X===7&&(X=0),X<0||X>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+X);this.setNthWeekdayOfMonth(X,Q);return}if(Y==="second"||Y==="minute"){if(X<0||X>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+X)}else if(Y==="hour"){if(X<0||X>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+X)}else if(Y==="day"){if(X<0||X>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+X)}else if(Y==="month"&&(X<0||X>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+X);this[Y][X]=Q}handleRangeWithStepping(Y,X,Q,J){let G=this.extractNth(Y,X),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,F=parseInt(W,10)+Q,V=parseInt(Z,10)+Q,$=parseInt(H,10);if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[X].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[X].length+")");if(F>V)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let q=F;q<=V;q+=$)this.setPart(X,q,G[1]||J)}extractNth(Y,X){let Q=Y,J;if(Q.includes("#")){if(X!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Q.split("#")[1],Q=Q.split("#")[0]}return[Q,J]}handleRange(Y,X,Q,J){let G=this.extractNth(Y,X),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+Q,Z=parseInt(K[1],10)+Q;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(X,H,G[1]||J)}handleStepping(Y,X,Q,J){let G=this.extractNth(Y,X),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+Q);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[X].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[X].length+")");for(let H=W;H<this[X].length;H+=Z)this.setPart(X,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let X=Y.trim().toLowerCase();return X==="@yearly"||X==="@annually"?"0 0 1 1 *":X==="@monthly"?"0 0 1 * *":X==="@weekly"?"0 0 * * 0":X==="@daily"?"0 0 * * *":X==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,X){if(typeof X!="number"&&X==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|P70;else if(X===_2)this.dayOfWeek[Y]=_2;else if(X<6&&X>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|Lw6[X-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${X}, Type: ${typeof X}`)}},Ow6,KK,v5=class Y{tz;ms;second;minute;hour;day;month;year;constructor(X,Q){if(this.tz=Q,X&&X instanceof Date)if(!isNaN(X))this.fromDate(X);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(X===void 0)this.fromDate(new Date);else if(X&&typeof X=="string")this.fromString(X);else if(X instanceof Y)this.fromCronDate(X);else throw TypeError("CronDate: Invalid type ("+typeof X+") passed to CronDate constructor")}isNthWeekdayOfMonth(X,Q,J,G){let K=new Date(Date.UTC(X,Q,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(X,Q,Z)).getUTCDay()===K&&W++;if(G&_2&&Lw6[W-1]&G)return!0;if(G&P70){let Z=new Date(Date.UTC(X,Q+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(X,Q,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(X){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes()+this.tz,this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply();else{let Q=wX.toTZ(X,this.tz);this.ms=X.getMilliseconds(),this.second=Q.s,this.minute=Q.i,this.hour=Q.h,this.day=Q.d,this.month=Q.m-1,this.year=Q.y}else this.ms=X.getMilliseconds(),this.second=X.getSeconds(),this.minute=X.getMinutes(),this.hour=X.getHours(),this.day=X.getDate(),this.month=X.getMonth(),this.year=X.getFullYear()}fromCronDate(X){this.tz=X.tz,this.year=X.year,this.month=X.month,this.day=X.day,this.hour=X.hour,this.minute=X.minute,this.second=X.second,this.ms=X.ms}apply(){if(this.month>11||this.day>Ow6[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let X=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),!0}else return!1}fromString(X){if(typeof this.tz=="number"){let Q=wX.fromTZISO(X);this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply()}else return this.fromDate(wX.fromTZISO(X,this.tz))}findNext(X,Q,J,G){let K=this[Q],W;J.lastDayOfMonth&&(this.month!==1?W=Ow6[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&Q=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[Q]+G;H<J[Q].length;H++){let F=J[Q][H];if(Q==="day"&&J.lastDayOfMonth&&H-G==W&&(F=1),Q==="day"&&!J.starDOW){let V=J.dayOfWeek[(Z+(H-G-1))%7];if(V&&V&_2)V=this.isNthWeekdayOfMonth(this.year,this.month,H-G,V)?1:0;else if(V)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${V}`);X.legacyMode&&!J.starDOM?F=F||V:F=F&&V}if(F)return this[Q]=H-G,K!==this[Q]?2:1}return 3}recurse(X,Q,J){let G=this.findNext(Q,KK[J][0],X,KK[J][2]);if(G>1){let K=J+1;for(;K<KK.length;)this[KK[K][0]]=-KK[K][2],K++;if(G===3)return this[KK[J][1]]++,this[KK[J][0]]=-KK[J][2],this.apply(),this.recurse(X,Q,0);if(this.apply())return this.recurse(X,Q,J-1)}return J+=1,J>=KK.length?this:this.year>=3000?null:this.recurse(X,Q,J)}increment(X,Q,J){return this.second+=Q.interval!==void 0&&Q.interval>1&&J?Q.interval:1,this.ms=0,this.apply(),this.recurse(X,Q,0)}getDate(X){return X||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):wX.fromTZ(wX.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},Nw6=30000,Ou,Nu=class{name;options;_states;fn;constructor(Y,X,Q){let J,G;if(v2(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(v2(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=wJ1(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Dw6("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new v5(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Dw6(Y,this.options.timezone),this.name){if(Ou.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Ou.push(this)}return G!==void 0&&MJ1(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let X=this._next(Y);return X?X.getDate(!1):null}nextRuns(Y,X){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let Q=[],J=X||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)Q.push(J);return Q}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),X=!this._states.paused,Q=this.fn!==void 0,J=!this._states.kill;return X&&Q&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let X=this._next(Y);return X?Y instanceof v5||Y instanceof Date?X.getTime()-Y.getTime():X.getTime()-new v5(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Ou.indexOf(this);Y>=0&&Ou.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let X=this.msToNext(),Q=this.nextRun(this._states.currentRun);return X==null||isNaN(X)||Q===null?this:(X>Nw6&&(X=Nw6),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),X),this._states.currentTimeout&&this.options.unref&&AJ1(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new v5(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(X){v2(this.options.catch)&&this.options.catch(X,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new v5(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let X=new Date,Q=!this._states.paused&&X.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;Q&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Q&&J&&v2(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let X=!!(Y||this._states.currentRun),Q=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,X]=this._calculatePreviousRun(Y,X),Q=!Y),Y=new v5(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new v5(Y,this.options.timezone||this.options.utcOffset);return!Q&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,X)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,X){let Q=new v5(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=Q.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Q.getTime();)J=new v5(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;X=!0}return J===null&&(J=void 0),[J,X]}};var E70=S(()=>{wX.fromTZISO=(Y,X,Q)=>wX.fromTZ(LJ1(Y,X),Q);wX.fromTZ=function(Y,X){let Q=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=T70(Y.tz,Q),G=new Date(Q.getTime()-J),K=T70(Y.tz,G);if(K-J===0)return G;{let W=new Date(Q.getTime()-K),Z=T70(Y.tz,W);if(Z-K===0)return W;if(!X&&Z-K>0)return W;if(X)throw Error("Invalid date passed to fromTZ()");return G}};wX.toTZ=function(Y,X){let Q=Y.toLocaleString("en-US",{timeZone:X}).replace(/[\u202f]/," "),J=new Date(Q);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:X}};wX.tp=(Y,X,Q,J,G,K,W)=>({y:Y,m:X,d:Q,h:J,i:G,s:K,tz:W});wX.minitz=wX;_2=31|P70,Lw6=[1,2,4,8,16],Ow6=[31,28,31,30,31,30,31,31,30,31,30,31],KK=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];Ou=[]});var Lu;var C70=S(()=>{Lu={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function ww6(){return async(Y,X)=>{try{let Q=await k3.create(),J=await Ww6(Y,Q),K=await a50.forClient(r$(J)).ON_EVENTS({events:X});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(Q){let J=Q instanceof Error?Q.message:String(Q);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}var Mw6=S(()=>{Uu();px();o$()});function Aw6(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function TJ1(Y){let X=new Map;for(let J of Y){let G=J.subscription.connectionId,K=X.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(Aw6(J.event))}else X.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[Aw6(J.event)],seenEventIds:new Set([J.event.id])})}let Q=new Map;for(let[J,G]of X)Q.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Q}class I70{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Y,X){this.storage=Y;this.notifySubscriber=ww6(),this.config={...Lu,...X}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let X=TJ1(Y),Q=new Set;for(let[J,G]of X){try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))Q.add(K.event.id)}for(let J of Q)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,X){let Q=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=X.results?.[W.id];if(H)if(H.success)Q.push(Z);else if(H.retryAfter&&H.retryAfter>0){let F=J.get(H.retryAfter)||[];F.push(Z),J.set(H.retryAfter,F)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(X.success)Q.push(Z);else if(X.retryAfter&&X.retryAfter>0){let F=J.get(X.retryAfter)||[];F.push(Z),J.set(X.retryAfter,F)}else G.push({deliveryId:Z,error:X.error||"Batch processing failed"})}if(Q.length>0)await this.storage.markDeliveriesDelivered(Q);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let F=W.get(H)||[];F.push(Z),W.set(H,F)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let Q=new Nu(Y.cron).nextRun();if(!Q){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=Q.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(X){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,X)}}}var Tw6=S(()=>{E70();C70();Mw6()});class R70{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new I70(this.storage,Y.config)}async publish(Y,X,Q){if(Q.deliverAt&&Q.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Q.cron){try{let V=new Nu(Q.cron).nextRun();if(!V)throw Error("Cron expression does not produce a next run time");J=V.toISOString()}catch(F){throw Error(`Invalid cron expression: ${F instanceof Error?F.message:String(F)}`)}let H=await this.storage.findActiveCronEvent(Y,Q.type,X,Q.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:Q.type,source:X,subject:Q.subject,time:K,data:Q.data,cron:Q.cron}),Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=Q.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map((F)=>F.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch((F)=>{console.warn("[EventBus] Notify failed (non-critical):",F)})}return W}async subscribe(Y,X){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:X.connectionId,publisher:X.publisher,eventType:X.eventType,filter:X.filter})}async unsubscribe(Y,X){return this.storage.unsubscribe(X,Y)}async listSubscriptions(Y,X){return this.storage.listSubscriptions(Y,X)}async getSubscription(Y,X){return this.storage.getSubscription(X,Y)}async getEvent(Y,X){return this.storage.getEvent(X,Y)}async cancelEvent(Y,X,Q){return this.storage.cancelEvent(X,Y,Q)}async ackEvent(Y,X,Q){return this.storage.ackDelivery(X,Y,Q)}async syncSubscriptions(Y,X){return this.storage.syncSubscriptions({organizationId:Y,...X})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}var Pw6=S(()=>{E70();Tw6()});function Ew6(...Y){return{async start(X){await Promise.all(Y.map((Q)=>Q.start(X)))},async stop(){await Promise.all(Y.map((X)=>X.stop().catch((Q)=>{console.error("[NotifyStrategy] Error stopping strategy:",Q)})))},async notify(X){await Promise.all(Y.map((Q)=>Q.notify(X).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class wu{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as PJ1}from"kysely";class j70{db;pool;listenClient=null;onNotify=null;constructor(Y,X){this.db=Y;this.pool=X}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(X)=>{if(X.channel===QO&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(X)=>{console.error("[PostgresNotify] Connection error:",X),this.cleanup()}),await this.listenClient.query(`LISTEN ${QO}`),console.log("[PostgresNotify] Started LISTEN on",QO)}catch(X){console.error("[PostgresNotify] Failed to start LISTEN:",X),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${QO}`),console.log("[PostgresNotify] Stopped LISTEN on",QO)}catch{}this.cleanup()}}async notify(Y){try{await PJ1`SELECT pg_notify(${QO}, ${Y})`.execute(this.db)}catch(X){console.warn("[PostgresNotify] Failed to send NOTIFY:",X)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var QO="mesh_events";var Cw6=()=>{};function Iw6(Y,X){let Q=Uw6(Y.db),J=X?.pollIntervalMs??Lu.pollIntervalMs,G=Y.type==="postgres"?Ew6(new wu(J),new j70(Y.db,Y.pool)):new wu(J);return new R70({storage:Q,config:X,notifyStrategy:G})}var Rw6=S(()=>{Pw6();C70();Cw6()});var jw6;var Sw6=S(()=>{jw6={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var kw6,vw6;var _w6=S(()=>{kG();sD();Sw6();kw6=new D9;kw6.get("/config",async(Y)=>{try{let X=Object.keys(U9.socialProviders??{}),Q=X.length>0,J=X.map((W)=>({name:W,icon:jw6[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:U9.emailAndPassword?.enabled??!1},magicLink:{enabled:U9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:U9.ssoConfig?{enabled:!0,providerId:U9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(X){let Q=X instanceof Error?X.message:"Failed to load auth config";return Y.json({success:!1,error:Q},500)}});vw6=kw6});function vG(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.message;return JSON.stringify(Y)}var HM6="vercel.ai.error",EJ1,yw6,fw6,M6,FM6="AI_APICallError",VM6,CJ1,hw6,bw6,t8,$M6="AI_EmptyResponseBodyError",qM6,IJ1,xw6,uw6,zM6,BM6="AI_InvalidArgumentError",UM6,RJ1,gw6,mw6,DM6,OM6="AI_InvalidPromptError",NM6,jJ1,lw6,dw6,s$,LM6="AI_InvalidResponseDataError",wM6,SJ1,pw6,cw6,WM8,MM6="AI_JSONParseError",AM6,kJ1,nw6,iw6,y2,TM6="AI_LoadAPIKeyError",PM6,vJ1,aw6,rw6,ZM8,EM6="AI_LoadSettingError",CM6,_J1,ow6,sw6,KM8,IM6="AI_NoContentGeneratedError",RM6,yJ1,tw6,ew6,HM8,jM6="AI_NoSuchModelError",SM6,fJ1,YM6,XM6,FM8,kM6="AI_TooManyEmbeddingValuesForCallError",vM6,hJ1,QM6,JM6,VM8,_M6="AI_TypeValidationError",yM6,bJ1,GM6,WM6,uQ,fM6="AI_UnsupportedFunctionalityError",hM6,xJ1,ZM6,KM6,bM6;var w1=S(()=>{EJ1=Symbol.for(HM6),M6=class Y extends(fw6=Error,yw6=EJ1,fw6){constructor({name:X,message:Q,cause:J}){super(Q);this[yw6]=!0,this.name=X,this.cause=J}static isInstance(X){return Y.hasMarker(X,HM6)}static hasMarker(X,Q){let J=Symbol.for(Q);return X!=null&&typeof X==="object"&&J in X&&typeof X[J]==="boolean"&&X[J]===!0}},VM6=`vercel.ai.error.${FM6}`,CJ1=Symbol.for(VM6),t8=class extends(bw6=M6,hw6=CJ1,bw6){constructor({message:Y,url:X,requestBodyValues:Q,statusCode:J,responseHeaders:G,responseBody:K,cause:W,isRetryable:Z=J!=null&&(J===408||J===409||J===429||J>=500),data:H}){super({name:FM6,message:Y,cause:W});this[hw6]=!0,this.url=X,this.requestBodyValues=Q,this.statusCode=J,this.responseHeaders=G,this.responseBody=K,this.isRetryable=Z,this.data=H}static isInstance(Y){return M6.hasMarker(Y,VM6)}},qM6=`vercel.ai.error.${$M6}`,IJ1=Symbol.for(qM6),zM6=class extends(uw6=M6,xw6=IJ1,uw6){constructor({message:Y="Empty response body"}={}){super({name:$M6,message:Y});this[xw6]=!0}static isInstance(Y){return M6.hasMarker(Y,qM6)}};UM6=`vercel.ai.error.${BM6}`,RJ1=Symbol.for(UM6),DM6=class extends(mw6=M6,gw6=RJ1,mw6){constructor({message:Y,cause:X,argument:Q}){super({name:BM6,message:Y,cause:X});this[gw6]=!0,this.argument=Q}static isInstance(Y){return M6.hasMarker(Y,UM6)}},NM6=`vercel.ai.error.${OM6}`,jJ1=Symbol.for(NM6),s$=class extends(dw6=M6,lw6=jJ1,dw6){constructor({prompt:Y,message:X,cause:Q}){super({name:OM6,message:`Invalid prompt: ${X}`,cause:Q});this[lw6]=!0,this.prompt=Y}static isInstance(Y){return M6.hasMarker(Y,NM6)}},wM6=`vercel.ai.error.${LM6}`,SJ1=Symbol.for(wM6),WM8=class extends(cw6=M6,pw6=SJ1,cw6){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:LM6,message:X});this[pw6]=!0,this.data=Y}static isInstance(Y){return M6.hasMarker(Y,wM6)}},AM6=`vercel.ai.error.${MM6}`,kJ1=Symbol.for(AM6),y2=class extends(iw6=M6,nw6=kJ1,iw6){constructor({text:Y,cause:X}){super({name:MM6,message:`JSON parsing failed: Text: ${Y}.
|
|
1188
|
+
`})}}}DQ1=[Gs({organizationCreation:{afterCreate:async(Y)=>{await XN6(Y.organization.id,Y.member.userId)}},ac:tx,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:JN6,resourceNameValidation:(Y)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Y)}}},roles:{user:zQ1,admin:BQ1,owner:UQ1},sendInvitationEmail:HN6}),Es({loginPage:"/login",oidcConfig:{scopes:KN6,metadata:{scopes_supported:KN6},loginPage:"/login"}}),Ps({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(Y)=>{if(Y.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=Y.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),$s({defaultRole:"user",adminRoles:["admin","owner"]}),js(),Bs({jwt:{expirationTime:"5m"}}),ZM0(U9.ssoConfig?GN6(U9.ssoConfig):void 0),...U9.magicLinkConfig&&U9.emailProviders&&U9.emailProviders.length>0?[Rs(bK6(U9.magicLinkConfig,U9.emailProviders))]:[]],OQ1=hY0(),NQ1=fK6(OQ1),SG=Wo({baseURL:t5(),database:NQ1,emailAndPassword:{enabled:!0},...U9,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:DQ1,databaseHooks:{user:{create:{after:async(Y)=>{if(BM.autoCreateOrganizationOnSignup===!1)return;let X=Y.name?Y.name.split(" ")[0]:Y.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${X} ${VQ1()}`,K=FQ1(G);try{await SG.api.createOrganization({body:{name:G,slug:K,userId:Y.id}});return}catch(W){if(!(W instanceof Error&&("body"in W)&&W.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",W);return}}}}}}}})});async function FN6(){console.log("\uD83D\uDD10 Running Better Auth migrations...");try{let{toBeAdded:Y,toBeCreated:X,runMigrations:Q}=await CL(SG.options);if(!Y.length&&!X.length){console.log("\u2705 Better Auth schema is up to date (no migrations needed)");return}console.log("\uD83D\uDCCB Better Auth will create/update the following tables:");for(let J of[...X,...Y])console.log(` - ${J.table}`);await Q(),console.log("\u2705 Better Auth migrations completed successfully")}catch(Y){console.warn("\u26A0\uFE0F Better Auth migration failed (tables may be created on first use):",Y)}}var VN6=S(()=>{xV0();sD()});var zN6={};o6(zN6,{runSeed:()=>dp,runKyselyMigrations:()=>qN6,migrateToLatest:()=>LQ1,migrateDown:()=>wQ1});import{Migrator as $N6}from"kysely";async function qN6(Y){let X=new $N6({db:Y,provider:{getMigrations:()=>Promise.resolve(UR)}}),{error:Q,results:J}=await X.migrateToLatest();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" executed successfully`);else if(G.status==="Error")console.error(`\u274C Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q}async function LQ1(Y){let{keepOpen:X=!1,database:Q,skipBetterAuth:J=!1,seed:G}=Y??{};if(!J&&!Q)await FN6();let K=Q??O$(),W=async()=>{if(!X&&!Q)console.log("\uD83D\uDD12 Closing database connection..."),await hK6(K).catch((Z)=>{console.warn("Warning: Error closing database:",Z)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await qN6(K.db),console.log("\uD83C\uDF89 All Kysely migrations completed successfully");let Z;if(G)Z=await dp(K.db,G);return await W(),{seedResult:Z}}catch(Z){throw await W(),Z}}async function wQ1(){let Y=O$(),X=new $N6({db:Y.db,provider:{getMigrations:()=>Promise.resolve(UR)}}),{error:Q,results:J}=await X.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var BN6=S(()=>{lp();oH0();VN6();kT()});var j3;var L2=S(()=>{j3=class extends Error{res;status;constructor(Y=500,X){super(X?.message,{cause:X?.cause});this.res=X?.res,this.status=Y}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var UN6,MQ1,AQ1=(Y,X)=>{if(!Y)return{};let Q=new Headers(Y.headers);if(X){let J=Q.get("connection");if(J){let G=J.split(",").map((W)=>W.trim()),K=G.filter((W)=>!MQ1.test(W));if(K.length>0)throw new j3(400,{message:`Invalid Connection header value: ${K.join(", ")}`});G.forEach((W)=>{Q.delete(W)})}}return UN6.forEach((J)=>{Q.delete(J)}),{method:Y.method,body:Y.body,duplex:Y.body?"half":void 0,headers:Q,signal:Y.signal}},TQ1=(Y)=>{if(!Y.headers||Array.isArray(Y.headers)||Y.headers instanceof Headers)return Y;let X=new Headers;for(let[Q,J]of Object.entries(Y.headers))if(J==null)X.delete(Q);else X.set(Q,J);return Y.headers=X,Y},DN6=async(Y,X)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...K}=X instanceof Request?{raw:X}:X??{},W=new Request(Y,{...AQ1(Q,G),...TQ1(K)});W.headers.delete("accept-encoding");let Z=await(J||fetch)(W),H=new Headers(Z.headers);if(UN6.forEach((F)=>{H.delete(F)}),H.has("content-encoding"))H.delete("content-encoding"),H.delete("content-length");return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:H})};var ON6=S(()=>{L2();UN6=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],MQ1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});var NN6=(Y)=>(X)=>{let Q=new URL(X.req.raw.url),J=new URL(Y);return J.pathname=Q.pathname,J.search=Q.search,DN6(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};var LN6=S(()=>{ON6()});import{resolve as w2,dirname as PQ1,join as EQ1,extname as CQ1}from"path";function jQ1(Y,X){let Q=w2(X),J=w2(Y);return J===Q||J.startsWith(Q+"/")}function SQ1({requestPath:Y,clientDir:X}){let Q=Y.startsWith("/")?Y.slice(1):Y,J=w2(X,Q);if(!jQ1(J,X))return null;return J}function wN6(Y,X="../client"){let Q=new URL(Y),J=PQ1(Q.pathname);return w2(J,X)}function MN6(Y={}){let{env:X="production",devServerUrl:Q=IQ1,clientDir:J=RQ1,isServerPath:G=()=>!1}=Y;if(X==="development"){let K=NN6(Q);return async function(Z){let H=new URL(Z.url);if(G(H.pathname))return null;let F={req:{raw:Z,url:Z.url}};return K(F)}}return async function(W){if(W.method!=="GET")return null;let Z=new URL(W.url),H;try{H=decodeURIComponent(Z.pathname)}catch{return null}if(G(H))return null;let F=SQ1({requestPath:H,clientDir:J});if(!F)return null;let V=EQ1(F,"index.html"),$=w2(J,"index.html"),q=W.headers.get("accept"),D=q?.includes("text/html")||q?.includes("*/*")&&["",".html"].includes(CQ1(F))?[V,$]:[];for(let O of[F,...D])try{let L=Bun.file(O);if(await L.exists())return new Response(L)}catch{}return null}}var IQ1="http://localhost:4000",RQ1="./dist/client";var AN6=S(()=>{LN6()});function PN6(Y){if(!Y)return!1;try{return new URL(Y).host==="api.decocms.com"&&Y!=="https://api.decocms.com/mcp/registry"}catch{return!1}}var TN6="https://api.decocms.com/mcp/registry";var dG0=(Y,X,Q)=>{return(J,G)=>{let K=-1;return W(0);async function W(Z){if(Z<=K)throw Error("next() called multiple times");K=Z;let H,F=!1,V;if(Y[Z])V=Y[Z][0][0],J.req.routeIndex=Z;else V=Z===Y.length&&G||void 0;if(V)try{H=await V(J,()=>W(Z+1))}catch($){if($ instanceof Error&&X)J.error=$,H=await X($,J),F=!0;else throw $}else if(J.finalized===!1&&Q)H=await Q(J);if(H&&(J.finalized===!1||F))J.res=H;return J}}};var EN6=()=>{};var CN6;var IN6=S(()=>{CN6=Symbol()});async function kQ1(Y,X){let Q=await Y.formData();if(Q)return vQ1(Q,X);return{}}function vQ1(Y,X){let Q=Object.create(null);if(Y.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Q[G]=J;else _Q1(Q,G,J)}),X.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))yQ1(Q,J,G),delete Q[J]});return Q}var RN6=async(Y,X=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=X,K=(Y instanceof ex?Y.raw.headers:Y.headers).get("Content-Type");if(K?.startsWith("multipart/form-data")||K?.startsWith("application/x-www-form-urlencoded"))return kQ1(Y,{all:Q,dot:J});return{}},_Q1=(Y,X,Q)=>{if(Y[X]!==void 0)if(Array.isArray(Y[X]))Y[X].push(Q);else Y[X]=[Y[X],Q];else if(!X.endsWith("[]"))Y[X]=Q;else Y[X]=[Q]},yQ1=(Y,X,Q)=>{let J=Y,G=X.split(".");G.forEach((K,W)=>{if(W===G.length-1)J[K]=Q;else{if(!J[K]||typeof J[K]!=="object"||Array.isArray(J[K])||J[K]instanceof File)J[K]=Object.create(null);J=J[K]}})};var jN6=S(()=>{pG0()});var nG0=(Y)=>{let X=Y.split("/");if(X[0]==="")X.shift();return X},SN6=(Y)=>{let{groups:X,path:Q}=fQ1(Y),J=nG0(Q);return hQ1(J,X)},fQ1=(Y)=>{let X=[];return Y=Y.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return X.push([G,Q]),G}),{groups:X,path:Y}},hQ1=(Y,X)=>{for(let Q=X.length-1;Q>=0;Q--){let[J]=X[Q];for(let G=Y.length-1;G>=0;G--)if(Y[G].includes(J)){Y[G]=Y[G].replace(J,X[Q][1]);break}}return Y},Yu,kN6=(Y,X)=>{if(Y==="*")return"*";let Q=Y.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${Y}#${X}`;if(!Yu[J])if(Q[2])Yu[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${X})`)]:[Y,Q[1],new RegExp(`^${Q[2]}$`)];else Yu[J]=[Y,Q[1],!0];return Yu[J]}return null},tD=(Y,X)=>{try{return X(Y)}catch{return Y.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return X(Q)}catch{return Q}})}},bQ1=(Y)=>tD(Y,decodeURI),iG0=(Y)=>{let X=Y.url,Q=X.indexOf("/",X.indexOf(":")+4),J=Q;for(;J<X.length;J++){let G=X.charCodeAt(J);if(G===37){let K=X.indexOf("?",J),W=X.slice(Q,K===-1?void 0:K);return bQ1(W.includes("%25")?W.replace(/%25/g,"%2525"):W)}else if(G===63)break}return X.slice(Q,J)},vN6=(Y)=>{let X=iG0(Y);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},d$=(Y,X,...Q)=>{if(Q.length)X=d$(X,...Q);return`${Y?.[0]==="/"?"":"/"}${Y}${X==="/"?"":`${Y?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},Xu=(Y)=>{if(Y.charCodeAt(Y.length-1)!==63||!Y.includes(":"))return null;let X=Y.split("/"),Q=[],J="";return X.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Q.length===0&&J==="")Q.push("/");else Q.push(J);let K=G.replace("?","");J+="/"+K,Q.push(J)}else J+="/"+G}),Q.filter((G,K,W)=>W.indexOf(G)===K)},cG0=(Y)=>{if(!/[%+]/.test(Y))return Y;if(Y.indexOf("+")!==-1)Y=Y.replace(/\+/g," ");return Y.indexOf("%")!==-1?tD(Y,M2):Y},_N6=(Y,X,Q)=>{let J;if(!Q&&X&&!/[%+]/.test(X)){let W=Y.indexOf("?",8);if(W===-1)return;if(!Y.startsWith(X,W+1))W=Y.indexOf(`&${X}`,W+1);while(W!==-1){let Z=Y.charCodeAt(W+X.length+1);if(Z===61){let H=W+X.length+2,F=Y.indexOf("&",H);return cG0(Y.slice(H,F===-1?void 0:F))}else if(Z==38||isNaN(Z))return"";W=Y.indexOf(`&${X}`,W+1)}if(J=/[%+]/.test(Y),!J)return}let G={};J??=/[%+]/.test(Y);let K=Y.indexOf("?",8);while(K!==-1){let W=Y.indexOf("&",K+1),Z=Y.indexOf("=",K);if(Z>W&&W!==-1)Z=-1;let H=Y.slice(K+1,Z===-1?W===-1?void 0:W:Z);if(J)H=cG0(H);if(K=W,H==="")continue;let F;if(Z===-1)F="";else if(F=Y.slice(Z+1,W===-1?void 0:W),J)F=cG0(F);if(Q){if(!(G[H]&&Array.isArray(G[H])))G[H]=[];G[H].push(F)}else G[H]??=F}return X?G[X]:G},yN6,fN6=(Y,X)=>{return _N6(Y,X,!0)},M2;var p$=S(()=>{Yu={},yN6=_N6,M2=decodeURIComponent});var hN6=(Y)=>tD(Y,M2),ex;var pG0=S(()=>{L2();IN6();jN6();p$();ex=class{raw;#Y;#X;routeIndex=0;path;bodyCache={};constructor(Y,X="/",Q=[[]]){this.raw=Y,this.path=X,this.#X=Q,this.#Y={}}param(Y){return Y?this.#Q(Y):this.#J()}#Q(Y){let X=this.#X[0][this.routeIndex][1][Y],Q=this.#W(X);return Q&&/\%/.test(Q)?hN6(Q):Q}#J(){let Y={},X=Object.keys(this.#X[0][this.routeIndex][1]);for(let Q of X){let J=this.#W(this.#X[0][this.routeIndex][1][Q]);if(J!==void 0)Y[Q]=/\%/.test(J)?hN6(J):J}return Y}#W(Y){return this.#X[1]?this.#X[1][Y]:Y}query(Y){return yN6(this.url,Y)}queries(Y){return fN6(this.url,Y)}header(Y){if(Y)return this.raw.headers.get(Y)??void 0;let X={};return this.raw.headers.forEach((Q,J)=>{X[J]=Q}),X}async parseBody(Y){return this.bodyCache.parsedBody??=await RN6(this,Y)}#G=(Y)=>{let{bodyCache:X,raw:Q}=this,J=X[Y];if(J)return J;let G=Object.keys(X)[0];if(G)return X[G].then((K)=>{if(G==="json")K=JSON.stringify(K);return new Response(K)[Y]()});return X[Y]=Q[Y]()};json(){return this.#G("text").then((Y)=>JSON.parse(Y))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(Y,X){this.#Y[Y]=X}valid(Y){return this.#Y[Y]}get url(){return this.raw.url}get method(){return this.raw.method}get[CN6](){return this.#X}get matchedRoutes(){return this.#X[0].map(([[,Y]])=>Y)}get routePath(){return this.#X[0].map(([[,Y]])=>Y)[this.routeIndex].path}}});var Qu,xQ1=(Y,X)=>{let Q=new String(Y);return Q.isEscaped=!0,Q.callbacks=X,Q},A2=async(Y,X,Q,J,G)=>{if(typeof Y==="object"&&!(Y instanceof String)){if(!(Y instanceof Promise))Y=Y.toString();if(Y instanceof Promise)Y=await Y}let K=Y.callbacks;if(!K?.length)return Promise.resolve(Y);if(G)G[0]+=Y;else G=[Y];let W=Promise.all(K.map((Z)=>Z({phase:X,buffer:G,context:J}))).then((Z)=>Promise.all(Z.filter(Boolean).map((H)=>A2(H,X,!1,J,G))).then(()=>G[0]));if(Q)return xQ1(await W,K);else return W};var aG0=S(()=>{Qu={Stringify:1,BeforeStream:2,Stream:3}});var bN6="text/plain; charset=UTF-8",rG0=(Y,X)=>{return{"Content-Type":Y,...X}},xN6=class{#Y;#X;env={};#Q;finalized=!1;error;#J;#W;#G;#K;#Z;#F;#H;#$;#q;constructor(Y,X){if(this.#Y=Y,X)this.#W=X.executionCtx,this.env=X.env,this.#F=X.notFoundHandler,this.#q=X.path,this.#$=X.matchResult}get req(){return this.#X??=new ex(this.#Y,this.#q,this.#$),this.#X}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#H??=new Headers})}set res(Y){if(this.#G&&Y){Y=new Response(Y.body,Y);for(let[X,Q]of this.#G.headers.entries()){if(X==="content-type")continue;if(X==="set-cookie"){let J=this.#G.headers.getSetCookie();Y.headers.delete("set-cookie");for(let G of J)Y.headers.append("set-cookie",G)}else Y.headers.set(X,Q)}}this.#G=Y,this.finalized=!0}render=(...Y)=>{return this.#Z??=(X)=>this.html(X),this.#Z(...Y)};setLayout=(Y)=>this.#K=Y;getLayout=()=>this.#K;setRenderer=(Y)=>{this.#Z=Y};header=(Y,X,Q)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#H??=new Headers;if(X===void 0)J.delete(Y);else if(Q?.append)J.append(Y,X);else J.set(Y,X)};status=(Y)=>{this.#J=Y};set=(Y,X)=>{this.#Q??=new Map,this.#Q.set(Y,X)};get=(Y)=>{return this.#Q?this.#Q.get(Y):void 0};get var(){if(!this.#Q)return{};return Object.fromEntries(this.#Q)}#V(Y,X,Q){let J=this.#G?new Headers(this.#G.headers):this.#H??new Headers;if(typeof X==="object"&&"headers"in X){let K=X.headers instanceof Headers?X.headers:new Headers(X.headers);for(let[W,Z]of K)if(W.toLowerCase()==="set-cookie")J.append(W,Z);else J.set(W,Z)}if(Q)for(let[K,W]of Object.entries(Q))if(typeof W==="string")J.set(K,W);else{J.delete(K);for(let Z of W)J.append(K,Z)}let G=typeof X==="number"?X:X?.status??this.#J;return new Response(Y,{status:G,headers:J})}newResponse=(...Y)=>this.#V(...Y);body=(Y,X,Q)=>this.#V(Y,X,Q);text=(Y,X,Q)=>{return!this.#H&&!this.#J&&!X&&!Q&&!this.finalized?new Response(Y):this.#V(Y,X,rG0(bN6,Q))};json=(Y,X,Q)=>{return this.#V(JSON.stringify(Y),X,rG0("application/json",Q))};html=(Y,X,Q)=>{let J=(G)=>this.#V(G,X,rG0("text/html; charset=UTF-8",Q));return typeof Y==="object"?A2(Y,Qu.Stringify,!1,{}).then(J):J(Y)};redirect=(Y,X)=>{let Q=String(Y);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,X??302)};notFound=()=>{return this.#F??=()=>new Response,this.#F(this)}};var Ju=S(()=>{pG0();aG0()});var H8="ALL",uN6="all",gN6,Gu="Can not add a route since the matcher is already built.",Wu;var c$=S(()=>{gN6=["get","post","put","delete","options","patch"],Wu=class extends Error{}});var mN6="__COMPOSED_HANDLER";var lN6=()=>{};var uQ1=(Y)=>{return Y.text("404 Not Found",404)},dN6=(Y,X)=>{if("getResponse"in Y){let Q=Y.getResponse();return X.newResponse(Q.body,Q)}return console.error(Y),X.text("Internal Server Error",500)},pN6=class Y{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Y="/";routes=[];constructor(X={}){[...gN6,uN6].forEach((K)=>{this[K]=(W,...Z)=>{if(typeof W==="string")this.#Y=W;else this.#J(K,this.#Y,W);return Z.forEach((H)=>{this.#J(K,this.#Y,H)}),this}}),this.on=(K,W,...Z)=>{for(let H of[W].flat()){this.#Y=H;for(let F of[K].flat())Z.map((V)=>{this.#J(F.toUpperCase(),this.#Y,V)})}return this},this.use=(K,...W)=>{if(typeof K==="string")this.#Y=K;else this.#Y="*",W.unshift(K);return W.forEach((Z)=>{this.#J(H8,this.#Y,Z)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??iG0:vN6}#X(){let X=new Y({router:this.router,getPath:this.getPath});return X.errorHandler=this.errorHandler,X.#Q=this.#Q,X.routes=this.routes,X}#Q=uQ1;errorHandler=dN6;route(X,Q){let J=this.basePath(X);return Q.routes.map((G)=>{let K;if(Q.errorHandler===dN6)K=G.handler;else K=async(W,Z)=>(await dG0([],Q.errorHandler)(W,()=>G.handler(W,Z))).res,K[mN6]=G.handler;J.#J(G.method,G.path,K)}),this}basePath(X){let Q=this.#X();return Q._basePath=d$(this._basePath,X),Q}onError=(X)=>{return this.errorHandler=X,this};notFound=(X)=>{return this.#Q=X,this};mount(X,Q,J){let G,K;if(J)if(typeof J==="function")K=J;else if(K=J.optionHandler,J.replaceRequest===!1)G=(H)=>H;else G=J.replaceRequest;let W=K?(H)=>{let F=K(H);return Array.isArray(F)?F:[F]}:(H)=>{let F=void 0;try{F=H.executionCtx}catch{}return[H.env,F]};G||=(()=>{let H=d$(this._basePath,X),F=H==="/"?0:H.length;return(V)=>{let $=new URL(V.url);return $.pathname=$.pathname.slice(F)||"/",new Request($,V)}})();let Z=async(H,F)=>{let V=await Q(G(H.req.raw),...W(H));if(V)return V;await F()};return this.#J(H8,d$(X,"*"),Z),this}#J(X,Q,J){X=X.toUpperCase(),Q=d$(this._basePath,Q);let G={basePath:this._basePath,path:Q,method:X,handler:J};this.router.add(X,Q,[J,G]),this.routes.push(G)}#W(X,Q){if(X instanceof Error)return this.errorHandler(X,Q);throw X}#G(X,Q,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(X,Q,J,"GET")))();let K=this.getPath(X,{env:J}),W=this.router.match(G,K),Z=new xN6(X,{path:K,matchResult:W,env:J,executionCtx:Q,notFoundHandler:this.#Q});if(W[0].length===1){let F;try{F=W[0][0][0][0](Z,async()=>{Z.res=await this.#Q(Z)})}catch(V){return this.#W(V,Z)}return F instanceof Promise?F.then((V)=>V||(Z.finalized?Z.res:this.#Q(Z))).catch((V)=>this.#W(V,Z)):F??this.#Q(Z)}let H=dG0(W[0],this.errorHandler,this.#Q);return(async()=>{try{let F=await H(Z);if(!F.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return F.res}catch(F){return this.#W(F,Z)}})()}fetch=(X,...Q)=>{return this.#G(X,Q[1],Q[0],X.method)};request=(X,Q,J,G)=>{if(X instanceof Request)return this.fetch(Q?new Request(X,Q):X,J,G);return X=X.toString(),this.fetch(new Request(/^https?:\/\//.test(X)?X:`http://localhost${d$("/",X)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var cN6=S(()=>{EN6();Ju();c$();lN6();p$()});function Zu(Y,X){let Q=this.buildAllMatchers(),J=(G,K)=>{let W=Q[G]||Q[H8],Z=W[2][K];if(Z)return Z;let H=K.match(W[0]);if(!H)return[[],T2];let F=H.indexOf("",1);return[W[1][F],H]};return this.match=J,J(Y,X)}var T2;var oG0=S(()=>{c$();T2=[]});function mQ1(Y,X){if(Y.length===1)return X.length===1?Y<X?-1:1:-1;if(X.length===1)return 1;if(Y===P2||Y===E2)return 1;else if(X===P2||X===E2)return-1;if(Y===Ku)return 1;else if(X===Ku)return-1;return Y.length===X.length?Y<X?-1:1:X.length-Y.length}var Ku="[^/]+",P2=".*",E2="(?:|/.*)",n$,gQ1,nN6=class Y{#Y;#X;#Q=Object.create(null);insert(X,Q,J,G,K){if(X.length===0){if(this.#Y!==void 0)throw n$;if(K)return;this.#Y=Q;return}let[W,...Z]=X,H=W==="*"?Z.length===0?["","",P2]:["","",Ku]:W==="/*"?["","",E2]:W.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),F;if(H){let V=H[1],$=H[2]||Ku;if(V&&H[2]){if($===".*")throw n$;if($=$.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test($))throw n$}if(F=this.#Q[$],!F){if(Object.keys(this.#Q).some((q)=>q!==P2&&q!==E2))throw n$;if(K)return;if(F=this.#Q[$]=new Y,V!=="")F.#X=G.varIndex++}if(!K&&V!=="")J.push([V,F.#X])}else if(F=this.#Q[W],!F){if(Object.keys(this.#Q).some((V)=>V.length>1&&V!==P2&&V!==E2))throw n$;if(K)return;F=this.#Q[W]=new Y}F.insert(Z,Q,J,G,K)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(mQ1).map((J)=>{let G=this.#Q[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:gQ1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#Y==="number")Q.unshift(`#${this.#Y}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var sG0=S(()=>{n$=Symbol(),gQ1=new Set(".\\+*[^]$()")});var iN6=class{#Y={varIndex:0};#X=new nN6;insert(Y,X,Q){let J=[],G=[];for(let W=0;;){let Z=!1;if(Y=Y.replace(/\{[^}]+\}/g,(H)=>{let F=`@\\${W}`;return G[W]=[F,H],W++,Z=!0,F}),!Z)break}let K=Y.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let W=G.length-1;W>=0;W--){let[Z]=G[W];for(let H=K.length-1;H>=0;H--)if(K[H].indexOf(Z)!==-1){K[H]=K[H].replace(Z,G[W][1]);break}}return this.#X.insert(K,X,J,this.#Y,Q),J}buildRegExp(){let Y=this.#X.buildRegExpStr();if(Y==="")return[/^$/,[],[]];let X=0,Q=[],J=[];return Y=Y.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,K,W)=>{if(K!==void 0)return Q[++X]=Number(K),"$()";if(W!==void 0)return J[Number(W)]=++X,"";return""}),[new RegExp(`^${Y}`),Q,J]}};var aN6=S(()=>{sG0()});function oN6(Y){return rN6[Y]??=new RegExp(Y==="*"?"":`^${Y.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function dQ1(){rN6=Object.create(null)}function pQ1(Y){let X=new iN6,Q=[];if(Y.length===0)return lQ1;let J=Y.map((F)=>[!/\*|\/:/.test(F[0]),...F]).sort(([F,V],[$,q])=>F?1:$?-1:V.length-q.length),G=Object.create(null);for(let F=0,V=-1,$=J.length;F<$;F++){let[q,B,D]=J[F];if(q)G[B]=[D.map(([L])=>[L,Object.create(null)]),T2];else V++;let O;try{O=X.insert(B,V,q)}catch(L){throw L===n$?new Wu(B):L}if(q)continue;Q[V]=D.map(([L,w])=>{let I=Object.create(null);w-=1;for(;w>=0;w--){let[T,P]=O[w];I[T]=P}return[L,I]})}let[K,W,Z]=X.buildRegExp();for(let F=0,V=Q.length;F<V;F++)for(let $=0,q=Q[F].length;$<q;$++){let B=Q[F][$]?.[1];if(!B)continue;let D=Object.keys(B);for(let O=0,L=D.length;O<L;O++)B[D[O]]=Z[B[D[O]]]}let H=[];for(let F in W)H[F]=Q[W[F]];return[K,H,G]}function eD(Y,X){if(!Y)return;for(let Q of Object.keys(Y).sort((J,G)=>G.length-J.length))if(oN6(Q).test(X))return[...Y[Q]];return}var lQ1,rN6,Hu=class{name="RegExpRouter";#Y;#X;constructor(){this.#Y={[H8]:Object.create(null)},this.#X={[H8]:Object.create(null)}}add(Y,X,Q){let J=this.#Y,G=this.#X;if(!J||!G)throw Error(Gu);if(!J[Y])[J,G].forEach((Z)=>{Z[Y]=Object.create(null),Object.keys(Z[H8]).forEach((H)=>{Z[Y][H]=[...Z[H8][H]]})});if(X==="/*")X="*";let K=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let Z=oN6(X);if(Y===H8)Object.keys(J).forEach((H)=>{J[H][X]||=eD(J[H],X)||eD(J[H8],X)||[]});else J[Y][X]||=eD(J[Y],X)||eD(J[H8],X)||[];Object.keys(J).forEach((H)=>{if(Y===H8||Y===H)Object.keys(J[H]).forEach((F)=>{Z.test(F)&&J[H][F].push([Q,K])})}),Object.keys(G).forEach((H)=>{if(Y===H8||Y===H)Object.keys(G[H]).forEach((F)=>Z.test(F)&&G[H][F].push([Q,K]))});return}let W=Xu(X)||[X];for(let Z=0,H=W.length;Z<H;Z++){let F=W[Z];Object.keys(G).forEach((V)=>{if(Y===H8||Y===V)G[V][F]||=[...eD(J[V],F)||eD(J[H8],F)||[]],G[V][F].push([Q,K-H+Z+1])})}}match=Zu;buildAllMatchers(){let Y=Object.create(null);return Object.keys(this.#X).concat(Object.keys(this.#Y)).forEach((X)=>{Y[X]||=this.#Q(X)}),this.#Y=this.#X=void 0,dQ1(),Y}#Q(Y){let X=[],Q=Y===H8;if([this.#Y,this.#X].forEach((J)=>{let G=J[Y]?Object.keys(J[Y]).map((K)=>[K,J[Y][K]]):[];if(G.length!==0)Q||=!0,X.push(...G);else if(Y!==H8)X.push(...Object.keys(J[H8]).map((K)=>[K,J[H8][K]]))}),!Q)return null;else return pQ1(X)}};var tG0=S(()=>{c$();p$();oG0();sG0();aN6();lQ1=[/^$/,[],Object.create(null)],rN6=Object.create(null)});var cQ1=class{name="PreparedRegExpRouter";#Y;#X;constructor(Y,X){this.#Y=Y,this.#X=X}#Q(Y,X){let Q=this.#Y[Y];Q[1].forEach((J)=>J&&J.push(X)),Object.values(Q[2]).forEach((J)=>J[0].push(X))}#J(Y,X,Q,J,G){let K=this.#Y[Y];if(!G)K[2][X][0].push([Q,{}]);else J.forEach((W)=>{if(typeof W==="number")K[1][W].push([Q,G]);else K[2][W||X][0].push([Q,G])})}add(Y,X,Q){if(!this.#Y[Y]){let G=this.#Y[H8],K={};for(let W in G[2])K[W]=[G[2][W][0].slice(),T2];this.#Y[Y]=[G[0],G[1].map((W)=>Array.isArray(W)?W.slice():0),K]}if(X==="/*"||X==="*"){let G=[Q,{}];if(Y===H8)for(let K in this.#Y)this.#Q(K,G);else this.#Q(Y,G);return}let J=this.#X[X];if(!J)throw Error(`Path ${X} is not registered`);for(let[G,K]of J)if(Y===H8)for(let W in this.#Y)this.#J(W,X,Q,G,K);else this.#J(Y,X,Q,G,K)}buildAllMatchers(){return this.#Y}match=Zu};var sN6=S(()=>{c$();oG0();tG0()});var tN6=S(()=>{tG0();sN6()});var eG0=class{name="SmartRouter";#Y=[];#X=[];constructor(Y){this.#Y=Y.routers}add(Y,X,Q){if(!this.#X)throw Error(Gu);this.#X.push([Y,X,Q])}match(Y,X){if(!this.#X)throw Error("Fatal error");let Q=this.#Y,J=this.#X,G=Q.length,K=0,W;for(;K<G;K++){let Z=Q[K];try{for(let H=0,F=J.length;H<F;H++)Z.add(...J[H]);W=Z.match(Y,X)}catch(H){if(H instanceof Wu)continue;throw H}this.match=Z.match.bind(Z),this.#Y=[Z],this.#X=void 0;break}if(K===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,W}get activeRouter(){if(this.#X||this.#Y.length!==1)throw Error("No active router has been determined yet.");return this.#Y[0]}};var eN6=S(()=>{c$()});var YL6=S(()=>{eN6()});var C2,XL6=class Y{#Y;#X;#Q;#J=0;#W=C2;constructor(X,Q,J){if(this.#X=J||Object.create(null),this.#Y=[],X&&Q){let G=Object.create(null);G[X]={handler:Q,possibleKeys:[],score:0},this.#Y=[G]}this.#Q=[]}insert(X,Q,J){this.#J=++this.#J;let G=this,K=SN6(Q),W=[];for(let Z=0,H=K.length;Z<H;Z++){let F=K[Z],V=K[Z+1],$=kN6(F,V),q=Array.isArray($)?$[0]:F;if(q in G.#X){if(G=G.#X[q],$)W.push($[1]);continue}if(G.#X[q]=new Y,$)G.#Q.push($),W.push($[1]);G=G.#X[q]}return G.#Y.push({[X]:{handler:J,possibleKeys:W.filter((Z,H,F)=>F.indexOf(Z)===H),score:this.#J}}),G}#G(X,Q,J,G){let K=[];for(let W=0,Z=X.#Y.length;W<Z;W++){let H=X.#Y[W],F=H[Q]||H[H8],V={};if(F!==void 0){if(F.params=Object.create(null),K.push(F),J!==C2||G&&G!==C2)for(let $=0,q=F.possibleKeys.length;$<q;$++){let B=F.possibleKeys[$],D=V[F.score];F.params[B]=G?.[B]&&!D?G[B]:J[B]??G?.[B],V[F.score]=!0}}}return K}search(X,Q){let J=[];this.#W=C2;let K=[this],W=nG0(Q),Z=[];for(let H=0,F=W.length;H<F;H++){let V=W[H],$=H===F-1,q=[];for(let B=0,D=K.length;B<D;B++){let O=K[B],L=O.#X[V];if(L)if(L.#W=O.#W,$){if(L.#X["*"])J.push(...this.#G(L.#X["*"],X,O.#W));J.push(...this.#G(L,X,O.#W))}else q.push(L);for(let w=0,I=O.#Q.length;w<I;w++){let T=O.#Q[w],P=O.#W===C2?{}:{...O.#W};if(T==="*"){let f=O.#X["*"];if(f)J.push(...this.#G(f,X,O.#W)),f.#W=P,q.push(f);continue}let[A,R,j]=T;if(!V&&!(j instanceof RegExp))continue;let k=O.#X[A],y=W.slice(H).join("/");if(j instanceof RegExp){let f=j.exec(y);if(f){if(P[R]=f[0],J.push(...this.#G(k,X,O.#W,P)),Object.keys(k.#X).length){k.#W=P;let h=f[0].match(/\//)?.length??0;(Z[h]||=[]).push(k)}continue}}if(j===!0||j.test(V))if(P[R]=V,$){if(J.push(...this.#G(k,X,P,O.#W)),k.#X["*"])J.push(...this.#G(k.#X["*"],X,P,O.#W))}else k.#W=P,q.push(k)}}K=q.concat(Z.shift()??[])}if(J.length>1)J.sort((H,F)=>{return H.score-F.score});return[J.map(({handler:H,params:F})=>[H,F])]}};var QL6=S(()=>{c$();p$();C2=Object.create(null)});var Y70=class{name="TrieRouter";#Y;constructor(){this.#Y=new XL6}add(Y,X,Q){let J=Xu(X);if(J){for(let G=0,K=J.length;G<K;G++)this.#Y.insert(Y,J[G],Q);return}this.#Y.insert(Y,X,Q)}match(Y,X){return this.#Y.search(Y,X)}};var JL6=S(()=>{p$();QL6()});var GL6=S(()=>{JL6()});var D9;var WL6=S(()=>{cN6();tN6();YL6();GL6();D9=class extends pN6{constructor(Y={}){super(Y);this.router=Y.router??new eG0({routers:[new Hu,new Y70]})}}});var kG=S(()=>{WL6()});var nQ1,iQ1,X70=(Y,X)=>{if(X&&Y.indexOf(X)===-1)return{};let Q=Y.trim().split(";"),J={};for(let G of Q){G=G.trim();let K=G.indexOf("=");if(K===-1)continue;let W=G.substring(0,K).trim();if(X&&X!==W||!nQ1.test(W))continue;let Z=G.substring(K+1).trim();if(Z.startsWith('"')&&Z.endsWith('"'))Z=Z.slice(1,-1);if(iQ1.test(Z)){if(J[W]=Z.indexOf("%")!==-1?tD(Z,M2):Z,X)break}}return J};var ZL6=S(()=>{p$();nQ1=/^[\w!#$%&'*.^`|~+-]+$/,iQ1=/^[ !#-:<-[\]-~]*$/});var KL6=(Y,X,Q)=>{let J=Y.req.raw.headers.get("Cookie");if(typeof X==="string"){if(!J)return;let K=X;if(Q==="secure")K="__Secure-"+X;else if(Q==="host")K="__Host-"+X;return X70(J,K)[K]}if(!J)return{};return X70(J)};var HL6=S(()=>{ZL6()});var FL6=(Y)=>{let Q={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...Y},J=((K)=>{if(typeof K==="string")if(K==="*")return()=>K;else return(W)=>K===W?W:null;else if(typeof K==="function")return K;else return(W)=>K.includes(W)?W:null})(Q.origin),G=((K)=>{if(typeof K==="function")return K;else if(Array.isArray(K))return()=>K;else return()=>[]})(Q.allowMethods);return async function(W,Z){function H(V,$){W.res.headers.set(V,$)}let F=await J(W.req.header("origin")||"",W);if(F)H("Access-Control-Allow-Origin",F);if(Q.credentials)H("Access-Control-Allow-Credentials","true");if(Q.exposeHeaders?.length)H("Access-Control-Expose-Headers",Q.exposeHeaders.join(","));if(W.req.method==="OPTIONS"){if(Q.origin!=="*")H("Vary","Origin");if(Q.maxAge!=null)H("Access-Control-Max-Age",Q.maxAge.toString());let V=await G(W.req.header("origin")||"",W);if(V.length)H("Access-Control-Allow-Methods",V.join(","));let $=Q.allowHeaders;if(!$?.length){let q=W.req.header("Access-Control-Request-Headers");if(q)$=q.split(/\s*,\s*/)}if($?.length)H("Access-Control-Allow-Headers",$.join(",")),W.res.headers.append("Vary","Access-Control-Request-Headers");return W.res.headers.delete("Content-Length"),W.res.headers.delete("Content-Type"),new Response(null,{headers:W.res.headers,status:204,statusText:"No Content"})}if(await Z(),Q.origin!=="*")W.header("Vary","Origin",{append:!0})}};var VL6=()=>{};function aQ1(){let{process:Y,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Y!==void 0?"NO_COLOR"in Y?.env:!1)}async function $L6(){let{navigator:Y}=globalThis,X="cloudflare:workers";return!(Y!==void 0&&Y.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!aQ1())}var qL6=()=>{};async function zL6(Y,X,Q,J,G=0,K){let W=X==="<--"?`${X} ${Q} ${J}`:`${X} ${Q} ${J} ${await sQ1(G)} ${K}`;Y(W)}var rQ1=(Y)=>{let[X,Q]=[",","."];return Y.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Q)},oQ1=(Y)=>{let X=Date.now()-Y;return rQ1([X<1000?X+"ms":Math.round(X/1000)+"s"])},sQ1=async(Y)=>{if(await $L6())switch(Y/100|0){case 5:return`\x1B[31m${Y}\x1B[0m`;case 4:return`\x1B[33m${Y}\x1B[0m`;case 3:return`\x1B[36m${Y}\x1B[0m`;case 2:return`\x1B[32m${Y}\x1B[0m`}return`${Y}`},BL6=(Y=console.log)=>{return async function(Q,J){let{method:G,url:K}=Q.req,W=K.slice(K.indexOf("/",8));await zL6(Y,"<--",G,W);let Z=Date.now();await J(),await zL6(Y,"-->",G,W,Q.res.status,oQ1(Z))}};var UL6=S(()=>{qL6()});var DL6=()=>{try{return performance.now()}catch{}return Date.now()},Q70=(Y)=>{let X={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...Y};return async function(J,G){let K=[],W=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:K,timers:W}),X.total)YO(J,"total",X.totalDescription);if(await G(),X.total)i$(J,"total");if(X.autoEnd)W.forEach((H,F)=>i$(J,F));if(typeof X.enabled==="function"?X.enabled(J):X.enabled){J.res.headers.append("Server-Timing",K.join(","));let H=typeof X.crossOrigin==="function"?X.crossOrigin(J):X.crossOrigin;if(H)J.res.headers.append("Timing-Allow-Origin",typeof H==="string"?H:"*")}}},OL6=(Y,X,Q,J,G)=>{let K=Y.get("metric");if(!K){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Q==="number"){let W=Q.toFixed(G||1),Z=J?`${X};dur=${W};desc="${J}"`:`${X};dur=${W}`;K.headers.push(Z)}else{let W=Q?`${X};desc="${Q}"`:`${X}`;K.headers.push(W)}},YO=(Y,X,Q)=>{let J=Y.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(X,{description:Q,start:DL6()})},i$=(Y,X,Q)=>{let J=Y.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(X);if(!G){console.warn(`Timer "${X}" does not exist!`);return}let{description:K,start:W}=G,Z=DL6()-W;OL6(Y,X,Z,K,Q),J.timers.delete(X)};var NL6=S(()=>{Ju()});var LL6=S(()=>{NL6()});import{randomBytes as tQ1}from"crypto";function wL6(){if(I2)return I2;let Y=process.env.MESH_JWT_SECRET??U9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)I2=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),I2=new Uint8Array(tQ1(32));return I2}async function ML6(Y,X="5m"){let Q=wL6();return await new VQ(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(X).sign(Q)}async function AL6(Y){try{let X=wL6(),{payload:Q}=await U8(Y,X);return Q}catch{return}}var I2=null;var J70=S(()=>{nQ();sD()});class G70{db;constructor(Y){this.db=Y}async create(Y,X,Q){let J=B9("vir"),G=new Date().toISOString();if(await this.db.insertInto("connections").values({id:J,organization_id:Y,created_by:X,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${J}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,tools:null,bindings:null,status:Q.status??"active",created_at:G,updated_at:G}).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((W)=>({id:B9("agg"),parent_connection_id:J,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,created_at:G}))).execute();let K=await this.findById(J);if(!K)throw Error(`Failed to create virtual MCP with id: ${J}`);return K}async findById(Y,X){if(Y&&oZ(Y)){let Q=Y.match(/^decopilot_(.+)$/),J;if(X)J=X;else if(Q&&Q[1])J=Q[1];else throw Error(`Invalid Decopilot ID format: ${Y}. Expected decopilot_{orgId} or provide organizationId`);let G=await this.db.selectFrom("connections").selectAll().where("organization_id","=",J).where("status","!=","inactive").where("status","!=","error").execute();return{...hP(J),connections:G.map((K)=>({connection_id:K.id,selected_tools:null,selected_resources:null,selected_prompts:null}))}}if(!Y){if(!X)throw Error("organizationId is required when id is null (Decopilot agent)");let Q=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).where("status","!=","inactive").where("status","!=","error").execute();return{...hP(X),connections:Q.map((J)=>({connection_id:J.id,selected_tools:null,selected_resources:null,selected_prompts:null}))}}return this.findByIdInternal(this.db,Y)}async findByIdInternal(Y,X){let Q=await Y.selectFrom("connections").selectAll().where("id","=",X).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let J=await Y.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",X).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(Y){let X=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute(),Q=X.map((K)=>K.id);if(Q.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).execute(),G=new Map;for(let K of J){let W=G.get(K.parent_connection_id)??[];W.push(K),G.set(K.parent_connection_id,W)}return X.map((K)=>this.deserializeVirtualMCPEntity(K,G.get(K.id)??[]))}async listByConnectionId(Y,X){let J=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",X).execute()).map((H)=>H.parent_connection_id);if(J.length===0)return[];let G=await this.db.selectFrom("connections").selectAll().where("id","in",J).where("organization_id","=",Y).where("connection_type","=","VIRTUAL").execute();if(G.length===0)return[];let K=G.map((H)=>H.id),W=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",K).execute(),Z=new Map;for(let H of W){let F=Z.get(H.parent_connection_id)??[];F.push(H),Z.set(H.parent_connection_id,F)}return G.map((H)=>this.deserializeVirtualMCPEntity(H,Z.get(H.id)??[]))}async update(Y,X,Q){let J=new Date().toISOString(),G={updated_at:J};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(Q.metadata!==void 0)G.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(await this.db.updateTable("connections").set(G).where("id","=",Y).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((W)=>({id:B9("agg"),parent_connection_id:Y,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,created_at:J}))).execute()}let K=await this.findById(Y);if(!K)throw Error("Virtual MCP not found after update");return K}async delete(Y){await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",Y).execute(),await this.db.deleteFrom("connections").where("id","=",Y).where("connection_type","=","VIRTUAL").execute()}deserializeVirtualMCPEntity(Y,X){let Q=Y.created_at instanceof Date?Y.created_at.toISOString():Y.created_at,J=Y.updated_at instanceof Date?Y.updated_at.toISOString():Y.updated_at,G=Y.status==="active"?"active":"inactive";return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,icon:Y.icon,status:G,created_at:Q,updated_at:J,created_by:Y.created_by,updated_by:void 0,metadata:this.parseJson(Y.metadata),connections:X.map((K)=>({connection_id:K.child_connection_id,selected_tools:this.parseJson(K.selected_tools),selected_resources:this.parseJson(K.selected_resources),selected_prompts:this.parseJson(K.selected_prompts)}))}}parseJson(Y){if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y}}var TL6=S(()=>{tZ();j5()});class W70{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(Y){if(Y===null||Y===void 0)return Y;if(typeof Y==="string")return this.redactString(Y);if(Array.isArray(Y))return Y.map((X)=>this.redact(X));if(typeof Y==="object"){let X={};for(let[Q,J]of Object.entries(Y)){let G=this.redactString(Q);X[G]=this.redact(J)}return X}return Y}redactString(Y){let X=Y;for(let Q of this.patterns)X=X.replace(Q.regex,`[REDACTED:${Q.type}]`);return X}}import{sql as Fu}from"kysely";class Z70{db;redactor;databaseType;constructor(Y,X="sqlite"){this.db=Y;this.redactor=new W70,this.databaseType=X}jsonExtract(Y,X){if(this.databaseType==="postgres")return Fu`(${Fu.ref(Y)}::jsonb)->>${X}`;let Q=`$.${X}`;return Fu`json_extract(${Fu.ref(Y)}, ${Q})`}async log(Y){await this.logBatch([Y])}async logBatch(Y){if(Y.length===0)return;let X=Y.map((Q)=>({...Q,input:this.redactor.redact(Q.input),output:this.redactor.redact(Q.output)}));await this.db.transaction().execute(async(Q)=>{await Q.insertInto("monitoring_logs").values(X.map((J)=>this.toDbRow(J))).execute()})}async query(Y){let X=this.db.selectFrom("monitoring_logs").selectAll(),Q=this.db.selectFrom("monitoring_logs").select((Z)=>Z.fn.count("id").as("count"));if(Y.organizationId)X=X.where("organization_id","=",Y.organizationId),Q=Q.where("organization_id","=",Y.organizationId);if(Y.connectionId)X=X.where("connection_id","=",Y.connectionId),Q=Q.where("connection_id","=",Y.connectionId);if(Y.virtualMcpId)X=X.where("virtual_mcp_id","=",Y.virtualMcpId),Q=Q.where("virtual_mcp_id","=",Y.virtualMcpId);if(Y.toolName)X=X.where("tool_name","=",Y.toolName),Q=Q.where("tool_name","=",Y.toolName);if(Y.isError!==void 0)X=X.where("is_error","=",Y.isError?1:0),Q=Q.where("is_error","=",Y.isError?1:0);if(Y.startDate)X=X.where("timestamp",">=",Y.startDate.toISOString()),Q=Q.where("timestamp",">=",Y.startDate.toISOString());if(Y.endDate)X=X.where("timestamp","<=",Y.endDate.toISOString()),Q=Q.where("timestamp","<=",Y.endDate.toISOString());if(Y.propertyFilters){let{properties:Z,propertyKeys:H,propertyPatterns:F}=Y.propertyFilters;if(Z)for(let[V,$]of Object.entries(Z)){let q=this.jsonExtract("properties",V);X=X.where(q,"=",$),Q=Q.where(q,"=",$)}if(H&&H.length>0)for(let V of H){let $=this.jsonExtract("properties",V);X=X.where($,"is not",null),Q=Q.where($,"is not",null)}if(F)for(let[V,$]of Object.entries(F)){let q=this.jsonExtract("properties",V),B=this.databaseType==="postgres"?"ilike":"like";X=X.where(q,B,$),Q=Q.where(q,B,$)}}if(X=X.orderBy("timestamp","desc"),Y.limit)X=X.limit(Y.limit);if(Y.offset)X=X.offset(Y.offset);let[J,G]=await Promise.all([X.execute(),Q.executeTakeFirst()]),K=Number(G?.count||0);return{logs:J.map((Z)=>this.fromDbRow(Z)),total:K}}async getStats(Y){let X=this.db.selectFrom("monitoring_logs").where("organization_id","=",Y.organizationId);if(Y.startDate)X=X.where("timestamp",">=",Y.startDate.toISOString());if(Y.endDate)X=X.where("timestamp","<=",Y.endDate.toISOString());let Q=await X.select([(W)=>W.fn.count("id").as("total_count"),(W)=>W.fn.sum(W.ref("is_error")).as("error_count"),(W)=>W.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Q?.total_count||0),G=Number(Q?.error_count||0),K=Number(Q?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:K}}toDbRow(Y){return{id:Y.id||B9("log"),organization_id:Y.organizationId,connection_id:Y.connectionId,connection_title:Y.connectionTitle,tool_name:Y.toolName,input:JSON.stringify(Y.input),output:JSON.stringify(Y.output),is_error:Y.isError?1:0,error_message:Y.errorMessage||null,duration_ms:Y.durationMs,timestamp:Y.timestamp instanceof Date?Y.timestamp.toISOString():Y.timestamp,user_id:Y.userId||null,request_id:Y.requestId,user_agent:Y.userAgent||null,virtual_mcp_id:Y.virtualMcpId||null,properties:Y.properties?JSON.stringify(Y.properties):null}}fromDbRow(Y){let X=typeof Y.input==="string"?JSON.parse(Y.input):Y.input,Q=typeof Y.output==="string"?JSON.parse(Y.output):Y.output,J=typeof Y.timestamp==="string"?new Date(Y.timestamp):Y.timestamp,G=Y.properties?typeof Y.properties==="string"?JSON.parse(Y.properties):Y.properties:null;return{id:Y.id,organizationId:Y.organization_id,connectionId:Y.connection_id,connectionTitle:Y.connection_title,toolName:Y.tool_name,input:X,output:Q,isError:Y.is_error===1,errorMessage:Y.error_message,durationMs:Y.duration_ms,timestamp:J,userId:Y.user_id,requestId:Y.request_id,userAgent:Y.user_agent,virtualMcpId:Y.virtual_mcp_id,properties:G}}}var PL6=S(()=>{tZ()});class K70{db;constructor(Y){this.db=Y}async get(Y){let X=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",Y).executeTakeFirst();if(!X)return null;return{organizationId:X.organizationId,sidebar_items:X.sidebar_items?typeof X.sidebar_items==="string"?JSON.parse(X.sidebar_items):X.sidebar_items:null,enabled_plugins:X.enabled_plugins?typeof X.enabled_plugins==="string"?JSON.parse(X.enabled_plugins):X.enabled_plugins:null,createdAt:X.createdAt,updatedAt:X.updatedAt}}async upsert(Y,X){let Q=new Date().toISOString(),J=X?.sidebar_items?JSON.stringify(X.sidebar_items):null,G=X?.enabled_plugins?JSON.stringify(X.enabled_plugins):null;await this.db.insertInto("organization_settings").values({organizationId:Y,sidebar_items:J,enabled_plugins:G,createdAt:Q,updatedAt:Q}).onConflict((W)=>W.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,enabled_plugins:G?G:void 0,updatedAt:Q})).execute();let K=await this.get(Y);if(!K)return{organizationId:Y,sidebar_items:X?.sidebar_items??null,enabled_plugins:X?.enabled_plugins??null,createdAt:Q,updatedAt:Q};return K}}class H70{db;constructor(Y){this.db=Y}async findById(Y,X){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",Y).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",Y).where("m2.userId","=",X))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}var EL6="mcp.mesh";var CL6,F70,S3;var Vu=S(()=>{CL6=class CL6 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};F70=class F70 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};S3=class S3{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,X,Q,J,G,K="self",W){this.userId=X;this.toolName=Q;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 CL6("Authentication required. Please provide a valid OAuth token or API key.")}let X=Y.length>0?Y:this.toolName?[this.toolName]:[];if(X.length===0)throw new F70("No resources specified for access check");for(let Q of X)if(await this.checkResource(Q)){this.grant();return}throw new F70(`Access denied to: ${X.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 X={};if(this.connectionId)X[this.connectionId]=[Y];return this.boundAuth.hasPermission(X)}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 Q=Y[EL6]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}});async function IL6(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 X=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)X.set("client_secret",Y.clientSecret);if(Y.scope)X.set("scope",Y.scope);let Q=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:X.toString()});if(!Q.ok){let G=await Q.text();console.error(`[TokenRefresh] Failed to refresh token: ${Q.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${Q.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Q.status}`}}}let J=await Q.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(X){return console.error("[TokenRefresh] Error refreshing token:",X),{success:!1,error:X instanceof Error?X.message:"Token refresh failed"}}}async function R2(Y,X,Q){let J=Y.id,G=YG0(Y.configuration_state,Y.configuration_scopes),K=X.auth.user?.id??X.auth.apiKey?.userId??(Q?Y.created_by:void 0),[W,Z]=K?await ML6({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??X.baseUrl,connectionId:J,organizationId:X.organization?.id},permissions:G}).then((B)=>[B,null]).catch((B)=>[null,B]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=X.auth.user?.connectionId,F={...H?{"x-caller-id":H}:{},...X.metadata.wellKnownForwardableHeaders??{},"x-request-id":X.metadata.requestId},V=null,$=new WK(X.db,X.vault),q=await $.get(J);if(q){let B=!!q.refreshToken&&!!q.tokenEndpoint;if($.isExpired(q,B?300000:0))if(B){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let O=await IL6(q);if(O.success&&O.accessToken)await $.upsert({connectionId:J,accessToken:O.accessToken,refreshToken:O.refreshToken??q.refreshToken,scope:O.scope??q.scope,expiresAt:O.expiresIn?new Date(Date.now()+O.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),V=O.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await $.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${O.error}`)}else await $.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else V=q.accessToken}if(!V&&Y.connection_token)V=Y.connection_token;if(V)F.Authorization=`Bearer ${V}`;if(W)F["x-mesh-token"]=W;return F}var V70=S(()=>{XG0();J70();ox()});function RL6(Y){let X=new nP({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),Q=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return X.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${Q}]\x1B[0m`)}),X}var jL6=S(()=>{D50()});async function SL6(Y,X,Q=!1){let J=Y.id;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 G=Y.connection_headers;if(!v$(G))throw Error("STDIO connection missing parameters");let K=RL6({id:J,name:Y.title,command:G.command,args:G.args,env:G.envVars,cwd:G.cwd});return X.getOrCreateClient(K,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let G=await R2(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new A3(new URL(Y.connection_url),{requestInit:{headers:G}});return X.getOrCreateClient(W,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let G=await R2(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new f$(new URL(Y.connection_url),{requestInit:{headers:G}});return X.getOrCreateClient(W,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var kL6=S(()=>{sZ();Ix();fP();V70();jL6()});class vL6{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,X){return this.getOrCreatePromise().then(Y,X)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function a$(Y){return new vL6(Y)}async function eQ1(Y,X){let Q=await Promise.all(Y.map(async(J)=>{try{let G=await X.createMCPProxy(J);return[J.id,G]}catch(G){return console.warn(`[aggregator] Failed to create proxy for connection ${J.id}:`,G),null}}));return new Map(Q.filter((J)=>!!J))}async function _L6(Y){let X=[];for(let[,Q]of Y)X.push(Q.close().catch(()=>{}));await Promise.all(X)}var XO;var $70=S(()=>{CD();XO=class XO extends R5{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,X){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=X;this._selectionMap=new Map;for(let Q of Y.virtualMcp.connections)this._selectionMap.set(Q.connection_id,Q);this._connections=new Map;for(let Q of Y.connections)this._connections.set(Q.id,Q);this._clients=a$(()=>eQ1(this.options.connections,this.ctx)),this._cachedTools=a$(()=>this.loadCache("tools")),this._cachedResources=a$(()=>this.loadCache("resources")),this._cachedPrompts=a$(()=>this.loadCache("prompts"))}async loadCache(Y){let X=await this._clients,Q=await Promise.all(Array.from(X.entries()).map(async([K,W])=>{try{let Z=Y==="tools"?await W.listTools().then((F)=>F.tools):Y==="resources"?await W.listResources().then((F)=>F.resources):await W.listPrompts().then((F)=>F.prompts),H=this._selectionMap.get(K);if(H?.[`selected_${Y}`]?.length){let F=new Set(H[`selected_${Y}`]);Z=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 Q){if(!K)continue;let{connectionId:W,data:Z}=K,F=this._connections.get(W)?.title??"";for(let V of Z){let $=V.name;if(G.has($))continue;let q={...V,_meta:{connectionId:W,connectionTitle:F,...V?._meta}};J.push(q),G.set($,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let[X,Q]=await Promise.all([this._cachedTools,this._clients]),J=X.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};let G=Q.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 listResources(){return{resources:(await this._cachedResources).data}}async readResource(Y){let[X,Q]=await Promise.all([this._cachedResources,this._clients]),J=X.mappings.get(Y.uri);if(!J)throw Error(`Resource not found: ${Y.uri}`);let G=Q.get(J);if(!G)throw Error(`Connection not found for resource: ${Y.uri}`);return await G.readResource(Y)}async listPrompts(){return{prompts:(await this._cachedPrompts).data}}async getPrompt(Y){let[X,Q]=await Promise.all([this._cachedPrompts,this._clients]),J=X.mappings.get(Y.name);if(!J)throw Error(`Prompt not found: ${Y.name}`);let G=Q.get(J);if(!G)throw Error(`Connection not found for prompt: ${Y.name}`);return await G.getPrompt(Y)}async callStreamableTool(Y,X){let[Q,J]=await Promise.all([this._cachedTools,this._clients]),G=Q.mappings.get(Y);if(G){let W=J.get(G);if(W)return W.callStreamableTool(Y,X)}let K=await this.callTool({name:Y,arguments:X});return new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}})}async[Symbol.asyncDispose](){let Y=await this._clients;if(Y)await _L6(Y)}async close(){let Y=await this._clients;if(Y)await _L6(Y);await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions}}});var yL6,YJ1,fL6,XJ1,j2;var q70=S(()=>{n0();g$();$70();yL6=z.object({query:z.string().min(1).describe("Search query to find tools by name or description"),limit:z.number().default(10).describe("Maximum number of results to return")}),YJ1=z.toJSONSchema(yL6),fL6=z.object({tools:z.array(z.string()).min(1).describe("Array of tool names to get detailed schemas for")}),XJ1=z.toJSONSchema(fL6);j2=class j2 extends XO{constructor(Y,X){super(Y,X)}getSearchTool(Y){return{name:"GATEWAY_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 GATEWAY_DESCRIBE_TOOLS for detailed schemas. Total tools: ${Y}.`,inputSchema:YJ1}}getDescribeTool(){return{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:XJ1}}async handleSearch(Y){let X=yL6.safeParse(Y);if(!X.success)return C3({error:X.error.flatten()});let Q=await this._cachedTools,J=XK(Q.data),G=hx(X.data.query,J,X.data.limit);return oP({query:X.data.query,results:G.map((K)=>({name:K.name,description:K.description,connection:K._meta.connectionTitle})),totalAvailable:J.length})}async handleDescribe(Y){let X=fL6.safeParse(Y);if(!X.success)return C3({error:X.error.flatten()});let Q=await this._cachedTools,J=XK(Q.data),G=bx(X.data.tools,J);return oP({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,X=XK(Y.data);return{tools:[this.getSearchTool(X.length),this.getDescribeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_SEARCH_TOOLS")return this.handleSearch(Y.arguments??{});if(Y.name==="GATEWAY_DESCRIBE_TOOLS")return this.handleDescribe(Y.arguments??{});return{content:[{type:"text",text:`Unknown tool: ${Y.name}. Available: GATEWAY_SEARCH_TOOLS, GATEWAY_DESCRIBE_TOOLS`}],isError:!0}}async routeToolCall(Y){return XO.prototype.callTool.call(this,Y)}}});var hL6,QJ1,z70;var bL6=S(()=>{n0();g$();q70();hL6=z.object({code:z.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:z.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),QJ1=z.toJSONSchema(hL6);z70=class z70 extends j2{constructor(Y,X){super(Y,X)}getRunCodeTool(){return{name:"GATEWAY_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 GATEWAY_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.',inputSchema:QJ1}}async handleRunCode(Y){let X=hL6.safeParse(Y);if(!X.success)return C3({error:X.error.flatten()});let Q=await this._cachedTools,G={tools:XK(Q.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await xx(X.data.code,G,X.data.timeoutMs);if(K.error)return C3(K);return oP(K)}async listTools(){return{tools:[...(await super.listTools()).tools,this.getRunCodeTool()]}}async callTool(Y){if(Y.name==="GATEWAY_RUN_CODE")return this.handleRunCode(Y.arguments??{});return super.callTool(Y)}}});function uL6(Y){let X=Y.slice().sort().join(","),Q=xL6.get(X);if(!Q){let J=z.object({name:(Y.length>0?z.enum(Y):z.string()).describe("The name of the tool to execute"),arguments:z.record(z.string(),z.unknown()).default({}).describe("Arguments to pass to the tool")});Q={schema:J,jsonSchema:z.toJSONSchema(J)},xL6.set(X,Q)}return Q}var xL6,B70;var gL6=S(()=>{n0();g$();q70();xL6=new Map;B70=class B70 extends j2{constructor(Y,X){super(Y,X)}async getCallTool(){let Y=await this._cachedTools,Q=XK(Y.data).map((G)=>G.name),{jsonSchema:J}=uL6(Q);return{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:J}}async handleCallTool(Y){let X=await this._cachedTools,Q=XK(X.data),J=Q.map((F)=>F.name),{schema:G}=uL6(J),K=G.safeParse(Y);if(!K.success)return C3({error:K.error.flatten()});let{name:W,arguments:Z}=K.data;if(!new Map(Q.map((F)=>[F.name,F])).has(W))return{content:[{type:"text",text:`Tool not found: ${W}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return this.routeToolCall({name:W,arguments:Z})}async listTools(){let Y=await super.listTools(),X=await this.getCallTool();return{tools:[...Y.tools,X]}}async callTool(Y){if(Y.name==="GATEWAY_CALL_TOOL")return this.handleCallTool(Y.arguments??{});return super.callTool(Y)}}});function U70(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function JJ1(Y,X){if(Y.connection_type!=="VIRTUAL")return!1;if(!X||oZ(X))return!1;return Y.id===X}async function mL6(Y,X){let Q=Y.id,J=await X.storage.virtualMcps.findById(Q);if(!J)throw Error(`Virtual MCP not found: ${Q}`);return S2(J,X,"passthrough")}async function S2(Y,X,Q){let G=Y.connections.map((H)=>H.connection_id).map((H)=>X.storage.connections.findById(H)),Z={connections:(await Promise.all(G)).filter((H)=>H!==null&&H.status==="active"&&!JJ1(H,Y.id)),virtualMcp:Y};return Q==="smart_tool_selection"?new B70(Z,X):Q==="code_execution"?new z70(Z,X):new XO(Z,X)}var $u=S(()=>{j5();bL6();$70();gL6()});async function lL6(Y,X,Q=!1){if(Y.connection_type==="VIRTUAL")return mL6(Y,X);return SL6(Y,X,Q)}var dL6=S(()=>{kL6();$u()});async function qu(Y,X){let Q=Y.get("meshContext");try{let J=Y.req.header("x-org-id"),G=Y.req.header("x-org-slug"),K=J?J:G?await Q.db.selectFrom("organization").select("id").where("slug","=",G).executeTakeFirst().then((q)=>q?.id):null,W=await Q.storage.virtualMcps.findById(X??null,K??void 0);if(!W)return Y.json({error:"Agent not found"},404);if(K&&W.organization_id!==K)return Y.json({error:"Agent not found"},404);if(W.status!=="active")return Y.json({error:`Agent is inactive: ${W.id??"Decopilot"}`},503);Q.connectionId=W.id??void 0;let Z=await Q.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",W.organization_id).executeTakeFirst();if(Z)Q.organization={id:Z.id,slug:Z.slug,name:Z.name};let H=U70(Y.req.query("mode")),F=await S2(W,Q,H),V=uP(F,{name:`mcp-virtual-mcp-${W.title??"Decopilot"}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:W.metadata?.instructions??void 0}),$=new h$({enableJsonResponse:Y.req.header("Accept")?.includes("application/json")??!1});return await V.connect($),await $.handleRequest(Y.req.raw)}catch(J){let G=J;return console.error("[virtual-mcp] Error handling virtual MCP request:",G),Y.json({error:"Internal server error",message:G.message},500)}}var D70,pL6;var O70=S(()=>{j5();kx();kG();$u();D70=new D9;D70.all("/gateway/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return qu(Y,X)});D70.all("/virtual-mcp/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return qu(Y,X)});pL6=D70});async function cL6(Y,X){return(await X.storage.connections.findById(Y))?.connection_url??null}function GJ1(Y){let X=Y.toLowerCase();return X.includes("resource_metadata=")||X.includes("invalid_token")||X.includes("oauth")}async function nL6(Y,X={}){try{let Q=await fetch(Y,{method:"POST",headers:{...X,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Q.status===401){let J=Q.headers.get("WWW-Authenticate");if(J){if(GJ1(J))return J}if(await WJ1(Y))return'Bearer realm="mcp"'}return null}catch{return null}}async function WJ1(Y){try{let X=new URL(Y),Q=new URL("/.well-known/oauth-authorization-server",X.origin),J=await fetch(Q.toString(),{method:"GET",headers:{Accept:"application/json"}});if(J.ok){let G=await J.json();if(G.authorization_endpoint||G.token_endpoint||G.issuer)return!0}return!1}catch{return!1}}async function Bu(Y){let Q=new URL(Y).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=new URL(Y);J.pathname=`${Q}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!N70.includes(G.status))return G;let K=new URL(Y);if(K.pathname=`/.well-known/oauth-protected-resource${Q}`,G=await fetch(K.toString(),{method:"GET",headers:{Accept:"application/json"}}),!N70.includes(G.status))return G;let W=new URL(Y);return W.pathname="/.well-known/oauth-protected-resource",G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function ZJ1(Y,X){let Q=await cL6(Y,X);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Bu(Q);if(G.ok){let K=await G.json();if(K.authorization_servers?.[0])return K.authorization_servers[0]}}catch{}return J}async function iL6(Y){let X=Y.get("meshContext");if(!X)X=await k3.create(Y.req.raw),Y.set("meshContext",X);return X}async function aL6({error:Y,reqUrl:X,connectionId:Q,connectionUrl:J,headers:G}){let K=Y.message?.toLowerCase()??"";if(!(Y.status===401||Y.code===401||Y.message?.includes("401")||K.includes("unauthorized")||K.includes("invalid_token")||K.includes("api key required")||K.includes("api-key required")))return null;if(Boolean(await nL6(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${X.origin}/mcp/${Q}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}async function L70(Y){let Q=new URL(Y).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=Q!==""&&Q!=="/",G=[];if(J){let W=new URL(Y);W.pathname=`/.well-known/oauth-authorization-server${Q}`,G.push(W);let Z=new URL(Y);Z.pathname=`/.well-known/openid-configuration${Q}`,G.push(Z);let H=new URL(Y);H.pathname=`${Q}/.well-known/openid-configuration`,G.push(H)}else{let W=new URL(Y);W.pathname="/.well-known/oauth-authorization-server",G.push(W);let Z=new URL(Y);Z.pathname="/.well-known/openid-configuration",G.push(Z)}let K=null;for(let W of G){if(K=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),K.ok)return K;if(K.status!==404&&K.status!==401)return K}return K}var zu,N70,rL6=(Y)=>{if(!(Y.hostname==="localhost"||Y.hostname==="127.0.0.1"))Y.protocol="https:";return Y},oL6=async(Y)=>{let X=Y.req.param("connectionId"),Q=await iL6(Y),J=await cL6(X,Q);if(!J)return Y.json({error:"Connection not found"},404);let G=rL6(new URL(Y.req.url)),K=`${G.origin}/mcp/${X}`,W=`${G.origin}/oauth-proxy/${X}`;try{let Z=await Bu(J);if(!Z.ok&&N70.includes(Z.status)){if(await nL6(J))return new Response(JSON.stringify({resource:K,authorization_servers:[W],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:{"Content-Type":"application/json"}})}if(!Z.ok)return new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:{"Content-Type":"application/json"}});let H=await Z.json();if("issuer"in H&&!("resource"in H)&&(("authorization_endpoint"in H)||("token_endpoint"in H))){let $={resource:K,authorization_servers:[W],bearer_methods_supported:["header"],scopes_supported:"scopes_supported"in H&&Array.isArray(H.scopes_supported)&&H.scopes_supported.length>0?H.scopes_supported:["*"]};return new Response(JSON.stringify($),{status:200,headers:{"Content-Type":"application/json"}})}let V={...H,resource:K,authorization_servers:[W]};return new Response(JSON.stringify(V),{status:Z.status,statusText:Z.statusText,headers:{"Content-Type":"application/json"}})}catch(Z){let H=Z;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",H),Y.json({error:"Failed to proxy OAuth metadata",message:H.message},502)}},sL6;var w70=S(()=>{kG();Uu();zu=new D9,N70=[404,401,406];zu.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Y)=>oL6(Y));zu.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Y)=>oL6(Y));zu.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=await iL6(Y),J=await ZJ1(X,Q);if(!J)return Y.json({error:"Connection not found or no auth server"},404);try{let G=await L70(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let K=await G.json(),Z=`${rL6(new URL(Y.req.url)).origin}/oauth-proxy/${X}`,H={...K,authorization_endpoint:K.authorization_endpoint?`${Z}/authorize`:void 0,token_endpoint:K.token_endpoint?`${Z}/token`:void 0,registration_endpoint:K.registration_endpoint?`${Z}/register`:void 0};return new Response(JSON.stringify(H),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let K=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",K),Y.json({error:"Failed to proxy auth server metadata",message:K.message},502)}});sL6=zu});function KJ1(Y){if(!Y.isError)return;let X=Y.content;if(!Array.isArray(X))return;for(let Q of X)if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text;return}function HJ1(Y){if(!Y)return;let X=Y._meta;if(!X||typeof X!=="object"||Array.isArray(X))return;let Q=X.properties;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J={};for(let[G,K]of Object.entries(Q))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function FJ1(Y,X){if(!Y&&!X)return;if(!Y)return X;if(!X)return Y;return{...X,...Y}}function eL6(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let X=Y,Q=X.structuredContent;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return X}return{value:Y}}async function VJ1(Y,X){let Q=Y.body;if(!Q)return{text:"",truncated:!1};let J=Q.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>X){K=!0;let V=X-(W-H.byteLength);if(V>0)Z.push(G.decode(H.slice(0,V),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}async function k2(Y){let{ctx:X,enabled:Q}=Y,J=Y.organizationId??X.organization?.id;if(!Q||!J)return;if(oZ(Y.connectionId))return;let G=HJ1(Y.request.params.arguments),K=FJ1(X.metadata.properties,G);await X.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:X.auth.user?.id||X.auth.apiKey?.userId||null,requestId:X.metadata.requestId,userAgent:X.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function Yw6(Y){let{ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),V=Date.now()-H;return await k2({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:eL6(F),isError:Boolean(F.isError),errorMessage:KJ1(F),durationMs:V}),F}catch(F){let V=F,$=Date.now()-H;throw await k2({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}function Xw6(Y){let{ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let F=await Z(),V=X.organization?.id;if(Q&&V){let $=F.clone();(async()=>{try{let{text:q,truncated:B}=await VJ1($,tL6),D=Date.now()-H,O=$.headers.get("content-type")??"",L=q;if(O.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=F.status>=400,I=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof I==="string"&&I?I:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${F.status} ${F.statusText}`.trim():B?`Response body truncated to ${tL6} bytes`:void 0;await k2({ctx:X,enabled:Q,organizationId:V,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:eL6(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let B=Date.now()-H;await k2({ctx:X,enabled:Q,organizationId:V,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:B})}})()}return F}catch(F){let V=F,$=Date.now()-H;throw await k2({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}var tL6=262144;var Qw6=S(()=>{j5()});function $J1(Y,X,Q){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await Q();return H.find((V)=>V.name===K)?._meta};return await new S3(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,X,W).check(K),await G()}catch(K){return{content:[{type:"text",text:`Authorization failed: ${K.message}`}],isError:!0}}}}function qJ1(Y,X,Q){return async(J,G)=>{try{let K=J.params.name,W=async()=>{let{tools:H}=await Q();return H.find((V)=>V.name===K)?._meta};return await new S3(Y.authInstance,Y.auth.user?.id??Y.auth.apiKey?.userId,K,Y.boundAuth,Y.auth.user?.role,X,W).check(K),await G()}catch(K){return new Response(JSON.stringify({error:`Authorization failed: ${K.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}function r$(Y){return{client:{callTool:Y.callTool.bind(Y),listTools:Y.listTools.bind(Y)},callStreamableTool:Y.callStreamableTool.bind(Y)}}async function Jw6(Y,X,{superUser:Q}){let J=typeof Y==="string"?await X.storage.connections.findById(Y,X.organization?.id):Y;if(!J)throw Error("Connection not found");let G=J?.id;if(X.organization&&J.organization_id!==X.organization.id)throw Error("Connection does not belong to the active organization");if(X.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let K=await lL6(J,X,Q),W=async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((L)=>({name:L.name,description:L.description,inputSchema:L.inputSchema,outputSchema:L.outputSchema,annotations:L.annotations,_meta:L._meta}))};return await K.listTools()},Z=X.connectionId&&X.connectionId!==G?X.connectionId:void 0,H={enabled:cT0().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:Z,ctx:X},F=async(L)=>{return iP(Yw6(H),Q?async(I,T)=>await T():$J1(X,G,W))(L,async()=>{let I=Date.now(),T={...L.params};if(T.arguments&&"_meta"in T.arguments){let{_meta:P,...A}=T.arguments;T.arguments=A}return await X.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":L.params.name,"request.id":X.metadata.requestId}},async(P)=>{try{let A=await K.callTool(T,void 0,{timeout:M70}),R=Date.now()-I;return X.meter.createHistogram("connection.proxy.duration").record(R,{"connection.id":G,"tool.name":L.params.name,status:"success"}),X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":L.params.name,status:"success"}),P.end(),A}catch(A){let R=A,j=Date.now()-I;throw X.meter.createHistogram("connection.proxy.duration").record(j,{"connection.id":G,"tool.name":L.params.name,status:"error"}),X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":L.params.name,error:R.message}),P.recordException(R),P.end(),A}})})};return{callTool:(L)=>F({method:"tools/call",params:L}),listTools:W,listResources:async()=>{try{return await K.listResources()}catch(L){if(L instanceof $6&&L.code===L6.MethodNotFound)return{resources:[]};throw L}},readResource:async(L)=>K.readResource(L),listResourceTemplates:async()=>{try{return await K.listResourceTemplates()}catch(L){if(L instanceof $6&&L.code===L6.MethodNotFound)return{resourceTemplates:[]};throw L}},listPrompts:async()=>{try{return await K.listPrompts()}catch(L){if(L instanceof $6&&L.code===L6.MethodNotFound)return{prompts:[]};throw L}},getPrompt:async(L)=>K.getPrompt(L),getServerCapabilities:()=>K.getServerCapabilities(),getInstructions:()=>K.getInstructions(),close:()=>K.close(),callStreamableTool:async(L,w)=>{if(J.connection_type==="VIRTUAL"){let A=await F({method:"tools/call",params:{name:L,arguments:w}});return new Response(JSON.stringify(A),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let I=J.connection_url,T={method:"tools/call",params:{name:L,arguments:w}};return iP(Xw6(H),Q?async(A,R)=>await R():qJ1(X,G,W))(T,async()=>{let A=await R2(J,X,Q),R=J.connection_headers;if(R&&"headers"in R)Object.assign(A,R.headers);let j=new URL(I);return j.pathname=j.pathname.replace(/\/$/,"")+`/call-tool/${T.params.name}`,await X.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":T.params.name,"request.id":X.metadata.requestId}},async(k)=>{let y=Date.now();try{let f=await fetch(j.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(T.params.arguments),headers:{...A,"Content-Type":"application/json"}}),h=Date.now()-y;return X.meter.createHistogram("connection.proxy.streamable.duration").record(h,{"connection.id":G,"tool.name":T.params.name,status:f.ok?"success":"error"}),X.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":T.params.name,status:f.ok?"success":"error"}),k.end(),f}catch(f){let h=f,s=Date.now()-y;throw X.meter.createHistogram("connection.proxy.streamable.duration").record(s,{"connection.id":G,"tool.name":T.params.name,status:"error"}),X.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":T.params.name,error:h.message}),k.recordException(h),k.end(),f}})})},[Symbol.asyncDispose]:()=>K.close()}}async function Gw6(Y,X){return Jw6(Y,X,{superUser:!1})}async function Ww6(Y,X){return Jw6(Y,X,{superUser:!0})}var Du,M70=300000,Zw6=(Y,X)=>{if(Y.message.includes("not found"))return X.json({error:Y.message},404);if(Y.message.includes("does not belong to the active organization"))return X.json({error:"Connection not found"},404);if(Y.message.includes("inactive"))return X.json({error:Y.message},503);return X.json({error:"Internal server error",message:Y.message},500)},Kw6;var o$=S(()=>{Ev();dL6();V70();j5();kx();OX();kG();Vu();O70();w70();Qw6();Du=new D9;Du.all("/",async(Y)=>{return qu(Y,void 0)});Du.all("/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=Y.get("meshContext");try{try{let J=await Q.createMCPProxy(X),G=uP(J,{name:"mcp-mesh",version:"1.0.0"}),K=new h$({enableJsonResponse:Y.req.raw.headers.get("Accept")?.includes("application/json")??!1});await G.connect(K);try{return await K.handleRequest(Y.req.raw)}finally{try{await K.close?.()}catch{}}}catch(J){let G=await Q.storage.connections.findById(X,Q.organization?.id);if(G?.connection_url){let K=await aL6({error:J,reqUrl:new URL(Y.req.raw.url),connectionId:X,connectionUrl:G.connection_url,headers:{}});if(K)return K}throw J}}catch(J){return Zw6(J,Y)}});Du.all("/:connectionId/call-tool/:toolName",async(Y)=>{let X=Y.req.param("connectionId"),Q=Y.req.param("toolName"),J=Y.get("meshContext");try{let K=await(await J.createMCPProxy(X)).callTool({name:Q,arguments:await Y.req.json()});if(K instanceof Response)return K;if(K.isError)return new Response(JSON.stringify(K.content),{headers:{"Content-Type":"application/json"},status:500});return new Response(JSON.stringify(K.structuredContent??K.content),{headers:{"Content-Type":"application/json"}})}catch(G){return Zw6(G,Y)}});Kw6=Du});class A70{db;constructor(Y){this.db=Y}async create(Y){let X=Y.id??B9("thrd"),Q=new Date().toISOString();if(!Y.organizationId)throw Error("organizationId is required");if(!Y.createdBy)throw Error("createdBy is required");if(!Y.title)Y.title="New Thread - "+Q;let J={id:X,organization_id:Y.organizationId,title:Y.title,description:Y.description??null,created_at:Q,updated_at:Q,created_by:Y.createdBy,updated_by:Y.updatedBy??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let X=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return X?this.threadFromDbRow(X):null}async update(Y,X){let J={updated_at:new Date().toISOString()};if(X.title!==void 0)J.title=X.title;if(X.description!==void 0)J.description=X.description;if(X.updatedBy!==void 0)J.updated_by=X.updatedBy;if(X.hidden!==void 0)J.hidden=X.hidden;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,X,Q){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(X)J=J.where("created_by","=",X);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(X)G=G.where("created_by","=",X);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let X=new Date().toISOString(),Q=Y[0]?.threadId;if(!Q)throw Error("threadId is required when creating multiple messages");let J=Y.find((K)=>K.threadId!==Q);if(J)throw Error(`All messages must target the same thread. Expected threadId "${Q}", but message "${J.id}" has threadId "${J.threadId}"`);let G=Y.map((K)=>({id:K.id,thread_id:Q,metadata:K.metadata?JSON.stringify(K.metadata):null,parts:JSON.stringify(K.parts),role:K.role,created_at:K.createdAt??X,updated_at:X}));await this.db.transaction().execute(async(K)=>{await K.insertInto("thread_messages").values(G).execute(),await K.updateTable("threads").set({updated_at:X}).where("id","=",Q).execute()})}async listMessages(Y,X){let Q=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at","asc").orderBy("id","asc"),J=this.db.selectFrom("thread_messages").select((W)=>W.fn.count("id").as("count")).where("thread_id","=",Y);if(X?.limit)Q=Q.limit(X.limit);if(X?.offset)Q=Q.offset(X.offset);let[G,K]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{messages:G.map((W)=>this.messageFromDbRow(W)),total:Number(K?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organizationId:Y.organization_id,title:Y.title,description:Y.description,createdAt:typeof Y.created_at==="string"?Y.created_at:Y.created_at.toISOString(),updatedAt:typeof Y.updated_at==="string"?Y.updated_at:Y.updated_at.toISOString(),createdBy:Y.created_by,updatedBy:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let X,Q;try{X=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),X=void 0}try{Q=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),Q=[]}return{id:Y.id,threadId:Y.thread_id,metadata:X,parts:Q,role:Y.role,createdAt:typeof Y.created_at==="string"?Y.created_at:Y.created_at.toISOString(),updatedAt:typeof Y.updated_at==="string"?Y.updated_at:Y.updated_at.toISOString()}}}var Hw6=S(()=>{tZ()});function Fw6(){let Y=new Map;function X(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;let W=new R5({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(X,{[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 Vw6=S(()=>{CD()});function zJ1(Y){if(!Y)return;try{let X=JSON.parse(Y);if(typeof X!=="object"||X===null||Array.isArray(X))return;let Q={};for(let[J,G]of Object.entries(X))if(typeof G==="string")Q[J]=G;return Object.keys(Q).length>0?Q:void 0}catch{return}}function BJ1(Y,X){for(let[Q,J]of Object.entries(X)){let G=Y[Q];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function UJ1(Y){let{auth:X,headers:Q,role:J,permissions:G,userId:K}=Y,W=X.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&mG0.includes(J))return!0;if(G)return BJ1(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:Q,body:{permission:Z}}))?.success===!0)return!0;let F={};for(let $ of Object.keys(Z))F[$]=["*"];return(await W({headers:Q,body:{permission:F}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return X.api.createOrganization({headers:Q,body:Z})},update:async(Z)=>{return X.api.updateOrganization({headers:Q,body:Z})},delete:async(Z)=>{await X.api.deleteOrganization({headers:Q,body:{organizationId:Z}})},get:async(Z)=>{return X.api.getFullOrganization({headers:Q,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return X.api.listOrganizations({headers:Q,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return X.api.addMember({headers:Q,body:Z})},removeMember:async(Z)=>{await X.api.removeMember({headers:Q,body:Z})},listMembers:async(Z)=>{return X.api.listMembers({headers:Q,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return X.api.updateMemberRole({headers:Q,body:Z})}},apiKey:{create:async(Z)=>{return X.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return X.api.listApiKeys({headers:Q})},update:async(Z)=>{return X.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await X.api.deleteApiKey({headers:Q,body:{keyId:Z}})}}}}async function DJ1(Y,X,Q){if(mG0.includes(Q))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",X).where("role","=",Q).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Q}`);return}}async function OJ1(Y,X,Q,J=qw6){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>X.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),F=H?.role,V=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,$;if(H&&F)$=await J.measure("auth_fetch_role_permissions",()=>DJ1(Q,H.organizationId,F));return{user:{id:Z,role:F},role:F,permissions:$,organization:V}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>AL6(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>X.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,F,V=W.key.userId;if(V&&Z?.id)F=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",V).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:F},role:F,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=await J.measure("auth_get_session",()=>X.api.getSession({headers:Y.headers}));if(K){let W,Z;if(K.session.activeOrganizationId){let H=await J.measure("auth_get_full_organization",()=>X.api.getFullOrganization({headers:Y.headers}).catch(()=>null));if(H)W={id:H.id,slug:H.slug,name:H.name},Z=H.members?.find((V)=>V.userId===K.user.id)?.role;else W={id:K.session.activeOrganizationId,slug:"",name:""}}return{user:{id:K.user.id,email:K.user.email,role:Z},role:Z,organization:W}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}async function zw6(Y){let G=[];try{let X=new k$(Y.encryption.key);let Q={connections:new mP(Y.db,X),organizationSettings:new K70(Y.db),monitoring:new Z70(Y.db,Y.databaseType),virtualMcps:new G70(Y.db),users:new H70(Y.db),threads:new A70(Y.db)};const J=gG(G,Fw6(),1);return async(F,V)=>{let $=V?.timings??qw6,q=F?.headers.get("x-caller-id")??void 0,B=F?await OJ1(F,Y.auth,Y.db,$):{user:void 0},D=UJ1({auth:Y.auth,headers:F?.headers??new Headers,role:B.role,permissions:B.permissions,userId:B.user?.id}),O={user:B.user};if(B.apiKeyId)O.apiKey={id:B.apiKeyId,name:"",userId:""};let L=B.organization,w=F?process.env.BASE_URL??`${new URL(F.url).origin}`:t5(),I=new S3(Y.auth,O.user?.id,void 0,D,B.role,"self"),T={timings:$,auth:O,connectionId:q,organization:L,storage:Q,vault:X,authInstance:Y.auth,boundAuth:D,access:I,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:w,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(NJ1.map((P)=>[P,F?.headers.get(P)??null]).filter(([P,A])=>A!==null)),userAgent:F?.headers.get("x-mesh-client")||F?.headers.get("User-Agent")||void 0,ipAddress:(F?.headers.get("CF-Connecting-IP")||F?.headers.get("X-Forwarded-For"))??void 0,properties:zJ1(F?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(P)=>{return await Gw6(P,T)},getOrCreateClient:J};return T}}catch(K){var W=K,Z=1}finally{var H=PW(G,W,Z);H&&await H}}var $w6,k3,qw6,NJ1;var Uu=S(()=>{J70();Ax();rJ0();TL6();PL6();Vu();o$();lG0();Hw6();Vw6();k3={set:(Y)=>{$w6=Y},create:async(Y,X)=>{return await $w6(Y,X)}},qw6={measure:async(Y,X)=>{return await X()}},NJ1=["x-hub-signature-256"]});class Bw6{db;constructor(Y){this.db=Y}async publishEvent(Y){let X=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:X,updated_at:X}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:X,updatedAt:X}}async subscribe(Y){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)X=X.where("publisher","=",Y.publisher);else X=X.where("publisher","is",null);if(Y.filter)X=X.where("filter","=",Y.filter);else X=X.where("filter","is",null);let Q=await X.executeTakeFirst();if(Q)return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,X){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",X).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,X){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(X)Q=Q.where("connection_id","=",X);return(await Q.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,X){let Q=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",X).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((Q)=>Q.or([Q("publisher","is",null),Q("publisher","=",Y.source)])).execute()).map((Q)=>({id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}))}async createDeliveries(Y,X,Q){if(X.length===0)return;let J=new Date().toISOString(),G=Q??null,K=X.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let X=new Date().toISOString(),Q;try{Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",X)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];Q=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Q).where("status","=","pending").execute()}if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let X=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:X}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,X,Q=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=Q)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:X,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),F=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:X,status:"pending",next_retry_at:F}).where("id","=",K).execute()}}}async updateEventStatus(Y){let X=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(X.length===0)return;let Q=X.every((K)=>K.status==="delivered"),J=X.some((K)=>K.status==="failed"),G=X.some((K)=>K.status==="pending"||K.status==="processing");if(Q)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,X){let Q=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",X).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,type:Q.type,source:Q.source,specversion:Q.specversion,subject:Q.subject,time:Q.time,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema,data:Q.data?JSON.parse(Q.data):null,cron:Q.cron,status:Q.status,attempts:Q.attempts,lastError:Q.last_error,nextRetryAt:Q.next_retry_at,createdAt:Q.created_at,updatedAt:Q.updated_at}}async findActiveCronEvent(Y,X,Q,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",X).where("source","=",Q).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,X,Q){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",X).where("source","=",Q).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,X){if(Y.length===0)return;let Q=new Date(Date.now()+X).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Q}).where("id","in",Y).execute()}async ackDelivery(Y,X,Q){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",X).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Q).where("event_subscriptions.organization_id","=",X))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:X,connectionId:Q,subscriptions:J}=Y,G=(w,I)=>{return`${w}::${I??""}`},K=await this.listSubscriptions(X,Q),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),F=[],V=[],$=[],q=0;for(let[w,I]of Z){let T=W.get(w);if(!T)F.push({id:crypto.randomUUID(),organization_id:X,connection_id:Q,event_type:I.eventType,publisher:I.publisher??null,filter:I.filter??null,enabled:1,created_at:H,updated_at:H});else{let P=T.filter??null,A=I.filter??null;if(P!==A)V.push({id:T.id,filter:A});else q++}}for(let[w,I]of W)if(!Z.has(w))$.push(I.id);if(F.length>0)await this.db.insertInto("event_subscriptions").values(F).execute();if(V.length>0)await Promise.all(V.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if($.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",$).execute();let B=F.length,D=V.length,O=$.length,L=await this.listSubscriptions(X,Q);return{created:B,updated:D,deleted:O,unchanged:q,subscriptions:L}}}function Uw6(Y){return new Bw6(Y)}function wX(Y,X,Q,J,G,K,W,Z){return wX.fromTZ(wX.tp(Y,X,Q,J,G,K,W),Z)}function T70(Y,X=new Date){let Q=X.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=X.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Q}`)}function LJ1(Y,X){let Q=new Date(Date.parse(Y));if(isNaN(Q))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?wX.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):wX.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),X)}function wJ1(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new v5(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new v5(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function v2(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function MJ1(Y){return v2(Y)}function AJ1(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var P70=32,_2,Lw6,Dw6=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,X){this.pattern=Y,this.timezone=X,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let X=new v5(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",X.getSeconds().toString()),Y[1]=Y[1].replace("?",X.getMinutes().toString()),Y[2]=Y[2].replace("?",X.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",X.getDate().toString())),Y[4]=Y[4].replace("?",(X.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",X.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,_2),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,X,Q,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(X===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+X+") is empty, check for trailing spaces.");if(X==="*")return G.fill(J);let W=X.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],Q,J);else X.indexOf("-")!==-1&&X.indexOf("/")!==-1?this.handleRangeWithStepping(X,Y,Q,J):X.indexOf("-")!==-1?this.handleRange(X,Y,Q,J):X.indexOf("/")!==-1?this.handleStepping(X,Y,Q,J):X!==""&&this.handleNumber(X,Y,Q,J)}throwAtIllegalCharacters(Y){for(let X=0;X<Y.length;X++)if((X===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[X]))throw TypeError("CronPattern: configuration entry "+X+" ("+Y[X]+") contains illegal characters.")}handleNumber(Y,X,Q,J){let G=this.extractNth(Y,X),K=parseInt(G[0],10)+Q;if(isNaN(K))throw TypeError("CronPattern: "+X+" is not a number: '"+Y+"'");this.setPart(X,K,G[1]||J)}setPart(Y,X,Q){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(X===7&&(X=0),X<0||X>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+X);this.setNthWeekdayOfMonth(X,Q);return}if(Y==="second"||Y==="minute"){if(X<0||X>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+X)}else if(Y==="hour"){if(X<0||X>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+X)}else if(Y==="day"){if(X<0||X>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+X)}else if(Y==="month"&&(X<0||X>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+X);this[Y][X]=Q}handleRangeWithStepping(Y,X,Q,J){let G=this.extractNth(Y,X),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,F=parseInt(W,10)+Q,V=parseInt(Z,10)+Q,$=parseInt(H,10);if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[X].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[X].length+")");if(F>V)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let q=F;q<=V;q+=$)this.setPart(X,q,G[1]||J)}extractNth(Y,X){let Q=Y,J;if(Q.includes("#")){if(X!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Q.split("#")[1],Q=Q.split("#")[0]}return[Q,J]}handleRange(Y,X,Q,J){let G=this.extractNth(Y,X),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+Q,Z=parseInt(K[1],10)+Q;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(X,H,G[1]||J)}handleStepping(Y,X,Q,J){let G=this.extractNth(Y,X),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+Q);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[X].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[X].length+")");for(let H=W;H<this[X].length;H+=Z)this.setPart(X,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let X=Y.trim().toLowerCase();return X==="@yearly"||X==="@annually"?"0 0 1 1 *":X==="@monthly"?"0 0 1 * *":X==="@weekly"?"0 0 * * 0":X==="@daily"?"0 0 * * *":X==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,X){if(typeof X!="number"&&X==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|P70;else if(X===_2)this.dayOfWeek[Y]=_2;else if(X<6&&X>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|Lw6[X-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${X}, Type: ${typeof X}`)}},Ow6,KK,v5=class Y{tz;ms;second;minute;hour;day;month;year;constructor(X,Q){if(this.tz=Q,X&&X instanceof Date)if(!isNaN(X))this.fromDate(X);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(X===void 0)this.fromDate(new Date);else if(X&&typeof X=="string")this.fromString(X);else if(X instanceof Y)this.fromCronDate(X);else throw TypeError("CronDate: Invalid type ("+typeof X+") passed to CronDate constructor")}isNthWeekdayOfMonth(X,Q,J,G){let K=new Date(Date.UTC(X,Q,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(X,Q,Z)).getUTCDay()===K&&W++;if(G&_2&&Lw6[W-1]&G)return!0;if(G&P70){let Z=new Date(Date.UTC(X,Q+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(X,Q,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(X){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes()+this.tz,this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply();else{let Q=wX.toTZ(X,this.tz);this.ms=X.getMilliseconds(),this.second=Q.s,this.minute=Q.i,this.hour=Q.h,this.day=Q.d,this.month=Q.m-1,this.year=Q.y}else this.ms=X.getMilliseconds(),this.second=X.getSeconds(),this.minute=X.getMinutes(),this.hour=X.getHours(),this.day=X.getDate(),this.month=X.getMonth(),this.year=X.getFullYear()}fromCronDate(X){this.tz=X.tz,this.year=X.year,this.month=X.month,this.day=X.day,this.hour=X.hour,this.minute=X.minute,this.second=X.second,this.ms=X.ms}apply(){if(this.month>11||this.day>Ow6[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let X=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),!0}else return!1}fromString(X){if(typeof this.tz=="number"){let Q=wX.fromTZISO(X);this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply()}else return this.fromDate(wX.fromTZISO(X,this.tz))}findNext(X,Q,J,G){let K=this[Q],W;J.lastDayOfMonth&&(this.month!==1?W=Ow6[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&Q=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[Q]+G;H<J[Q].length;H++){let F=J[Q][H];if(Q==="day"&&J.lastDayOfMonth&&H-G==W&&(F=1),Q==="day"&&!J.starDOW){let V=J.dayOfWeek[(Z+(H-G-1))%7];if(V&&V&_2)V=this.isNthWeekdayOfMonth(this.year,this.month,H-G,V)?1:0;else if(V)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${V}`);X.legacyMode&&!J.starDOM?F=F||V:F=F&&V}if(F)return this[Q]=H-G,K!==this[Q]?2:1}return 3}recurse(X,Q,J){let G=this.findNext(Q,KK[J][0],X,KK[J][2]);if(G>1){let K=J+1;for(;K<KK.length;)this[KK[K][0]]=-KK[K][2],K++;if(G===3)return this[KK[J][1]]++,this[KK[J][0]]=-KK[J][2],this.apply(),this.recurse(X,Q,0);if(this.apply())return this.recurse(X,Q,J-1)}return J+=1,J>=KK.length?this:this.year>=3000?null:this.recurse(X,Q,J)}increment(X,Q,J){return this.second+=Q.interval!==void 0&&Q.interval>1&&J?Q.interval:1,this.ms=0,this.apply(),this.recurse(X,Q,0)}getDate(X){return X||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):wX.fromTZ(wX.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},Nw6=30000,Ou,Nu=class{name;options;_states;fn;constructor(Y,X,Q){let J,G;if(v2(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(v2(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=wJ1(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Dw6("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new v5(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Dw6(Y,this.options.timezone),this.name){if(Ou.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Ou.push(this)}return G!==void 0&&MJ1(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let X=this._next(Y);return X?X.getDate(!1):null}nextRuns(Y,X){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let Q=[],J=X||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)Q.push(J);return Q}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),X=!this._states.paused,Q=this.fn!==void 0,J=!this._states.kill;return X&&Q&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let X=this._next(Y);return X?Y instanceof v5||Y instanceof Date?X.getTime()-Y.getTime():X.getTime()-new v5(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Ou.indexOf(this);Y>=0&&Ou.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let X=this.msToNext(),Q=this.nextRun(this._states.currentRun);return X==null||isNaN(X)||Q===null?this:(X>Nw6&&(X=Nw6),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),X),this._states.currentTimeout&&this.options.unref&&AJ1(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new v5(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(X){v2(this.options.catch)&&this.options.catch(X,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new v5(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let X=new Date,Q=!this._states.paused&&X.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;Q&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Q&&J&&v2(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let X=!!(Y||this._states.currentRun),Q=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,X]=this._calculatePreviousRun(Y,X),Q=!Y),Y=new v5(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new v5(Y,this.options.timezone||this.options.utcOffset);return!Q&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,X)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,X){let Q=new v5(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=Q.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Q.getTime();)J=new v5(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;X=!0}return J===null&&(J=void 0),[J,X]}};var E70=S(()=>{wX.fromTZISO=(Y,X,Q)=>wX.fromTZ(LJ1(Y,X),Q);wX.fromTZ=function(Y,X){let Q=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=T70(Y.tz,Q),G=new Date(Q.getTime()-J),K=T70(Y.tz,G);if(K-J===0)return G;{let W=new Date(Q.getTime()-K),Z=T70(Y.tz,W);if(Z-K===0)return W;if(!X&&Z-K>0)return W;if(X)throw Error("Invalid date passed to fromTZ()");return G}};wX.toTZ=function(Y,X){let Q=Y.toLocaleString("en-US",{timeZone:X}).replace(/[\u202f]/," "),J=new Date(Q);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:X}};wX.tp=(Y,X,Q,J,G,K,W)=>({y:Y,m:X,d:Q,h:J,i:G,s:K,tz:W});wX.minitz=wX;_2=31|P70,Lw6=[1,2,4,8,16],Ow6=[31,28,31,30,31,30,31,31,30,31,30,31],KK=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];Ou=[]});var Lu;var C70=S(()=>{Lu={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function ww6(){return async(Y,X)=>{try{let Q=await k3.create(),J=await Ww6(Y,Q),K=await a50.forClient(r$(J)).ON_EVENTS({events:X});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(Q){let J=Q instanceof Error?Q.message:String(Q);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}var Mw6=S(()=>{Uu();px();o$()});function Aw6(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function TJ1(Y){let X=new Map;for(let J of Y){let G=J.subscription.connectionId,K=X.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(Aw6(J.event))}else X.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[Aw6(J.event)],seenEventIds:new Set([J.event.id])})}let Q=new Map;for(let[J,G]of X)Q.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Q}class I70{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Y,X){this.storage=Y;this.notifySubscriber=ww6(),this.config={...Lu,...X}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let X=TJ1(Y),Q=new Set;for(let[J,G]of X){try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))Q.add(K.event.id)}for(let J of Q)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,X){let Q=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=X.results?.[W.id];if(H)if(H.success)Q.push(Z);else if(H.retryAfter&&H.retryAfter>0){let F=J.get(H.retryAfter)||[];F.push(Z),J.set(H.retryAfter,F)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(X.success)Q.push(Z);else if(X.retryAfter&&X.retryAfter>0){let F=J.get(X.retryAfter)||[];F.push(Z),J.set(X.retryAfter,F)}else G.push({deliveryId:Z,error:X.error||"Batch processing failed"})}if(Q.length>0)await this.storage.markDeliveriesDelivered(Q);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let F=W.get(H)||[];F.push(Z),W.set(H,F)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let Q=new Nu(Y.cron).nextRun();if(!Q){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=Q.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(X){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,X)}}}var Tw6=S(()=>{E70();C70();Mw6()});class R70{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new I70(this.storage,Y.config)}async publish(Y,X,Q){if(Q.deliverAt&&Q.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Q.cron){try{let V=new Nu(Q.cron).nextRun();if(!V)throw Error("Cron expression does not produce a next run time");J=V.toISOString()}catch(F){throw Error(`Invalid cron expression: ${F instanceof Error?F.message:String(F)}`)}let H=await this.storage.findActiveCronEvent(Y,Q.type,X,Q.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:Q.type,source:X,subject:Q.subject,time:K,data:Q.data,cron:Q.cron}),Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=Q.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map((F)=>F.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch((F)=>{console.warn("[EventBus] Notify failed (non-critical):",F)})}return W}async subscribe(Y,X){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:X.connectionId,publisher:X.publisher,eventType:X.eventType,filter:X.filter})}async unsubscribe(Y,X){return this.storage.unsubscribe(X,Y)}async listSubscriptions(Y,X){return this.storage.listSubscriptions(Y,X)}async getSubscription(Y,X){return this.storage.getSubscription(X,Y)}async getEvent(Y,X){return this.storage.getEvent(X,Y)}async cancelEvent(Y,X,Q){return this.storage.cancelEvent(X,Y,Q)}async ackEvent(Y,X,Q){return this.storage.ackDelivery(X,Y,Q)}async syncSubscriptions(Y,X){return this.storage.syncSubscriptions({organizationId:Y,...X})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}var Pw6=S(()=>{E70();Tw6()});function Ew6(...Y){return{async start(X){await Promise.all(Y.map((Q)=>Q.start(X)))},async stop(){await Promise.all(Y.map((X)=>X.stop().catch((Q)=>{console.error("[NotifyStrategy] Error stopping strategy:",Q)})))},async notify(X){await Promise.all(Y.map((Q)=>Q.notify(X).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class wu{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as PJ1}from"kysely";class j70{db;pool;listenClient=null;onNotify=null;constructor(Y,X){this.db=Y;this.pool=X}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(X)=>{if(X.channel===QO&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(X)=>{console.error("[PostgresNotify] Connection error:",X),this.cleanup()}),await this.listenClient.query(`LISTEN ${QO}`),console.log("[PostgresNotify] Started LISTEN on",QO)}catch(X){console.error("[PostgresNotify] Failed to start LISTEN:",X),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${QO}`),console.log("[PostgresNotify] Stopped LISTEN on",QO)}catch{}this.cleanup()}}async notify(Y){try{await PJ1`SELECT pg_notify(${QO}, ${Y})`.execute(this.db)}catch(X){console.warn("[PostgresNotify] Failed to send NOTIFY:",X)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var QO="mesh_events";var Cw6=()=>{};function Iw6(Y,X){let Q=Uw6(Y.db),J=X?.pollIntervalMs??Lu.pollIntervalMs,G=Y.type==="postgres"?Ew6(new wu(J),new j70(Y.db,Y.pool)):new wu(J);return new R70({storage:Q,config:X,notifyStrategy:G})}var Rw6=S(()=>{Pw6();C70();Cw6()});var jw6;var Sw6=S(()=>{jw6={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var kw6,vw6;var _w6=S(()=>{kG();sD();Sw6();kw6=new D9;kw6.get("/config",async(Y)=>{try{let X=Object.keys(U9.socialProviders??{}),Q=X.length>0,J=X.map((W)=>({name:W,icon:jw6[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:U9.emailAndPassword?.enabled??!1},magicLink:{enabled:U9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:U9.ssoConfig?{enabled:!0,providerId:U9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(X){let Q=X instanceof Error?X.message:"Failed to load auth config";return Y.json({success:!1,error:Q},500)}});vw6=kw6});function vG(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.message;return JSON.stringify(Y)}var HM6="vercel.ai.error",EJ1,yw6,fw6,M6,FM6="AI_APICallError",VM6,CJ1,hw6,bw6,t8,$M6="AI_EmptyResponseBodyError",qM6,IJ1,xw6,uw6,zM6,BM6="AI_InvalidArgumentError",UM6,RJ1,gw6,mw6,DM6,OM6="AI_InvalidPromptError",NM6,jJ1,lw6,dw6,s$,LM6="AI_InvalidResponseDataError",wM6,SJ1,pw6,cw6,WM8,MM6="AI_JSONParseError",AM6,kJ1,nw6,iw6,y2,TM6="AI_LoadAPIKeyError",PM6,vJ1,aw6,rw6,ZM8,EM6="AI_LoadSettingError",CM6,_J1,ow6,sw6,KM8,IM6="AI_NoContentGeneratedError",RM6,yJ1,tw6,ew6,HM8,jM6="AI_NoSuchModelError",SM6,fJ1,YM6,XM6,FM8,kM6="AI_TooManyEmbeddingValuesForCallError",vM6,hJ1,QM6,JM6,VM8,_M6="AI_TypeValidationError",yM6,bJ1,GM6,WM6,uQ,fM6="AI_UnsupportedFunctionalityError",hM6,xJ1,ZM6,KM6,bM6;var w1=S(()=>{EJ1=Symbol.for(HM6),M6=class Y extends(fw6=Error,yw6=EJ1,fw6){constructor({name:X,message:Q,cause:J}){super(Q);this[yw6]=!0,this.name=X,this.cause=J}static isInstance(X){return Y.hasMarker(X,HM6)}static hasMarker(X,Q){let J=Symbol.for(Q);return X!=null&&typeof X==="object"&&J in X&&typeof X[J]==="boolean"&&X[J]===!0}},VM6=`vercel.ai.error.${FM6}`,CJ1=Symbol.for(VM6),t8=class extends(bw6=M6,hw6=CJ1,bw6){constructor({message:Y,url:X,requestBodyValues:Q,statusCode:J,responseHeaders:G,responseBody:K,cause:W,isRetryable:Z=J!=null&&(J===408||J===409||J===429||J>=500),data:H}){super({name:FM6,message:Y,cause:W});this[hw6]=!0,this.url=X,this.requestBodyValues=Q,this.statusCode=J,this.responseHeaders=G,this.responseBody=K,this.isRetryable=Z,this.data=H}static isInstance(Y){return M6.hasMarker(Y,VM6)}},qM6=`vercel.ai.error.${$M6}`,IJ1=Symbol.for(qM6),zM6=class extends(uw6=M6,xw6=IJ1,uw6){constructor({message:Y="Empty response body"}={}){super({name:$M6,message:Y});this[xw6]=!0}static isInstance(Y){return M6.hasMarker(Y,qM6)}};UM6=`vercel.ai.error.${BM6}`,RJ1=Symbol.for(UM6),DM6=class extends(mw6=M6,gw6=RJ1,mw6){constructor({message:Y,cause:X,argument:Q}){super({name:BM6,message:Y,cause:X});this[gw6]=!0,this.argument=Q}static isInstance(Y){return M6.hasMarker(Y,UM6)}},NM6=`vercel.ai.error.${OM6}`,jJ1=Symbol.for(NM6),s$=class extends(dw6=M6,lw6=jJ1,dw6){constructor({prompt:Y,message:X,cause:Q}){super({name:OM6,message:`Invalid prompt: ${X}`,cause:Q});this[lw6]=!0,this.prompt=Y}static isInstance(Y){return M6.hasMarker(Y,NM6)}},wM6=`vercel.ai.error.${LM6}`,SJ1=Symbol.for(wM6),WM8=class extends(cw6=M6,pw6=SJ1,cw6){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:LM6,message:X});this[pw6]=!0,this.data=Y}static isInstance(Y){return M6.hasMarker(Y,wM6)}},AM6=`vercel.ai.error.${MM6}`,kJ1=Symbol.for(AM6),y2=class extends(iw6=M6,nw6=kJ1,iw6){constructor({text:Y,cause:X}){super({name:MM6,message:`JSON parsing failed: Text: ${Y}.
|
|
1189
1189
|
Error message: ${vG(X)}`,cause:X});this[nw6]=!0,this.text=Y}static isInstance(Y){return M6.hasMarker(Y,AM6)}},PM6=`vercel.ai.error.${TM6}`,vJ1=Symbol.for(PM6),ZM8=class extends(rw6=M6,aw6=vJ1,rw6){constructor({message:Y}){super({name:TM6,message:Y});this[aw6]=!0}static isInstance(Y){return M6.hasMarker(Y,PM6)}},CM6=`vercel.ai.error.${EM6}`,_J1=Symbol.for(CM6),KM8=class extends(sw6=M6,ow6=_J1,sw6){constructor({message:Y}){super({name:EM6,message:Y});this[ow6]=!0}static isInstance(Y){return M6.hasMarker(Y,CM6)}},RM6=`vercel.ai.error.${IM6}`,yJ1=Symbol.for(RM6),HM8=class extends(ew6=M6,tw6=yJ1,ew6){constructor({message:Y="No content generated."}={}){super({name:IM6,message:Y});this[tw6]=!0}static isInstance(Y){return M6.hasMarker(Y,RM6)}},SM6=`vercel.ai.error.${jM6}`,fJ1=Symbol.for(SM6),FM8=class extends(XM6=M6,YM6=fJ1,XM6){constructor({errorName:Y=jM6,modelId:X,modelType:Q,message:J=`No such ${Q}: ${X}`}){super({name:Y,message:J});this[YM6]=!0,this.modelId=X,this.modelType=Q}static isInstance(Y){return M6.hasMarker(Y,SM6)}},vM6=`vercel.ai.error.${kM6}`,hJ1=Symbol.for(vM6),VM8=class extends(JM6=M6,QM6=hJ1,JM6){constructor(Y){super({name:kM6,message:`Too many values for a single embedding call. The ${Y.provider} model "${Y.modelId}" can only embed up to ${Y.maxEmbeddingsPerCall} values per call, but ${Y.values.length} values were provided.`});this[QM6]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return M6.hasMarker(Y,vM6)}},yM6=`vercel.ai.error.${_M6}`,bJ1=Symbol.for(yM6),uQ=class Y extends(WM6=M6,GM6=bJ1,WM6){constructor({value:X,cause:Q}){super({name:_M6,message:`Type validation failed: Value: ${JSON.stringify(X)}.
|
|
1190
1190
|
Error message: ${vG(Q)}`,cause:Q});this[GM6]=!0,this.value=X}static isInstance(X){return M6.hasMarker(X,yM6)}static wrap({value:X,cause:Q}){return Y.isInstance(Q)&&Q.value===X?Q:new Y({value:X,cause:Q})}},hM6=`vercel.ai.error.${fM6}`,xJ1=Symbol.for(hM6),bM6=class extends(KM6=M6,ZM6=xJ1,KM6){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:fM6,message:X});this[ZM6]=!0,this.functionality=Y}static isInstance(Y){return M6.hasMarker(Y,hM6)}}});var xM6=()=>{};function e$(...Y){return Y.reduce((X,Q)=>({...X,...Q!=null?Q:{}}),{})}async function cM6(Y,X){if(Y==null)return Promise.resolve();let Q=X==null?void 0:X.abortSignal;return new Promise((J,G)=>{if(Q==null?void 0:Q.aborted){G(uM6());return}let K=setTimeout(()=>{W(),J()},Y),W=()=>{clearTimeout(K),Q==null||Q.removeEventListener("abort",Z)},Z=()=>{W(),G(uM6())};Q==null||Q.addEventListener("abort",Z)})}function uM6(){return new DOMException("Delay was aborted","AbortError")}function f2(Y){return Object.fromEntries([...Y.headers])}function JO(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),Q=gJ1(X);return Uint8Array.from(Q,(J)=>J.codePointAt(0))}function Xq(Y){let X="";for(let Q=0;Q<Y.length;Q++)X+=String.fromCodePoint(Y[Q]);return uJ1(X)}function GO(Y){if(Y==null)return"unknown error";if(typeof Y==="string")return Y;if(Y instanceof Error)return Y.message;return JSON.stringify(Y)}function HK(Y){return(Y instanceof Error||Y instanceof DOMException)&&(Y.name==="AbortError"||Y.name==="ResponseAborted"||Y.name==="TimeoutError")}function cJ1(Y){if(!(Y instanceof Error))return!1;let X=Y.code;if(typeof X==="string"&&pJ1.includes(X))return!0;return!1}function aM6({error:Y,url:X,requestBodyValues:Q}){if(HK(Y))return Y;if(Y instanceof TypeError&&dJ1.includes(Y.message.toLowerCase())){let J=Y.cause;if(J!=null)return new t8({message:`Cannot connect to API: ${J.message}`,cause:J,url:X,requestBodyValues:Q,isRetryable:!0})}if(cJ1(Y))return new t8({message:`Cannot connect to API: ${Y.message}`,cause:Y,url:X,requestBodyValues:Q,isRetryable:!0});return Y}function Au(Y=globalThis){var X,Q,J;if(Y.window)return"runtime/browser";if((X=Y.navigator)==null?void 0:X.userAgent)return`runtime/${Y.navigator.userAgent.toLowerCase()}`;if((J=(Q=Y.process)==null?void 0:Q.versions)==null?void 0:J.node)return`runtime/node.js/${Y.process.version.substring(0)}`;if(Y.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function nJ1(Y){if(Y==null)return{};let X={};if(Y instanceof Headers)Y.forEach((Q,J)=>{X[J.toLowerCase()]=Q});else{if(!Array.isArray(Y))Y=Object.entries(Y);for(let[Q,J]of Y)if(J!=null)X[Q.toLowerCase()]=J}return X}function FK(Y,...X){let Q=new Headers(nJ1(Y)),J=Q.get("user-agent")||"";return Q.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Q.entries())}function oM6(Y){return Y!=null}function sM6({mediaType:Y,url:X,supportedUrls:Q}){return X=X.toLowerCase(),Y=Y.toLowerCase(),Object.entries(Q).map(([J,G])=>{let K=J.toLowerCase();return K==="*"||K==="*/*"?{mediaTypePrefix:"",regexes:G}:{mediaTypePrefix:K.replace(/\*/,""),regexes:G}}).filter(({mediaTypePrefix:J})=>Y.startsWith(J)).flatMap(({regexes:J})=>J).some((J)=>J.test(X))}function h2({settingValue:Y,environmentVariableName:X}){if(typeof Y==="string")return Y;if(Y!=null||typeof process>"u")return;if(Y=process.env[X],Y==null||typeof Y!=="string")return;return Y}function lM6(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(aJ1.test(Y)===!1&&rJ1.test(Y)===!1)return X;return oJ1(X)}function oJ1(Y){let X=[Y];while(X.length){let Q=X;X=[];for(let J of Q){if(Object.prototype.hasOwnProperty.call(J,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(J,"constructor")&&Object.prototype.hasOwnProperty.call(J.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in J){let K=J[G];if(K&&typeof K==="object")X.push(K)}}}return Y}function tM6(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Q){return lM6(Y)}try{return lM6(Y)}finally{Error.stackTraceLimit=X}}function f70(Y){if(Y.type==="object"||Array.isArray(Y.type)&&Y.type.includes("object")){Y.additionalProperties=!1;let{properties:Q}=Y;if(Q!=null)for(let J of Object.keys(Q))Q[J]=t$(Q[J])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(t$):t$(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(t$);if(Y.allOf!=null)Y.allOf=Y.allOf.map(t$);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(t$);let{definitions:X}=Y;if(X!=null)for(let Q of Object.keys(X))X[Q]=t$(X[Q]);return Y}function t$(Y){if(typeof Y==="boolean")return Y;return f70(Y)}function AJ(){return{}}function eJ1(Y,X){var Q,J,G;let K={type:"array"};if(((Q=Y.type)==null?void 0:Q._def)&&((G=(J=Y.type)==null?void 0:J._def)==null?void 0:G.typeName)!==j0.ZodAny)K.items=i1(Y.type._def,{...X,currentPath:[...X.currentPath,"items"]});if(Y.minLength)K.minItems=Y.minLength.value;if(Y.maxLength)K.maxItems=Y.maxLength.value;if(Y.exactLength)K.minItems=Y.exactLength.value,K.maxItems=Y.exactLength.value;return K}function Y51(Y){let X={type:"integer",format:"int64"};if(!Y.checks)return X;for(let Q of Y.checks)switch(Q.kind){case"min":if(Q.inclusive)X.minimum=Q.value;else X.exclusiveMinimum=Q.value;break;case"max":if(Q.inclusive)X.maximum=Q.value;else X.exclusiveMaximum=Q.value;break;case"multipleOf":X.multipleOf=Q.value;break}return X}function X51(){return{type:"boolean"}}function eM6(Y,X){return i1(Y.type._def,X)}function YA6(Y,X,Q){let J=Q!=null?Q:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,K)=>YA6(Y,X,G))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return J51(Y)}}function G51(Y,X){return{...i1(Y.innerType._def,X),default:Y.defaultValue()}}function W51(Y,X){return X.effectStrategy==="input"?i1(Y.schema._def,X):AJ()}function Z51(Y){return{type:"string",enum:Array.from(Y.values)}}function H51(Y,X){let Q=[i1(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),i1(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Q.forEach((G)=>{if(K51(G))J.push(...G.allOf);else{let K=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:W,...Z}=G;K=Z}J.push(K)}}),J.length?{allOf:J}:void 0}function F51(Y){let X=typeof Y.value;if(X!=="bigint"&&X!=="number"&&X!=="boolean"&&X!=="string")return{type:Array.isArray(Y.value)?"array":"object"};return{type:X==="bigint"?"integer":X,const:Y.value}}function XA6(Y,X){let Q={type:"string"};if(Y.checks)for(let J of Y.checks)switch(J.kind){case"min":Q.minLength=typeof Q.minLength==="number"?Math.max(Q.minLength,J.value):J.value;break;case"max":Q.maxLength=typeof Q.maxLength==="number"?Math.min(Q.maxLength,J.value):J.value;break;case"email":switch(X.emailStrategy){case"format:email":yG(Q,"email",J.message,X);break;case"format:idn-email":yG(Q,"idn-email",J.message,X);break;case"pattern:zod":QQ(Q,_G.email,J.message,X);break}break;case"url":yG(Q,"uri",J.message,X);break;case"uuid":yG(Q,"uuid",J.message,X);break;case"regex":QQ(Q,J.regex,J.message,X);break;case"cuid":QQ(Q,_G.cuid,J.message,X);break;case"cuid2":QQ(Q,_G.cuid2,J.message,X);break;case"startsWith":QQ(Q,RegExp(`^${k70(J.value,X)}`),J.message,X);break;case"endsWith":QQ(Q,RegExp(`${k70(J.value,X)}$`),J.message,X);break;case"datetime":yG(Q,"date-time",J.message,X);break;case"date":yG(Q,"date",J.message,X);break;case"time":yG(Q,"time",J.message,X);break;case"duration":yG(Q,"duration",J.message,X);break;case"length":Q.minLength=typeof Q.minLength==="number"?Math.max(Q.minLength,J.value):J.value,Q.maxLength=typeof Q.maxLength==="number"?Math.min(Q.maxLength,J.value):J.value;break;case"includes":{QQ(Q,RegExp(k70(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")yG(Q,"ipv4",J.message,X);if(J.version!=="v4")yG(Q,"ipv6",J.message,X);break}case"base64url":QQ(Q,_G.base64url,J.message,X);break;case"jwt":QQ(Q,_G.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")QQ(Q,_G.ipv4Cidr,J.message,X);if(J.version!=="v4")QQ(Q,_G.ipv6Cidr,J.message,X);break}case"emoji":QQ(Q,_G.emoji(),J.message,X);break;case"ulid":{QQ(Q,_G.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{yG(Q,"binary",J.message,X);break}case"contentEncoding:base64":{Q.contentEncoding="base64";break}case"pattern:zod":{QQ(Q,_G.base64,J.message,X);break}}break}case"nanoid":QQ(Q,_G.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Q}function k70(Y,X){return X.patternStrategy==="escape"?$51(Y):Y}function $51(Y){let X="";for(let Q=0;Q<Y.length;Q++){if(!V51.has(Y[Q]))X+="\\";X+=Y[Q]}return X}function yG(Y,X,Q,J){var G;if(Y.format||((G=Y.anyOf)==null?void 0:G.some((K)=>K.format))){if(!Y.anyOf)Y.anyOf=[];if(Y.format)Y.anyOf.push({format:Y.format}),delete Y.format;Y.anyOf.push({format:X,...Q&&J.errorMessages&&{errorMessage:{format:Q}}})}else Y.format=X}function QQ(Y,X,Q,J){var G;if(Y.pattern||((G=Y.allOf)==null?void 0:G.some((K)=>K.pattern))){if(!Y.allOf)Y.allOf=[];if(Y.pattern)Y.allOf.push({pattern:Y.pattern}),delete Y.pattern;Y.allOf.push({pattern:pM6(X,J),...Q&&J.errorMessages&&{errorMessage:{pattern:Q}}})}else Y.pattern=pM6(X,J)}function pM6(Y,X){var Q;if(!X.applyRegexFlags||!Y.flags)return Y.source;let J={i:Y.flags.includes("i"),m:Y.flags.includes("m"),s:Y.flags.includes("s")},G=J.i?Y.source.toLowerCase():Y.source,K="",W=!1,Z=!1,H=!1;for(let F=0;F<G.length;F++){if(W){K+=G[F],W=!1;continue}if(J.i){if(Z){if(G[F].match(/[a-z]/)){if(H)K+=G[F],K+=`${G[F-2]}-${G[F]}`.toUpperCase(),H=!1;else if(G[F+1]==="-"&&((Q=G[F+2])==null?void 0:Q.match(/[a-z]/)))K+=G[F],H=!0;else K+=`${G[F]}${G[F].toUpperCase()}`;continue}}else if(G[F].match(/[a-z]/)){K+=`[${G[F]}${G[F].toUpperCase()}]`;continue}}if(J.m){if(G[F]==="^"){K+=`(^|(?<=[\r
|
|
1191
1191
|
]))`;continue}else if(G[F]==="$"){K+=`($|(?=[\r
|