@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.
@@ -267,7 +267,7 @@ ${Y.stack}`;return X}if(typeof Y==="object"&&Y!==null){let X=Y,Q="";if(typeof X.
267
267
  ${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}
268
268
 
269
269
  Stack trace:
270
- ${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 VD(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=VD(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=VD(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=VD(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=FD(F),$=Y.newString(`Promise resolution error: ${V}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=FD(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return VD(Y,W)}catch(K){let W=FD(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 a$6=()=>{};function o$6(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 r$6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){o$6(Y);let K=await Promise.race([G,ht4(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 RQ0({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await n$6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=NG(W,J.newContext({interruptAfterMs:Q}),0);const K=NG(W,L$6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),$=G.unwrapResult(V),q=VD(G,Y);G.setProp(G.global,"tools",q);let B=G.runtime.hasPendingJob()?G.unwrapResult(await r$6(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 r$6(G,w,Q),T=G.unwrapResult(I);if(G.runtime.hasPendingJob())o$6(G);return{returnValue:G.dump(T),consoleLogs:K.logs}}catch(V){return console.log(V),{error:FD(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{o7(W,H,F)}}var ht4=(Y)=>new Promise((X)=>setTimeout(X,Y));var s$6=l(()=>{i$6();a$6()});var t$6=l(()=>{s$6()});async function bt4(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 e$6(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 xt4(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 $D(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 bt4(J,Y);else Q=await e$6(X.id,Y)}else Q=await e$6(X.id,Y);return xt4(Q,Y)}function ut4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function gt4(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 kb(Y,X,Q){let J=ut4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:gt4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function vb(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 _b(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return RQ0({code:Y,tools:J,timeoutMs:Q})}function WP(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function sH(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function CZ(Y){let X=new Set(mt4);return Y.filter((Q)=>!X.has(Q.name))}var mt4;var q$=l(()=>{t$6();mt4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var jQ0;var Yq6=l(()=>{q4();JP();q$();jQ0=Q6({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:z$6,outputSchema:B$6,handler:async(Y,X)=>{U6(X),h6(X),await X.access.check();let Q=await $D(X),J=kb(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 SQ0;var Xq6=l(()=>{q4();JP();q$();SQ0=Q6({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:U$6,outputSchema:D$6,handler:async(Y,X)=>{U6(X),h6(X),await X.access.check();let Q=await $D(X);return vb(Y.tools,Q.tools)}})});var kQ0;var Qq6=l(()=>{q4();JP();q$();kQ0=Q6({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:O$6,outputSchema:N$6,handler:async(Y,X)=>{U6(X),h6(X),await X.access.check();let Q=await $D(X);return await _b(Y.code,Q,Y.timeoutMs)}})});var Jq6=l(()=>{Yq6();Xq6();Qq6();JP()});var dt4,pt4,vQ0;var Gq6=l(()=>{_J();c0();q4();Mb();MZ();dt4=z.object({data:a36.describe("Data for the new connection (id is auto-generated if not provided)")}),pt4=z.object({item:F5.describe("The created connection entity")}),vQ0=Q6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:dt4,outputSchema:pt4,handler:async(Y,X)=>{U6(X);let Q=h6(X);await X.access.check();let J=p8(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=Bb(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=Ub(H)}let K=await ZD({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,bQ.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function ZP(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)=>ZP(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)&&ZP(Y[G],X[G]))}return!1}function ze4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>ZP(Q,G)))return!1;return X.push(Q),!0})}}function yb(Y,X){return Y.safeParse(X).success}function kY(Y){if(typeof Y==="boolean")return Y?z.any():z.never();let X={};for(let G of Ie4)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 Re4)J=G.apply(J,Y);return J}var ct4=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()}}},nt4=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}},it4=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}},at4=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}}},rt4=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()}}},ot4=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`})}}},st4=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`})}}},tt4=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)}}}},et4=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)}}},Ye4=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)}}},Xe4=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}}},Qe4=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}}},Je4=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}`})}}},Ge4=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())}}},We4=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)}},Ze4=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)}},Ke4=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=kY(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())}},He4=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)=>kY(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}},Fe4=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()}},Ve4=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()}}},$e4=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`})}}},qe4=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`})}}},Be4=class{apply(Y,X){if(!X.not)return Y;let Q=kY(X.not);return Y.refine((J)=>!yb(Q,J),{message:"Value must not match the 'not' schema"})}},Ue4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(ze4(),{message:"Array items must be unique"})}},De4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>kY(J)).reduce((J,G)=>z.intersection(J,G),Y)}},Oe4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?kY(X.anyOf[0]):z.union([kY(X.anyOf[0]),kY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>kY(J))]);return z.intersection(Y,Q)}},Ne4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>kY(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"})}},Le4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>kY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!yb(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=kY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!yb(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},we4=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]=kY(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(!kY(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"})}},Me4=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)=>ZP(J,G))},{message:"Value must match one of the enum values"})}},Ae4=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)=>ZP(J,Q),{message:"Value must equal the const value"})}},Te4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},Pe4=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))}},Ee4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=kY(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(yb(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"})}},Ce4=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)}},Ie4,Re4;var Wq6=l(()=>{t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();Ie4=[new nt4,new it4,new ct4,new at4,new rt4,new Ge4,new Ve4,new ot4,new st4,new tt4,new et4,new Ye4,new Xe4,new Qe4,new Je4,new He4,new We4,new Ze4,new Ke4,new $e4,new qe4,new Fe4],Re4=[new Pe4,new Me4,new Ae4,new De4,new Oe4,new Ne4,new Le4,new we4,new Ee4,new Be4,new Ue4,new Ce4,new Te4]});class _Q0{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,je4),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=hQ.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 je4="mcp";var Zq6=l(()=>{mY()});function Se4(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 yQ0;var Kq6=l(()=>{qM();yQ0=class yQ0 extends iK{constructor(Y,X){super(Y,X)}send(Y,X){let Q=Se4(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 Hq6,Fq6=async(Y,X,Q)=>{let J=ke4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new Hq6({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})}}},ke4=(Y,X,Q)=>{if(Y.type==="Websocket")return new _Q0(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 Z$(new URL(Y.url),K)}return new yQ0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var Vq6=l(()=>{XB();Nb();Zq6();mY();Kq6();Hq6=class Hq6 extends vJ{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},fw,X)}}});function qq6(Y){let X=(Q)=>{if("connection"in Y)return Fq6({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"?ve4(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(!fb.has(F))fb.set(F,K());return await fb.get(F)}catch(V){console.error("Failed to list tools",V),fb.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>$q6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return $q6(F,G)},G}})}var ve4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},fb,$q6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?kY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?kY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var zq6=l(()=>{Wq6();Vq6();fb=new Map});function hb(Y){return qq6(Y)}var NW8;var Bq6=l(()=>{zq6();NW8=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>hb({connection:Q});return global[X]}})});function bb(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 z$=(Y)=>{return{...bb(Y),forClient:(X)=>{return hb({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return hb({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var KP=l(()=>{Bq6()});var fQ0,TW8;var Uq6=l(()=>{xN();fQ0=y4(bN(),1),TW8=fQ0.createContext(null)});function RZ(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 FP(Y){return z.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function fe4(Y){return z.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function he4(Y){return z.object({item:Y.describe("The created entity with generated id")})}function be4(Y){return z.object({id:z.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function xe4(Y){return z.object({item:Y.describe("The updated entity")})}function $P(Y){return z.object({item:Y.describe("The deleted entity")})}function zD(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:IZ,outputSchema:RZ(X)},{name:`COLLECTION_${J}_GET`,inputSchema:HP,outputSchema:FP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:fe4(X),outputSchema:he4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:be4(X),outputSchema:xe4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:VP,outputSchema:$P(X),opt:!0});return K}var qD,_e4,Dq6,ye4,IZ,HP,VP;var V5=l(()=>{c0();qD=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()}),_e4=z.object({field:z.array(z.string()),operator:z.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:z.unknown()}),Dq6=z.lazy(()=>z.union([_e4,z.object({operator:z.enum(["and","or","not"]),conditions:z.array(Dq6)})])),ye4=z.object({field:z.array(z.string()),direction:z.enum(["asc","desc"]),nulls:z.enum(["first","last"]).optional()}),IZ=z.object({where:Dq6.optional().describe("Filter expression"),orderBy:z.array(ye4).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")});HP=z.object({id:z.string().describe("ID of the entity to retrieve")});VP=z.object({id:z.string().describe("ID of the entity to delete")})});var ue4,Oq6,SW8;var Nq6=l(()=>{c0();V5();ue4=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()}),Oq6=qD.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(ue4).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()})}),SW8=zD("registry_app",Oq6,{readOnly:!0})});var Lq6,wq6,Mq6,Aq6,Tq6,hQ0;var Pq6=l(()=>{c0();KP();Lq6=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)")}),wq6=z.object({events:z.array(Lq6).min(1).describe("Batch of CloudEvents to process")}),Mq6=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")}),Aq6=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(),Mq6).optional().describe("Per-event results keyed by event ID")}),Tq6=[{name:"ON_EVENTS",inputSchema:wq6,outputSchema:Aq6}],hQ0=z$(Tq6)});var qP,zP,BP,UP,Eq6,Cq6,DP,OP,NP,LP,wP,MP,AP,TP,Iq6,ge4;var Rq6=l(()=>{c0();KP();qP=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.")}),zP=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")}),BP=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")}),UP=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)")})}),Eq6=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")}),Cq6=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)")}),DP=z.object({subscriptions:z.array(Eq6).describe("Desired subscriptions - system will create/update/delete to match")}),OP=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(Cq6).describe("Current subscriptions after sync")}),NP=z.object({subscriptionId:z.string().describe("Subscription ID to remove")}),LP=z.object({success:z.boolean().describe("Whether unsubscribe was successful"),subscriptionId:z.string().describe("Subscription ID that was removed")}),wP=z.object({eventId:z.string().describe("Event ID to cancel")}),MP=z.object({success:z.boolean().describe("Whether cancellation was successful"),eventId:z.string().describe("Event ID that was cancelled")}),AP=z.object({eventId:z.string().describe("Event ID to acknowledge")}),TP=z.object({success:z.boolean().describe("Whether ACK was successful"),eventId:z.string().describe("Event ID that was acknowledged")}),Iq6=[{name:"EVENT_PUBLISH",inputSchema:qP,outputSchema:zP},{name:"EVENT_SUBSCRIBE",inputSchema:BP,outputSchema:UP},{name:"EVENT_UNSUBSCRIBE",inputSchema:NP,outputSchema:LP},{name:"EVENT_CANCEL",inputSchema:wP,outputSchema:MP},{name:"EVENT_ACK",inputSchema:AP,outputSchema:TP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:DP,outputSchema:OP}],ge4=z$(Iq6)});var me4,le4,de4,pe4,ce4,ne4,ie4,ae4,re4,oe4,se4,te4,PP;var xb=l(()=>{c0();me4=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.")}),le4=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/'])")}),de4=z.object({key:z.string().describe("Object key/path to get metadata for")}),pe4=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")}),ce4=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)")}),ne4=z.object({url:z.string().describe("Presigned URL for downloading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),ie4=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")}),ae4=z.object({url:z.string().describe("Presigned URL for uploading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),re4=z.object({key:z.string().describe("Object key/path to delete")}),oe4=z.object({success:z.boolean().describe("Whether the deletion was successful"),key:z.string().describe("The key that was deleted")}),se4=z.object({keys:z.array(z.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),te4=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")}),PP=[{name:"LIST_OBJECTS",inputSchema:me4,outputSchema:le4},{name:"GET_OBJECT_METADATA",inputSchema:de4,outputSchema:pe4},{name:"GET_PRESIGNED_URL",inputSchema:ce4,outputSchema:ne4},{name:"PUT_PRESIGNED_URL",inputSchema:ie4,outputSchema:ae4},{name:"DELETE_OBJECT",inputSchema:re4,outputSchema:oe4},{name:"DELETE_OBJECTS",inputSchema:se4,outputSchema:te4}]});var ub=l(()=>{KP();Uq6();Nq6();Pq6();Rq6();xb()});var ee4,Y01,jq6;var Sq6=l(()=>{c0();V5();ee4=qD.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")}),Y01=zD("assistant",ee4),jq6=[...Y01]});var EP,jZ,vq6,X01,Q01,_q6,J01,G01,W01,Z01,K01,H01,yq6,F01,V01,$01,q01,z01,B01,U01,D01,O01,N01,JZ8,L01,GZ8,kq6,w01,M01,bQ0,CP;var gb=l(()=>{c0();KP();V5();EP=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),EP),z.array(EP)])),jZ=z.record(z.string(),z.record(z.string(),EP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),vq6=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerOptions:jZ}),X01=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),Q01=z.string().describe("File data as URL string"),_q6=z.object({type:z.literal("file"),filename:z.string().optional().describe("Optional filename of the file"),data:Q01,mediaType:z.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:jZ}),J01=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")}),G01=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerOptions:jZ}),W01=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),Z01=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:jZ}),K01=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")}),H01=z.union([z.object({type:z.literal("text"),value:z.string()}),z.object({type:z.literal("json"),value:EP}),z.object({type:z.literal("error-text"),value:z.string()}),z.object({type:z.literal("error-json"),value:EP}),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")})]))})]),yq6=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:H01.describe("Result of the tool call"),result:z.unknown().describe("Unknown result of the tool call"),providerOptions:jZ}),F01=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")}),V01=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")})]),$01=z.object({role:z.literal("system"),content:z.string().describe("System message content"),providerOptions:jZ}),q01=z.object({role:z.literal("user"),content:z.array(z.union([vq6,_q6])).describe("User message content parts (text or file)"),providerOptions:jZ}),z01=z.object({role:z.literal("assistant"),content:z.array(z.union([vq6,_q6,G01,Z01,yq6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:jZ}),B01=z.object({role:z.literal("tool"),content:z.array(yq6).describe("Tool message content (tool results)"),providerOptions:jZ}),U01=z.union([$01,q01,z01,B01]),D01=z.array(U01).describe("A list of messages forming the prompt"),O01=z.object({prompt:D01.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")}),N01=z.object({content:z.array(z.union([X01,J01,W01,K01,F01,V01])).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")}),JZ8=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")}),L01=z.object({supportedUrls:z.record(z.string(),z.array(z.string())).describe("Supported URL patterns by media type for the provider")}),GZ8=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()}),kq6=z.object({modelId:z.string().describe("The ID of the model"),callOptions:O01}),w01=qD.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()}),M01=zD("llm",w01,{readOnly:!0}),bQ0=[{name:"LLM_METADATA",inputSchema:z.object({modelId:z.string().describe("The ID of the model")}),outputSchema:L01},{name:"LLM_DO_STREAM",inputSchema:kq6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:kq6,outputSchema:N01},...M01],CP=z$(bQ0)});function mb(){return!1}function fq6(Y,X){return Y===bQ.DEV_ASSETS(X)}function lb(Y,X){let Q=J00(X,Y),J=new Date().toISOString();return{id:Q.id??bQ.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:A01,bindings:["OBJECT_STORAGE"],status:"active"}}var A01;var xQ0=l(()=>{xb();_J();c0();A01=PP.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:z.toJSONSchema(Y.inputSchema),outputSchema:z.toJSONSchema(Y.outputSchema)}))});function P01(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 tH(Y){return typeof Y==="string"||typeof Y==="number"}function db(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>db(Y,F));case"or":return H.some((F)=>db(Y,F));case"not":return!H.every((F)=>db(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=uQ0(Y,K);switch(J){case"eq":return W===G;case"gt":return tH(W)&&tH(G)&&W>G;case"gte":return tH(W)&&tH(G)&&W>=G;case"lt":return tH(W)&&tH(G)&&W<G;case"lte":return tH(W)&&tH(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=P01(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 uQ0(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 E01(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=uQ0(Q,K),Z=uQ0(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 T01,C01,I01,gQ0;var hq6=l(()=>{ub();Sq6();V5();gb();xb();_J();c0();q4();xQ0();MZ();T01={LLM:bQ0,ASSISTANTS:jq6,OBJECT_STORAGE:PP};C01=IZ.extend({binding:z.union([z.object({}).passthrough(),z.string()]).optional()}),I01=RZ(F5),gQ0=Q6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:C01,outputSchema:I01,handler:async(Y,X)=>{await X.access.check();let Q=h6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=T01[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?bb(J):void 0,K=await X.storage.connections.list(Q.id);if(mb()){let B=ZG(),D=bQ.DEV_ASSETS(Q.id);if(!K.some((O)=>O.id===D)){let O=lb(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)=>db(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=E01(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 R01,mQ0;var bq6=l(()=>{V5();q4();xQ0();MZ();R01=FP(F5),mQ0=Q6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:HP,outputSchema:R01,handler:async(Y,X)=>{let Q=h6(X);if(await X.access.check(),mb()&&fq6(Y.id,Q.id))return{item:lb(Q.id,ZG())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var pb=(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 xq6(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 j01(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function S01(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function lQ0(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=j01(J);if(!G)continue;let[K,W]=G,Z=pb(K,Y),H=S01(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function uq6(Y,X){let Q=lQ0(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var dQ0=()=>{};class SZ{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=H9("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 cb=l(()=>{AZ()});async function _01(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=xq6(K),Z=pb(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=uq6(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 k01,v01,pQ0;var gq6=l(()=>{dQ0();cb();c0();q4();Mb();MZ();k01=z.object({id:z.string().describe("ID of the connection to update"),data:r36.describe("Partial connection data to update")}),v01=z.object({item:F5.describe("The updated connection entity")});pQ0=Q6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:k01,outputSchema:v01,handler:async(Y,X)=>{U6(X);let Q=h6(X);if(await X.access.check(),!p8(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=Bb(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=Ub(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 _01(F,V,Q.id,X)}let $=K.connection_token??W.connection_token;if(!$)try{let R=await new SZ(X.db,X.vault).get(G);if(R?.accessToken)$=R.accessToken}catch{}let q=await ZD({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=NG(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=o7(L,I,T);P&&await P}}catch(A){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",A)}return{item:O}}})});var cQ0;var mq6=l(()=>{V5();q4();MZ();cQ0=Q6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:VP,outputSchema:$P(F5),handler:async(Y,X)=>{U6(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 nQ0;var lq6=l(()=>{c0();q4();nQ0=Q6({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 dq6=l(()=>{Gq6();hq6();bq6();gq6();mq6();lq6()});import{sql as Z1}from"kysely";function pq6(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 h01(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,pq6(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=pq6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function cq6(Y){return Y.replace(/-/g,"_")}function x01(Y){return`app_${cq6(Y)}`}function u01(Y){return`app_role_${cq6(Y)}`}function g01(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 m01(Y,X,Q){if(await Z1`CREATE SCHEMA IF NOT EXISTS ${Z1.id(X)}`.execute(Y),!(await Z1`
270
+ ${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 VD(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=VD(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=VD(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=VD(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let V=FD(F),$=Y.newString(`Promise resolution error: ${V}`);Z.reject($),$.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=FD(H),V=Y.newString(`Promise rejection: ${F}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return VD(Y,W)}catch(K){let W=FD(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 a$6=()=>{};function o$6(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 r$6(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){o$6(Y);let K=await Promise.race([G,ht4(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 RQ0({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await n$6({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=NG(W,J.newContext({interruptAfterMs:Q}),0);const K=NG(W,L$6(G),0);try{let V=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),$=G.unwrapResult(V),q=VD(G,Y);G.setProp(G.global,"tools",q);let B=G.runtime.hasPendingJob()?G.unwrapResult(await r$6(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 r$6(G,w,Q),T=G.unwrapResult(I);if(G.runtime.hasPendingJob())o$6(G);return{returnValue:G.dump(T),consoleLogs:K.logs}}catch(V){return console.log(V),{error:FD(V),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{o7(W,H,F)}}var ht4=(Y)=>new Promise((X)=>setTimeout(X,Y));var s$6=l(()=>{i$6();a$6()});var t$6=l(()=>{s$6()});async function bt4(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 e$6(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 xt4(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 $D(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 bt4(J,Y);else Q=await e$6(X.id,Y)}else Q=await e$6(X.id,Y);return xt4(Q,Y)}function ut4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function gt4(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 kb(Y,X,Q){let J=ut4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:gt4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function vb(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 _b(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return RQ0({code:Y,tools:J,timeoutMs:Q})}function WP(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function sH(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function CZ(Y){let X=new Set(mt4);return Y.filter((Q)=>!X.has(Q.name))}var mt4;var q$=l(()=>{t$6();mt4=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var jQ0;var Yq6=l(()=>{q4();JP();q$();jQ0=Q6({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:z$6,outputSchema:B$6,handler:async(Y,X)=>{U6(X),h6(X),await X.access.check();let Q=await $D(X),J=kb(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 SQ0;var Xq6=l(()=>{q4();JP();q$();SQ0=Q6({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:U$6,outputSchema:D$6,handler:async(Y,X)=>{U6(X),h6(X),await X.access.check();let Q=await $D(X);return vb(Y.tools,Q.tools)}})});var kQ0;var Qq6=l(()=>{q4();JP();q$();kQ0=Q6({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:O$6,outputSchema:N$6,handler:async(Y,X)=>{U6(X),h6(X),await X.access.check();let Q=await $D(X);return await _b(Y.code,Q,Y.timeoutMs)}})});var Jq6=l(()=>{Yq6();Xq6();Qq6();JP()});var dt4,pt4,vQ0;var Gq6=l(()=>{_J();c0();q4();Mb();MZ();dt4=z.object({data:a36.describe("Data for the new connection (id is auto-generated if not provided)")}),pt4=z.object({item:F5.describe("The created connection entity")}),vQ0=Q6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:dt4,outputSchema:pt4,handler:async(Y,X)=>{U6(X);let Q=h6(X);await X.access.check();let J=p8(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=Bb(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=Ub(H)}let K=await ZD({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,bQ.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function ZP(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)=>ZP(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)&&ZP(Y[G],X[G]))}return!1}function ze4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>ZP(Q,G)))return!1;return X.push(Q),!0})}}function yb(Y,X){return Y.safeParse(X).success}function kY(Y){if(typeof Y==="boolean")return Y?z.any():z.never();let X={};for(let G of Ie4)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 Re4)J=G.apply(J,Y);return J}var ct4=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()}}},nt4=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}},it4=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}},at4=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}}},rt4=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()}}},ot4=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`})}}},st4=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`})}}},tt4=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)}}}},et4=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)}}},Ye4=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)}}},Xe4=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}}},Qe4=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}}},Je4=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}`})}}},Ge4=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())}}},We4=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)}},Ze4=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)}},Ke4=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=kY(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())}},He4=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)=>kY(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}},Fe4=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()}},Ve4=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()}}},$e4=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`})}}},qe4=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`})}}},Be4=class{apply(Y,X){if(!X.not)return Y;let Q=kY(X.not);return Y.refine((J)=>!yb(Q,J),{message:"Value must not match the 'not' schema"})}},Ue4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(ze4(),{message:"Array items must be unique"})}},De4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>kY(J)).reduce((J,G)=>z.intersection(J,G),Y)}},Oe4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?kY(X.anyOf[0]):z.union([kY(X.anyOf[0]),kY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>kY(J))]);return z.intersection(Y,Q)}},Ne4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>kY(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"})}},Le4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>kY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!yb(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=kY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!yb(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},we4=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]=kY(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(!kY(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"})}},Me4=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)=>ZP(J,G))},{message:"Value must match one of the enum values"})}},Ae4=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)=>ZP(J,Q),{message:"Value must equal the const value"})}},Te4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},Pe4=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))}},Ee4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=kY(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(yb(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"})}},Ce4=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)}},Ie4,Re4;var Wq6=l(()=>{t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();t4();Ie4=[new nt4,new it4,new ct4,new at4,new rt4,new Ge4,new Ve4,new ot4,new st4,new tt4,new et4,new Ye4,new Xe4,new Qe4,new Je4,new He4,new We4,new Ze4,new Ke4,new $e4,new qe4,new Fe4],Re4=[new Pe4,new Me4,new Ae4,new De4,new Oe4,new Ne4,new Le4,new we4,new Ee4,new Be4,new Ue4,new Ce4,new Te4]});class _Q0{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,je4),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=hQ.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 je4="mcp";var Zq6=l(()=>{mY()});function Se4(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 yQ0;var Kq6=l(()=>{qM();yQ0=class yQ0 extends iK{constructor(Y,X){super(Y,X)}send(Y,X){let Q=Se4(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 Hq6,Fq6=async(Y,X,Q)=>{let J=ke4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new Hq6({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})}}},ke4=(Y,X,Q)=>{if(Y.type==="Websocket")return new _Q0(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 Z$(new URL(Y.url),K)}return new yQ0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var Vq6=l(()=>{XB();Nb();Zq6();mY();Kq6();Hq6=class Hq6 extends vJ{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},fw,X)}}});function qq6(Y){let X=(Q)=>{if("connection"in Y)return Fq6({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"?ve4(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(!fb.has(F))fb.set(F,K());return await fb.get(F)}catch(V){console.error("Failed to list tools",V),fb.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>$q6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((V)=>V.name===J);if(!F)throw Error(`Tool ${J} not found`);return $q6(F,G)},G}})}var ve4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},fb,$q6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?kY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?kY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var zq6=l(()=>{Wq6();Vq6();fb=new Map});function hb(Y){return qq6(Y)}var NW8;var Bq6=l(()=>{zq6();NW8=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>hb({connection:Q});return global[X]}})});function bb(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 z$=(Y)=>{return{...bb(Y),forClient:(X)=>{return hb({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return hb({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var KP=l(()=>{Bq6()});var fQ0,TW8;var Uq6=l(()=>{xN();fQ0=y4(bN(),1),TW8=fQ0.createContext(null)});function RZ(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 FP(Y){return z.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function fe4(Y){return z.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function he4(Y){return z.object({item:Y.describe("The created entity with generated id")})}function be4(Y){return z.object({id:z.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function xe4(Y){return z.object({item:Y.describe("The updated entity")})}function $P(Y){return z.object({item:Y.describe("The deleted entity")})}function zD(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:IZ,outputSchema:RZ(X)},{name:`COLLECTION_${J}_GET`,inputSchema:HP,outputSchema:FP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:fe4(X),outputSchema:he4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:be4(X),outputSchema:xe4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:VP,outputSchema:$P(X),opt:!0});return K}var qD,_e4,Dq6,ye4,IZ,HP,VP;var V5=l(()=>{c0();qD=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()}),_e4=z.object({field:z.array(z.string()),operator:z.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:z.unknown()}),Dq6=z.lazy(()=>z.union([_e4,z.object({operator:z.enum(["and","or","not"]),conditions:z.array(Dq6)})])),ye4=z.object({field:z.array(z.string()),direction:z.enum(["asc","desc"]),nulls:z.enum(["first","last"]).optional()}),IZ=z.object({where:Dq6.optional().describe("Filter expression"),orderBy:z.array(ye4).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")});HP=z.object({id:z.string().describe("ID of the entity to retrieve")});VP=z.object({id:z.string().describe("ID of the entity to delete")})});var ue4,Oq6,SW8;var Nq6=l(()=>{c0();V5();ue4=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()}),Oq6=qD.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(ue4).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()})}),SW8=zD("registry_app",Oq6,{readOnly:!0})});var Lq6,wq6,Mq6,Aq6,Tq6,hQ0;var Pq6=l(()=>{c0();KP();Lq6=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)")}),wq6=z.object({events:z.array(Lq6).min(1).describe("Batch of CloudEvents to process")}),Mq6=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")}),Aq6=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(),Mq6).optional().describe("Per-event results keyed by event ID")}),Tq6=[{name:"ON_EVENTS",inputSchema:wq6,outputSchema:Aq6}],hQ0=z$(Tq6)});var qP,zP,BP,UP,Eq6,Cq6,DP,OP,NP,LP,wP,MP,AP,TP,Iq6,ge4;var Rq6=l(()=>{c0();KP();qP=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.")}),zP=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")}),BP=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")}),UP=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)")})}),Eq6=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")}),Cq6=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)")}),DP=z.object({subscriptions:z.array(Eq6).describe("Desired subscriptions - system will create/update/delete to match")}),OP=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(Cq6).describe("Current subscriptions after sync")}),NP=z.object({subscriptionId:z.string().describe("Subscription ID to remove")}),LP=z.object({success:z.boolean().describe("Whether unsubscribe was successful"),subscriptionId:z.string().describe("Subscription ID that was removed")}),wP=z.object({eventId:z.string().describe("Event ID to cancel")}),MP=z.object({success:z.boolean().describe("Whether cancellation was successful"),eventId:z.string().describe("Event ID that was cancelled")}),AP=z.object({eventId:z.string().describe("Event ID to acknowledge")}),TP=z.object({success:z.boolean().describe("Whether ACK was successful"),eventId:z.string().describe("Event ID that was acknowledged")}),Iq6=[{name:"EVENT_PUBLISH",inputSchema:qP,outputSchema:zP},{name:"EVENT_SUBSCRIBE",inputSchema:BP,outputSchema:UP},{name:"EVENT_UNSUBSCRIBE",inputSchema:NP,outputSchema:LP},{name:"EVENT_CANCEL",inputSchema:wP,outputSchema:MP},{name:"EVENT_ACK",inputSchema:AP,outputSchema:TP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:DP,outputSchema:OP}],ge4=z$(Iq6)});var me4,le4,de4,pe4,ce4,ne4,ie4,ae4,re4,oe4,se4,te4,PP;var xb=l(()=>{c0();me4=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.")}),le4=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/'])")}),de4=z.object({key:z.string().describe("Object key/path to get metadata for")}),pe4=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")}),ce4=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)")}),ne4=z.object({url:z.string().describe("Presigned URL for downloading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),ie4=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")}),ae4=z.object({url:z.string().describe("Presigned URL for uploading the object"),expiresIn:z.number().describe("Expiration time in seconds that was used")}),re4=z.object({key:z.string().describe("Object key/path to delete")}),oe4=z.object({success:z.boolean().describe("Whether the deletion was successful"),key:z.string().describe("The key that was deleted")}),se4=z.object({keys:z.array(z.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),te4=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")}),PP=[{name:"LIST_OBJECTS",inputSchema:me4,outputSchema:le4},{name:"GET_OBJECT_METADATA",inputSchema:de4,outputSchema:pe4},{name:"GET_PRESIGNED_URL",inputSchema:ce4,outputSchema:ne4},{name:"PUT_PRESIGNED_URL",inputSchema:ie4,outputSchema:ae4},{name:"DELETE_OBJECT",inputSchema:re4,outputSchema:oe4},{name:"DELETE_OBJECTS",inputSchema:se4,outputSchema:te4}]});var ub=l(()=>{KP();Uq6();Nq6();Pq6();Rq6();xb()});var ee4,Y01,jq6;var Sq6=l(()=>{c0();V5();ee4=qD.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")}),Y01=zD("assistant",ee4),jq6=[...Y01]});var EP,jZ,vq6,X01,Q01,_q6,J01,G01,W01,Z01,K01,H01,yq6,F01,V01,$01,q01,z01,B01,U01,D01,O01,N01,JZ8,L01,GZ8,kq6,w01,M01,bQ0,CP;var gb=l(()=>{c0();KP();V5();EP=z.lazy(()=>z.union([z.null(),z.string(),z.number(),z.boolean(),z.record(z.string(),EP),z.array(EP)])),jZ=z.record(z.string(),z.record(z.string(),EP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),vq6=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerOptions:jZ}),X01=z.object({type:z.literal("text"),text:z.string().describe("The text content"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),Q01=z.string().describe("File data as URL string"),_q6=z.object({type:z.literal("file"),filename:z.string().optional().describe("Optional filename of the file"),data:Q01,mediaType:z.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:jZ}),J01=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")}),G01=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerOptions:jZ}),W01=z.object({type:z.literal("reasoning"),text:z.string().describe("The reasoning text"),providerMetadata:z.any().optional().describe("Additional provider-specific metadata")}),Z01=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:jZ}),K01=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")}),H01=z.union([z.object({type:z.literal("text"),value:z.string()}),z.object({type:z.literal("json"),value:EP}),z.object({type:z.literal("error-text"),value:z.string()}),z.object({type:z.literal("error-json"),value:EP}),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")})]))})]),yq6=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:H01.describe("Result of the tool call"),result:z.unknown().describe("Unknown result of the tool call"),providerOptions:jZ}),F01=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")}),V01=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")})]),$01=z.object({role:z.literal("system"),content:z.string().describe("System message content"),providerOptions:jZ}),q01=z.object({role:z.literal("user"),content:z.array(z.union([vq6,_q6])).describe("User message content parts (text or file)"),providerOptions:jZ}),z01=z.object({role:z.literal("assistant"),content:z.array(z.union([vq6,_q6,G01,Z01,yq6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:jZ}),B01=z.object({role:z.literal("tool"),content:z.array(yq6).describe("Tool message content (tool results)"),providerOptions:jZ}),U01=z.union([$01,q01,z01,B01]),D01=z.array(U01).describe("A list of messages forming the prompt"),O01=z.object({prompt:D01.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")}),N01=z.object({content:z.array(z.union([X01,J01,W01,K01,F01,V01])).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")}),JZ8=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")}),L01=z.object({supportedUrls:z.record(z.string(),z.array(z.string())).describe("Supported URL patterns by media type for the provider")}),GZ8=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()}),kq6=z.object({modelId:z.string().describe("The ID of the model"),callOptions:O01}),w01=qD.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()}),M01=zD("llm",w01,{readOnly:!0}),bQ0=[{name:"LLM_METADATA",inputSchema:z.object({modelId:z.string().describe("The ID of the model")}),outputSchema:L01},{name:"LLM_DO_STREAM",inputSchema:kq6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:kq6,outputSchema:N01},...M01],CP=z$(bQ0)});function mb(){return!1}function fq6(Y,X){return Y===bQ.DEV_ASSETS(X)}function lb(Y,X){let Q=J00(X,Y),J=new Date().toISOString();return{id:Q.id??bQ.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:A01,bindings:["OBJECT_STORAGE"],status:"active"}}var A01;var xQ0=l(()=>{xb();_J();c0();A01=PP.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:z.toJSONSchema(Y.inputSchema),outputSchema:z.toJSONSchema(Y.outputSchema)}))});function P01(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 tH(Y){return typeof Y==="string"||typeof Y==="number"}function db(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>db(Y,F));case"or":return H.some((F)=>db(Y,F));case"not":return!H.every((F)=>db(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=uQ0(Y,K);switch(J){case"eq":return W===G;case"gt":return tH(W)&&tH(G)&&W>G;case"gte":return tH(W)&&tH(G)&&W>=G;case"lt":return tH(W)&&tH(G)&&W<G;case"lte":return tH(W)&&tH(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=P01(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 uQ0(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 E01(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=uQ0(Q,K),Z=uQ0(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 T01,C01,I01,gQ0;var hq6=l(()=>{ub();Sq6();V5();gb();xb();_J();c0();q4();xQ0();MZ();T01={LLM:bQ0,ASSISTANTS:jq6,OBJECT_STORAGE:PP};C01=IZ.extend({binding:z.union([z.object({}).passthrough(),z.string()]).optional()}),I01=RZ(F5),gQ0=Q6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:C01,outputSchema:I01,handler:async(Y,X)=>{await X.access.check();let Q=h6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=T01[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?bb(J):void 0,K=await X.storage.connections.list(Q.id);if(mb()){let B=ZG(),D=bQ.DEV_ASSETS(Q.id);if(!K.some((O)=>O.id===D)){let O=lb(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)=>db(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=E01(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 R01,mQ0;var bq6=l(()=>{V5();q4();xQ0();MZ();R01=FP(F5),mQ0=Q6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:HP,outputSchema:R01,handler:async(Y,X)=>{let Q=h6(X);if(await X.access.check(),mb()&&fq6(Y.id,Q.id))return{item:lb(Q.id,ZG())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var pb=(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 xq6(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 j01(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function S01(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function lQ0(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=j01(J);if(!G)continue;let[K,W]=G,Z=pb(K,Y),H=S01(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function uq6(Y,X){let Q=lQ0(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var dQ0=()=>{};class SZ{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=H9("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 cb=l(()=>{AZ()});async function _01(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=xq6(K),Z=pb(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=uq6(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 k01,v01,pQ0;var gq6=l(()=>{dQ0();cb();c0();q4();Mb();MZ();k01=z.object({id:z.string().describe("ID of the connection to update"),data:r36.describe("Partial connection data to update")}),v01=z.object({item:F5.describe("The updated connection entity")});pQ0=Q6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:k01,outputSchema:v01,handler:async(Y,X)=>{U6(X);let Q=h6(X);if(await X.access.check(),!p8(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=Bb(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=Ub(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 _01(F,V,Q.id,X)}let $=K.connection_token??W.connection_token;if(!$)try{let R=await new SZ(X.db,X.vault).get(G);if(R?.accessToken)$=R.accessToken}catch{}let q=await ZD({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=NG(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=o7(L,I,T);P&&await P}}catch(A){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",A)}return{item:O}}})});var cQ0;var mq6=l(()=>{V5();q4();MZ();cQ0=Q6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:VP,outputSchema:$P(F5),handler:async(Y,X)=>{U6(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 nQ0;var lq6=l(()=>{c0();q4();nQ0=Q6({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 dq6=l(()=>{Gq6();hq6();bq6();gq6();mq6();lq6()});import{sql as Z1}from"kysely";function pq6(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 h01(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,pq6(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=pq6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function cq6(Y){return Y.replace(/-/g,"_")}function x01(Y){return`app_${cq6(Y)}`}function u01(Y){return`app_role_${cq6(Y)}`}function g01(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 m01(Y,X,Q){if(await Z1`CREATE SCHEMA IF NOT EXISTS ${Z1.id(X)}`.execute(Y),!(await Z1`
271
271
  SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
272
272
  `.execute(Y)).rows[0]?.exists)await Z1`CREATE ROLE ${Z1.id(Q)} NOLOGIN`.execute(Y);await Z1`GRANT ${Z1.id(Q)} TO CURRENT_USER`.execute(Y),await Z1`GRANT USAGE, CREATE ON SCHEMA ${Z1.id(X)} TO ${Z1.id(Q)}`.execute(Y),await Z1`GRANT ALL ON ALL TABLES IN SCHEMA ${Z1.id(X)} TO ${Z1.id(Q)}`.execute(Y),await Z1`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${Z1.id(X)} TO ${Z1.id(Q)}`.execute(Y),await Z1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${Z1.id(X)} GRANT ALL ON TABLES TO ${Z1.id(Q)}`.execute(Y),await Z1`ALTER DEFAULT PRIVILEGES IN SCHEMA ${Z1.id(X)} GRANT ALL ON SEQUENCES TO ${Z1.id(Q)}`.execute(Y),await Z1`REVOKE ALL ON SCHEMA public FROM ${Z1.id(Q)}`.execute(Y)}async function l01(Y,X,Q,J){try{return await Y.transaction().execute(async(G)=>{return await Z1`SET LOCAL ROLE ${Z1.id(Q)}`.execute(G),await Z1`SET LOCAL search_path TO ${Z1.id(X)}`.execute(G),await Z1.raw(J).execute(G)})}catch(G){if(g01(G))return await m01(Y,X,Q),await Y.transaction().execute(async(K)=>{return await Z1`SET LOCAL ROLE ${Z1.id(Q)}`.execute(K),await Z1`SET LOCAL search_path TO ${Z1.id(X)}`.execute(K),await Z1.raw(J).execute(K)});throw G}}var f01,b01,nq6;var iq6=l(()=>{c0();q4();f01=z.object({results:z.array(z.unknown()).optional(),success:z.boolean().optional()});b01=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()});nq6=Q6({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:b01,outputSchema:z.object({result:z.array(f01)}),handler:async(Y,X)=>{U6(X),await X.access.check();let Q=h01(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=x01(X.connectionId),G=u01(X.connectionId);return{result:[{results:(await l01(X.db,J,G,Q)).rows,success:!0}]}}})});var aq6,p01,rq6;var kZ=l(()=>{c0();ub();aq6=z.object({connectionId:z.string().optional().describe("Filter subscriptions by connection ID (optional)")}),p01=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)")}),rq6=z.object({subscriptions:z.array(p01).describe("List of subscriptions")})});var iQ0;var oq6=l(()=>{q4();kZ();iQ0=Q6({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:qP,outputSchema:zP,handler:async(Y,X)=>{U6(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 aQ0;var sq6=l(()=>{q4();kZ();aQ0=Q6({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:BP,outputSchema:UP,handler:async(Y,X)=>{U6(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 rQ0;var tq6=l(()=>{q4();kZ();rQ0=Q6({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:NP,outputSchema:LP,handler:async(Y,X)=>{U6(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 oQ0;var eq6=l(()=>{q4();kZ();oQ0=Q6({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:wP,outputSchema:MP,handler:async(Y,X)=>{U6(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 sQ0;var Yz6=l(()=>{q4();kZ();sQ0=Q6({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:AP,outputSchema:TP,handler:async(Y,X)=>{U6(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 tQ0;var Xz6=l(()=>{q4();kZ();tQ0=Q6({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:aq6,outputSchema:rq6,handler:async(Y,X)=>{U6(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 eQ0;var Qz6=l(()=>{q4();kZ();eQ0=Q6({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:DP,outputSchema:OP,handler:async(Y,X)=>{U6(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 Jz6=l(()=>{oq6();sq6();tq6();eq6();Yz6();Xz6();Qz6();kZ()});var n01,l7,Gz6,Wz6;var BD=l(()=>{c0();n01=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")}),l7=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(n01).describe("Connections with their selected tools, resources, and prompts")}),Gz6=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")}),Wz6=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 i01,a01,YJ0;var Zz6=l(()=>{c0();q4();BD();i01=z.object({data:Gz6.describe("Data for the new virtual MCP")}),a01=z.object({item:l7.describe("The created virtual MCP entity")}),YJ0=Q6({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:i01,outputSchema:a01,handler:async(Y,X)=>{U6(X);let Q=h6(X);await X.access.check();let J=p8(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 r01(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 eH(Y){return typeof Y==="string"||typeof Y==="number"}function XJ0(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 o01(Y,X){return Y.connections.some((Q)=>Q.connection_id===X)}function nb(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>nb(Y,F));case"or":return H.some((F)=>nb(Y,F));case"not":return!H.every((F)=>nb(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 o01(Y,G)}let W=XJ0(Y,K);switch(J){case"eq":return W===G;case"gt":return eH(W)&&eH(G)&&W>G;case"gte":return eH(W)&&eH(G)&&W>=G;case"lt":return eH(W)&&eH(G)&&W<G;case"lte":return eH(W)&&eH(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=r01(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 s01(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=XJ0(Q,K),Z=XJ0(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 t01,e01,QJ0;var Kz6=l(()=>{V5();q4();BD();t01=IZ,e01=RZ(l7),QJ0=Q6({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:t01,outputSchema:e01,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(($)=>nb($,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=s01(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 Y61,X61,JJ0;var Hz6=l(()=>{c0();q4();BD();Y61=z.object({id:z.string().describe("ID of the virtual MCP to retrieve")}),X61=z.object({item:l7.nullable().describe("The retrieved virtual MCP, or null if not found")}),JJ0=Q6({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:Y61,outputSchema:X61,handler:async(Y,X)=>{U6(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 Q61,J61,GJ0;var Fz6=l(()=>{c0();q4();BD();Q61=z.object({id:z.string().describe("ID of the virtual MCP to update"),data:Wz6.describe("Partial virtual MCP data to update")}),J61=z.object({item:l7.describe("The updated virtual MCP entity")}),GJ0=Q6({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:Q61,outputSchema:J61,handler:async(Y,X)=>{U6(X);let Q=h6(X);await X.access.check();let J=p8(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 G61,W61,WJ0;var Vz6=l(()=>{c0();q4();BD();G61=z.object({id:z.string().describe("ID of the virtual MCP to delete")}),W61=z.object({item:l7.describe("The deleted virtual MCP entity")}),WJ0=Q6({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:G61,outputSchema:W61,handler:async(Y,X)=>{U6(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 $z6=l(()=>{Zz6();Kz6();Hz6();Fz6();Vz6()});var K61,ZJ0;var qz6=l(()=>{q4();c0();K61=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")}),ZJ0=Q6({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(K61).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 KJ0;var zz6=l(()=>{q4();c0();KJ0=Q6({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 Bz6=l(()=>{qz6();zz6()});var HJ0;var Uz6=l(()=>{c0();q4();HJ0=Q6({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)=>{U6(X),await X.access.check();let Q=p8(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 FJ0;var Dz6=l(()=>{c0();q4();FJ0=Q6({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)=>{U6(X),await X.access.check();let Q=p8(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 VJ0;var Oz6=l(()=>{c0();q4();VJ0=Q6({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)=>{U6(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 $J0;var Nz6=l(()=>{c0();q4();$J0=Q6({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)=>{U6(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 qJ0;var Lz6=l(()=>{c0();q4();qJ0=Q6({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 U6(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var IP;var zJ0=l(()=>{c0();IP=z.object({title:z.string(),url:z.string(),icon:z.string()})});var BJ0;var wz6=l(()=>{c0();q4();zJ0();BJ0=Q6({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:z.object({}),outputSchema:z.object({organizationId:z.string(),sidebar_items:z.array(IP).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)=>{U6(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 UJ0;var Mz6=l(()=>{c0();q4();zJ0();UJ0=Q6({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:z.object({organizationId:z.string(),sidebar_items:z.array(IP).optional(),enabled_plugins:z.array(z.string()).optional()}),outputSchema:z.object({organizationId:z.string(),sidebar_items:z.array(IP).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(U6(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 DJ0;var Az6=l(()=>{c0();q4();DJ0=Q6({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)=>{U6(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 OJ0;var Tz6=l(()=>{c0();q4();OJ0=Q6({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)=>{U6(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 NJ0;var Pz6=l(()=>{c0();q4();NJ0=Q6({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)=>{U6(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 LJ0;var Ez6=l(()=>{c0();q4();LJ0=Q6({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)=>{U6(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 Cz6=l(()=>{Uz6();Dz6();Oz6();Nz6();Lz6();wz6();Mz6();Az6();Tz6();Pz6();Ez6()});var Iz6,d7,Rz6,jz6;var B$=l(()=>{c0();Iz6=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")}),d7=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")}),Rz6=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")}),jz6=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 V61,$61,wJ0;var Sz6=l(()=>{c0();q4();B$();AZ();V61=z.object({data:Rz6.describe("Data for the new thread (id is auto-generated if not provided)")}),$61=z.object({item:d7.describe("The created thread entity")}),wJ0=Q6({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:V61,outputSchema:$61,handler:async(Y,X)=>{U6(X);let Q=h6(X);await X.access.check();let J=p8(X);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??H9("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 q61,z61,MJ0;var kz6=l(()=>{V5();q4();B$();c0();q61=IZ.extend({where:z.object({created_by:z.string().optional()}).optional()}),z61=RZ(d7),MJ0=Q6({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:q61,outputSchema:z61,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 B61,AJ0;var vz6=l(()=>{V5();q4();B$();B61=FP(d7),AJ0=Q6({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:HP,outputSchema:B61,handler:async(Y,X)=>{U6(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 U61,D61,TJ0;var _z6=l(()=>{c0();q4();B$();U61=z.object({id:z.string().describe("ID of the thread to update"),data:jz6.describe("Partial thread data to update")}),D61=z.object({item:d7.describe("The updated thread entity")}),TJ0=Q6({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:U61,outputSchema:D61,handler:async(Y,X)=>{U6(X);let Q=h6(X);await X.access.check();let J=p8(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 PJ0;var yz6=l(()=>{V5();q4();B$();PJ0=Q6({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:VP,outputSchema:$P(d7),handler:async(Y,X)=>{U6(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 fz6(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=fz6(X);if(Q)return Q}return null}var O61,EJ0;var hz6=l(()=>{V5();q4();B$();O61=RZ(Iz6),EJ0=Q6({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:IZ,outputSchema:O61,handler:async(Y,X)=>{let Q=h6(X);await X.access.check();let J=fz6(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 bz6=l(()=>{Sz6();kz6();vz6();_z6();yz6();hz6()});var L61,w61,CJ0;var xz6=l(()=>{c0();q4();L61=z.object({id:z.string().min(1)}),w61=z.object({user:z.object({id:z.string(),name:z.string(),email:z.string(),image:z.string().nullable()}).nullable()}),CJ0=Q6({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:L61,outputSchema:w61,handler:async(Y,X)=>{await X.access.check(),U6(X);let Q=p8(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 uz6=l(()=>{xz6()});var mz6={};k8(mz6,{managementMCP:()=>IJ0,ALL_TOOLS:()=>gz6});var A61,T61,gz6,IJ0=async(Y)=>{let X=null;if(Y.organization)X=(await Y.storage.organizationSettings.get(Y.organization.id))?.enabled_plugins??null;let J=rV6(gz6,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 sF6({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var RJ0=l(()=>{tF6();GQ0();q$6();Jq6();dq6();iq6();Jz6();$z6();Bz6();Cz6();bz6();uz6();A61=[HJ0,FJ0,VJ0,$J0,qJ0,BJ0,UJ0,DJ0,OJ0,NJ0,LJ0,vQ0,gQ0,mQ0,pQ0,cQ0,nQ0,YJ0,QJ0,JJ0,GJ0,WJ0,nq6,ZJ0,KJ0,ZQ0,HQ0,FQ0,KQ0,iQ0,aQ0,rQ0,oQ0,sQ0,tQ0,eQ0,CJ0,jQ0,SQ0,kQ0,wJ0,MJ0,AJ0,TJ0,PJ0,EJ0],T61=oV6(),gz6=[...A61,...T61]});var Q50=E((Nz8,MD6)=>{var{defineProperty:X50,getOwnPropertyDescriptor:S11,getOwnPropertyNames:k11}=Object,v11=Object.prototype.hasOwnProperty,_11=(Y,X)=>{for(var Q in X)X50(Y,Q,{get:X[Q],enumerable:!0})},y11=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of k11(X))if(!v11.call(Y,G)&&G!==Q)X50(Y,G,{get:()=>X[G],enumerable:!(J=S11(X,G))||J.enumerable})}return Y},f11=(Y)=>y11(X50({},"__esModule",{value:!0}),Y),LD6={};_11(LD6,{SYMBOL_FOR_REQ_CONTEXT:()=>wD6,getContext:()=>h11});MD6.exports=f11(LD6);var wD6=Symbol.for("@vercel/request-context");function h11(){return globalThis[wD6]?.get?.()??{}}});var xP=E((Lz8,PD6)=>{var{defineProperty:J50,getOwnPropertyDescriptor:b11,getOwnPropertyNames:x11}=Object,u11=Object.prototype.hasOwnProperty,g11=(Y,X)=>{for(var Q in X)J50(Y,Q,{get:X[Q],enumerable:!0})},m11=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of x11(X))if(!u11.call(Y,G)&&G!==Q)J50(Y,G,{get:()=>X[G],enumerable:!(J=b11(X,G))||J.enumerable})}return Y},l11=(Y)=>m11(J50({},"__esModule",{value:!0}),Y),AD6={};g11(AD6,{VercelOidcTokenError:()=>TD6});PD6.exports=l11(AD6);class TD6 extends Error{constructor(Y,X){super(Y);this.name="VercelOidcTokenError",this.cause=X}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var RD6=E((wz8,ID6)=>{var{create:d11,defineProperty:Wx,getOwnPropertyDescriptor:p11,getOwnPropertyNames:c11,getPrototypeOf:n11}=Object,i11=Object.prototype.hasOwnProperty,a11=(Y,X)=>{for(var Q in X)Wx(Y,Q,{get:X[Q],enumerable:!0})},ED6=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of c11(X))if(!i11.call(Y,G)&&G!==Q)Wx(Y,G,{get:()=>X[G],enumerable:!(J=p11(X,G))||J.enumerable})}return Y},W50=(Y,X,Q)=>(Q=Y!=null?d11(n11(Y)):{},ED6(X||!Y||!Y.__esModule?Wx(Q,"default",{value:Y,enumerable:!0}):Q,Y)),r11=(Y)=>ED6(Wx({},"__esModule",{value:!0}),Y),CD6={};a11(CD6,{findRootDir:()=>t11,getUserDataDir:()=>e11});ID6.exports=r11(CD6);var uP=W50(V0("path")),o11=W50(V0("fs")),G50=W50(V0("os")),s11=xP();function t11(){try{let Y=process.cwd();while(Y!==uP.default.dirname(Y)){let X=uP.default.join(Y,".vercel");if(o11.default.existsSync(X))return Y;Y=uP.default.dirname(Y)}}catch(Y){throw new s11.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function e11(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(G50.default.platform()){case"darwin":return uP.default.join(G50.default.homedir(),"Library/Application Support");case"linux":return uP.default.join(G50.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var fD6=E((Mz8,yD6)=>{var{create:Y81,defineProperty:Zx,getOwnPropertyDescriptor:X81,getOwnPropertyNames:Q81,getPrototypeOf:J81}=Object,G81=Object.prototype.hasOwnProperty,W81=(Y,X)=>{for(var Q in X)Zx(Y,Q,{get:X[Q],enumerable:!0})},jD6=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Q81(X))if(!G81.call(Y,G)&&G!==Q)Zx(Y,G,{get:()=>X[G],enumerable:!(J=X81(X,G))||J.enumerable})}return Y},SD6=(Y,X,Q)=>(Q=Y!=null?Y81(J81(Y)):{},jD6(X||!Y||!Y.__esModule?Zx(Q,"default",{value:Y,enumerable:!0}):Q,Y)),Z81=(Y)=>jD6(Zx({},"__esModule",{value:!0}),Y),kD6={};W81(kD6,{isValidAccessToken:()=>V81,readAuthConfig:()=>H81,writeAuthConfig:()=>F81});yD6.exports=Z81(kD6);var gP=SD6(V0("fs")),vD6=SD6(V0("path")),K81=Kx();function _D6(){let Y=(0,K81.getVercelDataDir)();if(!Y)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return vD6.join(Y,"auth.json")}function H81(){try{let Y=_D6();if(!gP.existsSync(Y))return null;let X=gP.readFileSync(Y,"utf8");if(!X)return null;return JSON.parse(X)}catch(Y){return null}}function F81(Y){let X=_D6(),Q=vD6.dirname(X);if(!gP.existsSync(Q))gP.mkdirSync(Q,{mode:504,recursive:!0});gP.writeFileSync(X,JSON.stringify(Y,null,2),{mode:384})}function V81(Y){if(!Y.token)return!1;if(typeof Y.expiresAt!=="number")return!0;let X=Math.floor(Date.now()/1000);return Y.expiresAt>=X}});var uD6=E((Az8,xD6)=>{var{defineProperty:H50,getOwnPropertyDescriptor:$81,getOwnPropertyNames:q81}=Object,z81=Object.prototype.hasOwnProperty,B81=(Y,X)=>{for(var Q in X)H50(Y,Q,{get:X[Q],enumerable:!0})},U81=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of q81(X))if(!z81.call(Y,G)&&G!==Q)H50(Y,G,{get:()=>X[G],enumerable:!(J=$81(X,G))||J.enumerable})}return Y},D81=(Y)=>U81(H50({},"__esModule",{value:!0}),Y),hD6={};B81(hD6,{processTokenResponse:()=>M81,refreshTokenRequest:()=>w81});xD6.exports=D81(hD6);var Z50=V0("os"),O81="https://vercel.com",N81="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",bD6=`@vercel/oidc node-${process.version} ${(0,Z50.platform)()} (${(0,Z50.arch)()}) ${(0,Z50.hostname)()}`,K50=null;async function L81(){if(K50)return K50;let Y=`${O81}/.well-known/openid-configuration`,X=await fetch(Y,{headers:{"user-agent":bD6}});if(!X.ok)throw Error("Failed to discover OAuth endpoints");let Q=await X.json();if(!Q||typeof Q.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let J=Q.token_endpoint;return K50=J,J}async function w81(Y){let X=await L81();return await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":bD6},body:new URLSearchParams({client_id:N81,grant_type:"refresh_token",...Y})})}async function M81(Y){let X=await Y.json();if(!Y.ok){let Q=typeof X==="object"&&X&&"error"in X?String(X.error):"Token refresh failed";return[Error(Q)]}if(typeof X!=="object"||X===null)return[Error("Invalid token response")];if(typeof X.access_token!=="string")return[Error("Missing access_token in response")];if(X.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof X.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,X]}});var Kx=E((Tz8,pD6)=>{var{create:A81,defineProperty:Hx,getOwnPropertyDescriptor:T81,getOwnPropertyNames:P81,getPrototypeOf:E81}=Object,C81=Object.prototype.hasOwnProperty,I81=(Y,X)=>{for(var Q in X)Hx(Y,Q,{get:X[Q],enumerable:!0})},mD6=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of P81(X))if(!C81.call(Y,G)&&G!==Q)Hx(Y,G,{get:()=>X[G],enumerable:!(J=T81(X,G))||J.enumerable})}return Y},lD6=(Y,X,Q)=>(Q=Y!=null?A81(E81(Y)):{},mD6(X||!Y||!Y.__esModule?Hx(Q,"default",{value:Y,enumerable:!0}):Q,Y)),R81=(Y)=>mD6(Hx({},"__esModule",{value:!0}),Y),dD6={};I81(dD6,{assertVercelOidcTokenResponse:()=>F50,findProjectInfo:()=>v81,getTokenPayload:()=>f81,getVercelCliToken:()=>S81,getVercelDataDir:()=>j81,getVercelOidcToken:()=>k81,isExpired:()=>h81,loadToken:()=>y81,saveToken:()=>_81});pD6.exports=R81(dD6);var mP=lD6(V0("path")),T$=lD6(V0("fs")),MD=xP(),Fx=RD6(),wD=fD6(),gD6=uD6();function j81(){let X=(0,Fx.getUserDataDir)();if(!X)return null;return mP.join(X,"com.vercel.cli")}async function S81(){let Y=(0,wD.readAuthConfig)();if(!Y)return null;if((0,wD.isValidAccessToken)(Y))return Y.token||null;if(!Y.refreshToken)return(0,wD.writeAuthConfig)({}),null;try{let X=await(0,gD6.refreshTokenRequest)({refresh_token:Y.refreshToken}),[Q,J]=await(0,gD6.processTokenResponse)(X);if(Q||!J)return(0,wD.writeAuthConfig)({}),null;let G={token:J.access_token,expiresAt:Math.floor(Date.now()/1000)+J.expires_in};if(J.refresh_token)G.refreshToken=J.refresh_token;return(0,wD.writeAuthConfig)(G),G.token??null}catch(X){return(0,wD.writeAuthConfig)({}),null}}async function k81(Y,X,Q){let J=`https://api.vercel.com/v1/projects/${X}/token?source=vercel-oidc-refresh${Q?`&teamId=${Q}`:""}`,G=await fetch(J,{method:"POST",headers:{Authorization:`Bearer ${Y}`}});if(!G.ok)throw new MD.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let K=await G.json();return F50(K),K}function F50(Y){if(!Y||typeof Y!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in Y)||typeof Y.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function v81(){let Y=(0,Fx.findRootDir)();if(!Y)throw new MD.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let X=mP.join(Y,".vercel","project.json");if(!T$.existsSync(X))throw new MD.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let Q=JSON.parse(T$.readFileSync(X,"utf8"));if(typeof Q.projectId!=="string"&&typeof Q.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:Q.projectId,teamId:Q.orgId}}function _81(Y,X){let Q=(0,Fx.getUserDataDir)();if(!Q)throw new MD.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let J=mP.join(Q,"com.vercel.token",`${X}.json`),G=JSON.stringify(Y);T$.mkdirSync(mP.dirname(J),{mode:504,recursive:!0}),T$.writeFileSync(J,G),T$.chmodSync(J,432);return}function y81(Y){let X=(0,Fx.getUserDataDir)();if(!X)throw new MD.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=mP.join(X,"com.vercel.token",`${Y}.json`);if(!T$.existsSync(Q))return null;let J=JSON.parse(T$.readFileSync(Q,"utf8"));return F50(J),J}function f81(Y){let X=Y.split(".");if(X.length!==3)throw new MD.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let Q=X[1].replace(/-/g,"+").replace(/_/g,"/"),J=Q.padEnd(Q.length+(4-Q.length%4)%4,"=");return JSON.parse(Buffer.from(J,"base64").toString("utf8"))}function h81(Y){return Y.exp*1000<Date.now()}});var iD6=E((Pz8,nD6)=>{var{defineProperty:$50,getOwnPropertyDescriptor:b81,getOwnPropertyNames:x81}=Object,u81=Object.prototype.hasOwnProperty,g81=(Y,X)=>{for(var Q in X)$50(Y,Q,{get:X[Q],enumerable:!0})},m81=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of x81(X))if(!u81.call(Y,G)&&G!==Q)$50(Y,G,{get:()=>X[G],enumerable:!(J=b81(X,G))||J.enumerable})}return Y},l81=(Y)=>m81($50({},"__esModule",{value:!0}),Y),cD6={};g81(cD6,{refreshToken:()=>d81});nD6.exports=l81(cD6);var V50=xP(),P$=Kx();async function d81(){let{projectId:Y,teamId:X}=(0,P$.findProjectInfo)(),Q=(0,P$.loadToken)(Y);if(!Q||(0,P$.isExpired)((0,P$.getTokenPayload)(Q.token))){let J=await(0,P$.getVercelCliToken)();if(!J)throw new V50.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!Y)throw new V50.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(Q=await(0,P$.getVercelOidcToken)(J,Y,X),!Q)throw new V50.VercelOidcTokenError("Failed to refresh OIDC token");(0,P$.saveToken)(Q,Y)}process.env.VERCEL_OIDC_TOKEN=Q.token;return}});var oD6=E((Ez8,rD6)=>{var{defineProperty:z50,getOwnPropertyDescriptor:p81,getOwnPropertyNames:c81}=Object,n81=Object.prototype.hasOwnProperty,i81=(Y,X)=>{for(var Q in X)z50(Y,Q,{get:X[Q],enumerable:!0})},a81=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of c81(X))if(!n81.call(Y,G)&&G!==Q)z50(Y,G,{get:()=>X[G],enumerable:!(J=p81(X,G))||J.enumerable})}return Y},r81=(Y)=>a81(z50({},"__esModule",{value:!0}),Y),aD6={};i81(aD6,{getVercelOidcToken:()=>t81,getVercelOidcTokenSync:()=>q50});rD6.exports=r81(aD6);var o81=Q50(),s81=xP();async function t81(){let Y="",X;try{Y=q50()}catch(Q){X=Q}try{let[{getTokenPayload:Q,isExpired:J},{refreshToken:G}]=await Promise.all([await Promise.resolve().then(() => y4(Kx())),await Promise.resolve().then(() => y4(iD6()))]);if(!Y||J(Q(Y)))await G(),Y=q50()}catch(Q){let J=X instanceof Error?X.message:"";if(Q instanceof Error)J=`${J}
273
273
  ${Q.message}`;if(J)throw new s81.VercelOidcTokenError(J);throw Q}return Y}function q50(){let Y=(0,o81.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!Y)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return Y}});var U50=E((Cz8,eD6)=>{var{defineProperty:B50,getOwnPropertyDescriptor:e81,getOwnPropertyNames:Y91}=Object,X91=Object.prototype.hasOwnProperty,Q91=(Y,X)=>{for(var Q in X)B50(Y,Q,{get:X[Q],enumerable:!0})},J91=(Y,X,Q,J)=>{if(X&&typeof X==="object"||typeof X==="function"){for(let G of Y91(X))if(!X91.call(Y,G)&&G!==Q)B50(Y,G,{get:()=>X[G],enumerable:!(J=e81(X,G))||J.enumerable})}return Y},G91=(Y)=>J91(B50({},"__esModule",{value:!0}),Y),tD6={};Q91(tD6,{getContext:()=>W91.getContext,getVercelOidcToken:()=>sD6.getVercelOidcToken,getVercelOidcTokenSync:()=>sD6.getVercelOidcTokenSync});eD6.exports=G91(tD6);var sD6=oD6(),W91=Q50()});var UK=y4(u0(),1),cq=y4(Z2(),1);var kO0=y4(vU0(),1);var Fg=y4(TD0(),1);var CD0=y4(v$(),1);function PD0(Y){if(Y>=48&&Y<=57)return Y-48;if(Y>=97&&Y<=102)return Y-87;return Y-55}function C2(Y){let X=new Uint8Array(Y.length/2),Q=0;for(let J=0;J<Y.length;J+=2){let G=PD0(Y.charCodeAt(J)),K=PD0(Y.charCodeAt(J+1));X[Q++]=G<<4|K}return X}function ID0(Y){let X=BigInt(1e9);return BigInt(Math.trunc(Y[0]))*X+BigInt(Math.trunc(Y[1]))}function Ef6(Y){let X=Number(BigInt.asUintN(32,Y)),Q=Number(BigInt.asUintN(32,Y>>BigInt(32)));return{low:X,high:Q}}function RD0(Y){let X=ID0(Y);return Ef6(X)}function Cf6(Y){return ID0(Y).toString()}var If6=typeof BigInt<"u"?Cf6:CD0.hrTimeToNanoseconds;function ED0(Y){return Y}function jD0(Y){if(Y===void 0)return;return C2(Y)}var Rf6={encodeHrTime:RD0,encodeSpanContext:C2,encodeOptionalSpanContext:jD0};function SD0(Y){if(Y===void 0)return Rf6;let X=Y.useLongBits??!0,Q=Y.useHex??!1;return{encodeHrTime:X?RD0:If6,encodeSpanContext:Q?ED0:C2,encodeOptionalSpanContext:Q?ED0:jD0}}function kD0(Y){let X={attributes:jf6(Y.attributes),droppedAttributesCount:0},Q=Y.schemaUrl;if(Q&&Q!=="")X.schemaUrl=Q;return X}function vD0(Y){return{name:Y.name,version:Y.version}}function jf6(Y){return Object.keys(Y).map((X)=>I2(X,Y[X]))}function I2(Y,X){return{key:Y,value:R2(X)}}function R2(Y){let X=typeof Y;if(X==="string")return{stringValue:Y};if(X==="number"){if(!Number.isInteger(Y))return{doubleValue:Y};return{intValue:Y}}if(X==="boolean")return{boolValue:Y};if(Y instanceof Uint8Array)return{bytesValue:Y};if(Array.isArray(Y))return{arrayValue:{values:Y.map(R2)}};if(X==="object"&&Y!=null)return{kvlistValue:{values:Object.entries(Y).map(([Q,J])=>I2(Q,J))}};return{}}function _D0(Y,X){let Q=SD0(X);return{resourceLogs:kf6(Y,Q)}}function Sf6(Y){let X=new Map;for(let Q of Y){let{resource:J,instrumentationScope:{name:G,version:K="",schemaUrl:W=""}}=Q,Z=X.get(J);if(!Z)Z=new Map,X.set(J,Z);let H=`${G}@${K}:${W}`,F=Z.get(H);if(!F)F=[],Z.set(H,F);F.push(Q)}return X}function kf6(Y,X){let Q=Sf6(Y);return Array.from(Q,([J,G])=>{let K=kD0(J);return{resource:K,scopeLogs:Array.from(G,([,W])=>{return{scope:vD0(W[0].instrumentationScope),logRecords:W.map((Z)=>vf6(Z,X)),schemaUrl:W[0].instrumentationScope.schemaUrl}}),schemaUrl:K.schemaUrl}})}function vf6(Y,X){return{timeUnixNano:X.encodeHrTime(Y.hrTime),observedTimeUnixNano:X.encodeHrTime(Y.hrTimeObserved),severityNumber:_f6(Y.severityNumber),severityText:Y.severityText,body:R2(Y.body),eventName:Y.eventName,attributes:yf6(Y.attributes),droppedAttributesCount:Y.droppedAttributesCount,flags:Y.spanContext?.traceFlags,traceId:X.encodeOptionalSpanContext(Y.spanContext?.traceId),spanId:X.encodeOptionalSpanContext(Y.spanContext?.spanId)}}function _f6(Y){return Y}function yf6(Y){return Object.keys(Y).map((X)=>I2(X,Y[X]))}var ff6=Fg.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse,hf6=Fg.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest,j2={serializeRequest:(Y)=>{let X=_D0(Y);return hf6.encode(X).finish()},deserializeResponse:(Y)=>{return ff6.decode(Y)}};var v2=y4(zg(),1);class f$ extends kO0.OTLPExporterBase{constructor(Y={}){super(v2.createOtlpHttpExportDelegate(v2.convertLegacyHttpOptions(Y,"LOGS","v1/logs",{"Content-Type":"application/x-protobuf"}),j2))}}var Lp0=y4(Um(),1),wp0=y4(tm(),1),Mp0=y4(Nj0(),1);var IG=y4(u0(),1);var Ro6=globalThis.fetch;async function jo6(Y,X){let Q,J;if(Y instanceof Request)Q=new URL(Y.url),J=X?.method??Y.method;else if(Y instanceof URL)Q=Y,J=X?.method??"GET";else Q=new URL(Y),J=X?.method??"GET";let G=`${J} ${Q.host}`;return Jq.startActiveSpan(G,{kind:IG.SpanKind.CLIENT,attributes:{"http.request.method":J,"url.full":Q.href,"url.scheme":Q.protocol.replace(":",""),"url.path":Q.pathname,"url.query":Q.search||void 0,"server.address":Q.hostname,"server.port":Q.port?Number(Q.port):void 0}},async(K)=>{try{let W=new Headers(X?.headers??(Y instanceof Request?Y.headers:{}));IG.propagation.inject(IG.context.active(),W,{set:(F,V,$)=>F.set(V,$)});let Z={...X,headers:W},H=await Ro6(Y,Z);if(K.setAttribute("http.response.status_code",H.status),H.status>=400)K.setStatus({code:IG.SpanStatusCode.ERROR,message:`HTTP ${H.status}`});else K.setStatus({code:IG.SpanStatusCode.OK});return H}catch(W){throw K.recordException(W),K.setStatus({code:IG.SpanStatusCode.ERROR,message:W instanceof Error?W.message:"Fetch failed"}),W}finally{K.end()}})}function Lj0(){globalThis.fetch=jo6}var wj0=y4(u0(),1),y9=y4(v$(),1);class Sl{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(Y,X){if(this._exporter=Y,this._maxExportBatchSize=X?.maxExportBatchSize??y9.getNumberFromEnv("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")??512,this._maxQueueSize=X?.maxQueueSize??y9.getNumberFromEnv("OTEL_BLRP_MAX_QUEUE_SIZE")??2048,this._scheduledDelayMillis=X?.scheduledDelayMillis??y9.getNumberFromEnv("OTEL_BLRP_SCHEDULE_DELAY")??5000,this._exportTimeoutMillis=X?.exportTimeoutMillis??y9.getNumberFromEnv("OTEL_BLRP_EXPORT_TIMEOUT")??30000,this._shutdownOnce=new y9.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize)wj0.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize}onEmit(Y){if(this._shutdownOnce.isCalled)return;this._addToBuffer(Y)}forceFlush(){if(this._shutdownOnce.isCalled)return this._shutdownOnce.promise;return this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(Y){if(this._finishedLogRecords.length>=this._maxQueueSize)return;this._finishedLogRecords.push(Y),this._maybeStartTimer()}_flushAll(){return new Promise((Y,X)=>{let Q=[],J=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let G=0;G<J;G++)Q.push(this._flushOneBatch());Promise.all(Q).then(()=>{Y()}).catch(X)})}_flushOneBatch(){if(this._clearTimer(),this._finishedLogRecords.length===0)return Promise.resolve();return y9.callWithTimeout(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis)}_maybeStartTimer(){if(this._isExporting)return;let Y=()=>{this._isExporting=!0,this._flushOneBatch().then(()=>{if(this._isExporting=!1,this._finishedLogRecords.length>0)this._clearTimer(),this._maybeStartTimer()}).catch((X)=>{this._isExporting=!1,y9.globalErrorHandler(X)})};if(this._finishedLogRecords.length>=this._maxExportBatchSize)return Y();if(this._timer!==void 0)return;if(this._timer=setTimeout(()=>Y(),this._scheduledDelayMillis),typeof this._timer!=="number")this._timer.unref()}_clearTimer(){if(this._timer!==void 0)clearTimeout(this._timer),this._timer=void 0}_export(Y){let X=()=>y9.internal._export(this._exporter,Y).then((J)=>{if(J.code!==y9.ExportResultCode.SUCCESS)y9.globalErrorHandler(J.error??Error(`BatchLogRecordProcessor: log record export failed (status ${J})`))}).catch(y9.globalErrorHandler),Q=[];for(let J=0;J<Y.length;J++){let G=Y[J].resource;if(G.asyncAttributesPending&&typeof G.waitForAsyncAttributes==="function")Q.push(G.waitForAsyncAttributes())}if(Q.length===0)return X();else return Promise.all(Q).then(X,y9.globalErrorHandler)}}class Gq extends Sl{onShutdown(){}}var Ap0=y4(Dp0(),1);var dG;(function(Y){Y[Y.NOT_RECORD=0]="NOT_RECORD",Y[Y.RECORD=1]="RECORD",Y[Y.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(dG||(dG={}));var bI=y4(u0(),1);var pn=async(Y,X)=>{let Q=Y.req.raw,J=new URL(Q.url),G=Np0(Q),K=cn(Q),W={"http.request.url":Q.url,"http.request.method":Q.method,"http.request.body.size":Q.headers.get("content-length")??void 0,"url.scheme":J.protocol.replace(":",""),"server.address":J.host,"url.query":J.search||void 0,"url.path":J.pathname,"user_agent.original":Q.headers.get("user-agent")??void 0,"request.internal":Q.headers.has("traceparent"),...K?{"trace.debug.id":K}:{}};await Jq.startActiveSpan(`${Q.method} ${J.pathname}`,{attributes:W},G,async(Z)=>{Y.set("rootSpan",Z);try{await X()}catch(H){Z.recordException(H),Z.setStatus({code:bI.SpanStatusCode.ERROR});let F=typeof H==="object"&&H&&"message"in H?String(H.message):JSON.stringify(H);throw console.error("error: ",F,W),H}finally{let H=Y.res?.status??500,F=H>=500;Z.setStatus({code:F?bI.SpanStatusCode.ERROR:bI.SpanStatusCode.OK}),Z.setAttribute("http.response.status_code",H);let V=Y.get("meshContext");if(V){if(V.auth.user?.id)Z.setAttribute("mesh.user.id",V.auth.user.id);if(V.auth.apiKey?.id)Z.setAttribute("mesh.api_key.id",V.auth.apiKey.id);if(V.organization?.id)Z.setAttribute("mesh.organization.id",V.organization.id)}if(K)Op0(Y.res.headers,K);Z.end()}})};var EK4="__d",Tp0=UK.createContextKey("Current request"),CK4=0.1,cn=(Y)=>{let Q=new URL(Y.url).searchParams.get(EK4);if(Q==="")return crypto.randomUUID();if(!Q)Q=Y.headers.get("x-trace-debug-id");return Q},Op0=(Y,X)=>{try{Y.set("x-trace-debug-id",X)}catch{}};class Pp0{inner;constructor(Y){this.inner=Y}shouldSample(Y,X,Q,J,G,K){let W=Y.getValue(Tp0);if(!W){if(this.inner)return this.inner.shouldSample(Y,X,Q,J,G,K);return{decision:dG.RECORD_AND_SAMPLED}}let Z=cn(W);if(Z)return{decision:dG.RECORD_AND_SAMPLED,attributes:{"trace.debug.id":Z}};if(this.inner){let H=this.inner.shouldSample(Y,X,Q,J,G,K);if(H.decision===dG.RECORD_AND_SAMPLED){let F=crypto.randomUUID();H.attributes={...H.attributes??{},"trace.debug.id":F}}return H}return{decision:dG.NOT_RECORD}}toString(){return"DebugSampler"}}class Ep0{ratio;constructor(Y){this.ratio=Y}shouldSample(){if(Math.random()<this.ratio)return{decision:dG.RECORD_AND_SAMPLED};return{decision:dG.NOT_RECORD}}toString(){return`RatioSampler(${this.ratio})`}}var nn=new Lp0.PrometheusExporter({preventServerStart:!0}),IK4=new Pp0(new Ep0(CK4)),RK4=new Ap0.NodeSDK({serviceName:process.env.OTEL_SERVICE_NAME??"mesh",traceExporter:new wp0.OTLPTraceExporter,metricReader:nn,sampler:IK4,logRecordProcessors:[new Gq(new f$)],instrumentations:[new Mp0.RuntimeNodeInstrumentation]});RK4.start();Lj0();var Jq=UK.trace.getTracer("mesh","1.0.0"),xI=UK.metrics.getMeter("mesh","1.0.0"),jK4=cq.logs.getLogger("mesh","1.0.0"),an=(Y,X,Q)=>{let J={},G=Q,K=Q[Q.length-1];if(K!==null&&typeof K==="object"&&!Array.isArray(K)&&!(K instanceof Error)&&Object.getPrototypeOf(K)===Object.prototype)J=K,G=Q.slice(0,-1);let W=G.map((Z)=>{if(Z instanceof Error)return`${Z.name}: ${Z.message}`;if(typeof Z==="object")try{return JSON.stringify(Z)}catch{return"[Object]"}return String(Z)}).join(" ");jK4.emit({severityNumber:Y,severityText:X,body:W,attributes:{"log.source":"console",...J}})},rn={error:console.error.bind(console),warn:console.warn.bind(console),debug:console.debug.bind(console)};console.error=(...Y)=>{an(cq.SeverityNumber.ERROR,"ERROR",Y),rn.error(...Y)};console.warn=(...Y)=>{an(cq.SeverityNumber.WARN,"WARN",Y),rn.warn(...Y)};console.debug=(...Y)=>{an(cq.SeverityNumber.DEBUG,"DEBUG",Y),rn.debug(...Y)};var Np0=(Y)=>{return UK.context.active().setValue(Tp0,Y)};var DK=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 Cp0=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],SK4=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/,kK4=(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)=>!SK4.test(W));if(K.length>0)throw new DK(400,{message:`Invalid Connection header value: ${K.join(", ")}`});G.forEach((W)=>{Q.delete(W)})}}return Cp0.forEach((J)=>{Q.delete(J)}),{method:Y.method,body:Y.body,duplex:Y.body?"half":void 0,headers:Q,signal:Y.signal}},vK4=(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},Ip0=async(Y,X)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...K}=X instanceof Request?{raw:X}:X??{},W=new Request(Y,{...kK4(Q,G),...vK4(K)});W.headers.delete("accept-encoding");let Z=await(J||fetch)(W),H=new Headers(Z.headers);if(Cp0.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 Rp0=(Y)=>(X)=>{let Q=new URL(X.req.raw.url),J=new URL(Y);return J.pathname=Q.pathname,J.search=Q.search,Ip0(J,{raw:X.req.raw,headers:{...X.req.raw.headers}})};import{resolve as hN,dirname as _K4,join as yK4,extname as fK4}from"path";var hK4="http://localhost:4000",bK4="./dist/client";function xK4(Y,X){let Q=hN(X),J=hN(Y);return J===Q||J.startsWith(Q+"/")}function uK4({requestPath:Y,clientDir:X}){let Q=Y.startsWith("/")?Y.slice(1):Y,J=hN(X,Q);if(!xK4(J,X))return null;return J}function jp0(Y,X="../client"){let Q=new URL(Y),J=_K4(Q.pathname);return hN(J,X)}function Sp0(Y={}){let{env:X="production",devServerUrl:Q=hK4,clientDir:J=bK4,isServerPath:G=()=>!1}=Y;if(X==="development"){let K=Rp0(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=uK4({requestPath:H,clientDir:J});if(!F)return null;let V=yK4(F,"index.html"),$=hN(J,"index.html"),q=W.headers.get("accept"),D=q?.includes("text/html")||q?.includes("*/*")&&["",".html"].includes(fK4(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 kp0="https://api.decocms.com/mcp/registry";function vp0(Y){if(!Y)return!1;try{return new URL(Y).host==="api.decocms.com"&&Y!=="https://api.decocms.com/mcp/registry"}catch{return!1}}_J();var dL6=y4(Um(),1);var D00=(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 re0=Symbol();var oe0=async(Y,X=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=X,K=(Y instanceof pv?Y.raw.headers:Y.headers).get("Content-Type");if(K?.startsWith("multipart/form-data")||K?.startsWith("application/x-www-form-urlencoded"))return cM4(Y,{all:Q,dot:J});return{}};async function cM4(Y,X){let Q=await Y.formData();if(Q)return nM4(Q,X);return{}}function nM4(Y,X){let Q=Object.create(null);if(Y.forEach((J,G)=>{if(!(X.all||G.endsWith("[]")))Q[G]=J;else iM4(Q,G,J)}),X.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))aM4(Q,J,G),delete Q[J]});return Q}var iM4=(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]},aM4=(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 N00=(Y)=>{let X=Y.split("/");if(X[0]==="")X.shift();return X},se0=(Y)=>{let{groups:X,path:Q}=rM4(Y),J=N00(Q);return oM4(J,X)},rM4=(Y)=>{let X=[];return Y=Y.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return X.push([G,Q]),G}),{groups:X,path:Y}},oM4=(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},cv={},te0=(Y,X)=>{if(Y==="*")return"*";let Q=Y.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${Y}#${X}`;if(!cv[J])if(Q[2])cv[J]=X&&X[0]!==":"&&X[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${X})`)]:[Y,Q[1],new RegExp(`^${Q[2]}$`)];else cv[J]=[Y,Q[1],!0];return cv[J]}return null},HB=(Y,X)=>{try{return X(Y)}catch{return Y.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return X(Q)}catch{return Q}})}},sM4=(Y)=>HB(Y,decodeURI),L00=(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 sM4(W.includes("%25")?W.replace(/%25/g,"%2525"):W)}else if(G===63)break}return X.slice(Q,J)};var ee0=(Y)=>{let X=L00(Y);return X.length>1&&X.at(-1)==="/"?X.slice(0,-1):X},aF=(Y,X,...Q)=>{if(Q.length)X=aF(X,...Q);return`${Y?.[0]==="/"?"":"/"}${Y}${X==="/"?"":`${Y?.at(-1)==="/"?"":"/"}${X?.[0]==="/"?X.slice(1):X}`}`},nv=(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)},O00=(Y)=>{if(!/[%+]/.test(Y))return Y;if(Y.indexOf("+")!==-1)Y=Y.replace(/\+/g," ");return Y.indexOf("%")!==-1?HB(Y,OM):Y},Y06=(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 O00(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=O00(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=O00(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},X06=Y06,Q06=(Y,X)=>{return Y06(Y,X,!0)},OM=decodeURIComponent;var J06=(Y)=>HB(Y,OM),pv=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)?J06(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)?J06(J):J}return Y}#W(Y){return this.#X[1]?this.#X[1][Y]:Y}query(Y){return X06(this.url,Y)}queries(Y){return Q06(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 oe0(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[re0](){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 iv={Stringify:1,BeforeStream:2,Stream:3},tM4=(Y,X)=>{let Q=new String(Y);return Q.isEscaped=!0,Q.callbacks=X,Q};var NM=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)=>NM(H,X,!1,J,G))).then(()=>G[0]));if(Q)return tM4(await W,K);else return W};var G06="text/plain; charset=UTF-8",w00=(Y,X)=>{return{"Content-Type":Y,...X}},W06=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 pv(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,w00(G06,Q))};json=(Y,X,Q)=>{return this.#V(JSON.stringify(Y),X,w00("application/json",Q))};html=(Y,X,Q)=>{let J=(G)=>this.#V(G,X,w00("text/html; charset=UTF-8",Q));return typeof Y==="object"?NM(Y,iv.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 Y8="ALL",Z06="all",K06=["get","post","put","delete","options","patch"],av="Can not add a route since the matcher is already built.",rv=class extends Error{};var H06="__COMPOSED_HANDLER";var eM4=(Y)=>{return Y.text("404 Not Found",404)},F06=(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)},V06=class Y{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#Y="/";routes=[];constructor(X={}){[...K06,Z06].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(Y8,this.#Y,Z)}),this};let{strict:J,...G}=X;Object.assign(this,G),this.getPath=J??!0?X.getPath??L00:ee0}#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=eM4;errorHandler=F06;route(X,Q){let J=this.basePath(X);return Q.routes.map((G)=>{let K;if(Q.errorHandler===F06)K=G.handler;else K=async(W,Z)=>(await D00([],Q.errorHandler)(W,()=>G.handler(W,Z))).res,K[H06]=G.handler;J.#J(G.method,G.path,K)}),this}basePath(X){let Q=this.#X();return Q._basePath=aF(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=aF(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(Y8,aF(X,"*"),Z),this}#J(X,Q,J){X=X.toUpperCase(),Q=aF(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 W06(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=D00(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${aF("/",X)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(X)=>{X.respondWith(this.#G(X.request,X,void 0,X.request.method))})}};var LM=[];function ov(Y,X){let Q=this.buildAllMatchers(),J=(G,K)=>{let W=Q[G]||Q[Y8],Z=W[2][K];if(Z)return Z;let H=K.match(W[0]);if(!H)return[[],LM];let F=H.indexOf("",1);return[W[1][F],H]};return this.match=J,J(Y,X)}var sv="[^/]+",wM=".*",MM="(?:|/.*)",rF=Symbol(),YA4=new Set(".\\+*[^]$()");function XA4(Y,X){if(Y.length===1)return X.length===1?Y<X?-1:1:-1;if(X.length===1)return 1;if(Y===wM||Y===MM)return 1;else if(X===wM||X===MM)return-1;if(Y===sv)return 1;else if(X===sv)return-1;return Y.length===X.length?Y<X?-1:1:X.length-Y.length}var $06=class Y{#Y;#X;#Q=Object.create(null);insert(X,Q,J,G,K){if(X.length===0){if(this.#Y!==void 0)throw rF;if(K)return;this.#Y=Q;return}let[W,...Z]=X,H=W==="*"?Z.length===0?["","",wM]:["","",sv]:W==="/*"?["","",MM]:W.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),F;if(H){let V=H[1],$=H[2]||sv;if(V&&H[2]){if($===".*")throw rF;if($=$.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test($))throw rF}if(F=this.#Q[$],!F){if(Object.keys(this.#Q).some((q)=>q!==wM&&q!==MM))throw rF;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!==wM&&V!==MM))throw rF;if(K)return;F=this.#Q[W]=new Y}F.insert(Z,Q,J,G,K)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(XA4).map((J)=>{let G=this.#Q[J];return(typeof G.#X==="number"?`(${J})@${G.#X}`:YA4.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 q06=class{#Y={varIndex:0};#X=new $06;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 QA4=[/^$/,[],Object.create(null)],z06=Object.create(null);function B06(Y){return z06[Y]??=new RegExp(Y==="*"?"":`^${Y.replace(/\/\*$|([.\\+*[^\]$()])/g,(X,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function JA4(){z06=Object.create(null)}function GA4(Y){let X=new q06,Q=[];if(Y.length===0)return QA4;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)]),LM];else V++;let O;try{O=X.insert(B,V,q)}catch(L){throw L===rF?new rv(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 FB(Y,X){if(!Y)return;for(let Q of Object.keys(Y).sort((J,G)=>G.length-J.length))if(B06(Q).test(X))return[...Y[Q]];return}var tv=class{name="RegExpRouter";#Y;#X;constructor(){this.#Y={[Y8]:Object.create(null)},this.#X={[Y8]:Object.create(null)}}add(Y,X,Q){let J=this.#Y,G=this.#X;if(!J||!G)throw Error(av);if(!J[Y])[J,G].forEach((Z)=>{Z[Y]=Object.create(null),Object.keys(Z[Y8]).forEach((H)=>{Z[Y][H]=[...Z[Y8][H]]})});if(X==="/*")X="*";let K=(X.match(/\/:/g)||[]).length;if(/\*$/.test(X)){let Z=B06(X);if(Y===Y8)Object.keys(J).forEach((H)=>{J[H][X]||=FB(J[H],X)||FB(J[Y8],X)||[]});else J[Y][X]||=FB(J[Y],X)||FB(J[Y8],X)||[];Object.keys(J).forEach((H)=>{if(Y===Y8||Y===H)Object.keys(J[H]).forEach((F)=>{Z.test(F)&&J[H][F].push([Q,K])})}),Object.keys(G).forEach((H)=>{if(Y===Y8||Y===H)Object.keys(G[H]).forEach((F)=>Z.test(F)&&G[H][F].push([Q,K]))});return}let W=nv(X)||[X];for(let Z=0,H=W.length;Z<H;Z++){let F=W[Z];Object.keys(G).forEach((V)=>{if(Y===Y8||Y===V)G[V][F]||=[...FB(J[V],F)||FB(J[Y8],F)||[]],G[V][F].push([Q,K-H+Z+1])})}}match=ov;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,JA4(),Y}#Q(Y){let X=[],Q=Y===Y8;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!==Y8)X.push(...Object.keys(J[Y8]).map((K)=>[K,J[Y8][K]]))}),!Q)return null;else return GA4(X)}};var WA4=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[Y8],K={};for(let W in G[2])K[W]=[G[2][W][0].slice(),LM];this.#Y[Y]=[G[0],G[1].map((W)=>Array.isArray(W)?W.slice():0),K]}if(X==="/*"||X==="*"){let G=[Q,{}];if(Y===Y8)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===Y8)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=ov};var M00=class{name="SmartRouter";#Y=[];#X=[];constructor(Y){this.#Y=Y.routers}add(Y,X,Q){if(!this.#X)throw Error(av);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 rv)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 AM=Object.create(null),U06=class Y{#Y;#X;#Q;#J=0;#W=AM;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=se0(Q),W=[];for(let Z=0,H=K.length;Z<H;Z++){let F=K[Z],V=K[Z+1],$=te0(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[Y8],V={};if(F!==void 0){if(F.params=Object.create(null),K.push(F),J!==AM||G&&G!==AM)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=AM;let K=[this],W=N00(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===AM?{}:{...O.#W};if(T==="*"){let y=O.#X["*"];if(y)J.push(...this.#G(y,X,O.#W)),y.#W=P,q.push(y);continue}let[A,R,j]=T;if(!V&&!(j instanceof RegExp))continue;let S=O.#X[A],_=W.slice(H).join("/");if(j instanceof RegExp){let y=j.exec(_);if(y){if(P[R]=y[0],J.push(...this.#G(S,X,O.#W,P)),Object.keys(S.#X).length){S.#W=P;let f=y[0].match(/\//)?.length??0;(Z[f]||=[]).push(S)}continue}}if(j===!0||j.test(V))if(P[R]=V,$){if(J.push(...this.#G(S,X,P,O.#W)),S.#X["*"])J.push(...this.#G(S.#X["*"],X,P,O.#W))}else S.#W=P,q.push(S)}}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 A00=class{name="TrieRouter";#Y;constructor(){this.#Y=new U06}add(Y,X,Q){let J=nv(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 Y9=class extends V06{constructor(Y={}){super(Y);this.router=Y.router??new M00({routers:[new tv,new A00]})}};var ZA4=/^[\w!#$%&'*.^`|~+-]+$/,KA4=/^[ !#-:<-[\]-~]*$/,T00=(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||!ZA4.test(W))continue;let Z=G.substring(K+1).trim();if(Z.startsWith('"')&&Z.endsWith('"'))Z=Z.slice(1,-1);if(KA4.test(Z)){if(J[W]=Z.indexOf("%")!==-1?HB(Z,OM):Z,X)break}}return J};var D06=(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 T00(J,K)[K]}if(!J)return{};return T00(J)};var O06=(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})}};function HA4(){let{process:Y,Deno:X}=globalThis;return!(typeof X?.noColor==="boolean"?X.noColor:Y!==void 0?"NO_COLOR"in Y?.env:!1)}async function N06(){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}})():!HA4())}var FA4=(Y)=>{let[X,Q]=[",","."];return Y.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+X)).join(Q)},VA4=(Y)=>{let X=Date.now()-Y;return FA4([X<1000?X+"ms":Math.round(X/1000)+"s"])},$A4=async(Y)=>{if(await N06())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}`};async function L06(Y,X,Q,J,G=0,K){let W=X==="<--"?`${X} ${Q} ${J}`:`${X} ${Q} ${J} ${await $A4(G)} ${K}`;Y(W)}var w06=(Y=console.log)=>{return async function(Q,J){let{method:G,url:K}=Q.req,W=K.slice(K.indexOf("/",8));await L06(Y,"<--",G,W);let Z=Date.now();await J(),await L06(Y,"-->",G,W,Q.res.status,VA4(Z))}};var M06=()=>{try{return performance.now()}catch{}return Date.now()},P00=(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)VB(J,"total",X.totalDescription);if(await G(),X.total)oF(J,"total");if(X.autoEnd)W.forEach((H,F)=>oF(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:"*")}}},A06=(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)}},VB=(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:M06()})},oF=(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=M06()-W;A06(Y,X,Z,K,Q),J.timers.delete(X)};var E00=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search available tools by name or description",category:"Code Execution"},{name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools",category:"Code Execution"},{name:"CODE_EXECUTION_RUN_CODE",description:"Run JavaScript code in a sandbox with tool access",category:"Code Execution",dangerous:!0},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"}];function TM(){let Y={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],"Code Execution":[]};for(let X of E00)Y[X.category]?.push(X);return Y}var qA4=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",zA4="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+qA4+"]*",BA4=new RegExp("^"+zA4+"$");function T06(Y,X){let Q=[],J=X.exec(Y);while(J){let G=[];G.startIndex=X.lastIndex-J[0].length;let K=J.length;for(let W=0;W<K;W++)G.push(J[W]);Q.push(G),J=X.exec(Y)}return Q}var C00=function(Y){let X=BA4.exec(Y);return!(X===null||typeof X>"u")};var UA4={allowBooleanAttributes:!1,unpairedTags:[]};function R06(Y,X){X=Object.assign({},UA4,X);let Q=[],J=!1,G=!1;if(Y[0]==="\uFEFF")Y=Y.substr(1);for(let K=0;K<Y.length;K++)if(Y[K]==="<"&&Y[K+1]==="?"){if(K+=2,K=E06(Y,K),K.err)return K}else if(Y[K]==="<"){let W=K;if(K++,Y[K]==="!"){K=C06(Y,K);continue}else{let Z=!1;if(Y[K]==="/")Z=!0,K++;let H="";for(;K<Y.length&&Y[K]!==">"&&Y[K]!==" "&&Y[K]!=="\t"&&Y[K]!==`
@@ -1048,7 +1048,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
1048
1048
  <h2>You've been invited!</h2>
1049
1049
  <p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
1050
1050
  <p><a href="${G}">Click here to accept the invitation</a></p>
1051
- `})}}}var _61=[wY0({organizationCreation:{afterCreate:async(Y)=>{await lz6(Y.organization.id,Y.member.userId)}},ac:ib,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:dz6,resourceNameValidation:(Y)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Y)}}},roles:{user:S61,admin:k61,owner:v61},sendInvitationEmail:az6}),fY0({loginPage:"/login",oidcConfig:{scopes:iz6,metadata:{scopes_supported:iz6},loginPage:"/login"}}),yY0({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}}),TY0({defaultRole:"user",adminRoles:["admin","owner"]}),uY0(),CY0({jwt:{expirationTime:"5m"}}),wW6(F9.ssoConfig?pz6(F9.ssoConfig):void 0),...F9.magicLinkConfig&&F9.emailProviders&&F9.emailProviders.length>0?[xY0(d36(F9.magicLinkConfig,F9.emailProviders))]:[]],y61=PX0(),f61=l36(y61),vZ=k90({baseURL:ZG(),database:f61,emailAndPassword:{enabled:!0},...F9,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:_61,databaseHooks:{user:{create:{after:async(Y)=>{if(yT.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} ${I61()}`,K=C61(G);try{await vZ.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}}}}}}}});iQ();import{randomBytes as h61}from"crypto";var RP=null;function rz6(){if(RP)return RP;let Y=process.env.MESH_JWT_SECRET??F9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)RP=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),RP=new Uint8Array(h61(32));return RP}async function oz6(Y,X="5m"){let Q=rz6();return await new UQ(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(X).sign(Q)}async function sz6(Y){try{let X=rz6(),{payload:Q}=await D8(Y,X);return Q}catch{return}}AZ();_J();class SJ0{db;constructor(Y){this.db=Y}async create(Y,X,Q){let J=H9("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:H9("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&&hW(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{...zM(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{...zM(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:H9("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}}import{sql as ab}from"kysely";class kJ0{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}}AZ();class vJ0{db;redactor;databaseType;constructor(Y,X="sqlite"){this.db=Y;this.redactor=new kJ0,this.databaseType=X}jsonExtract(Y,X){if(this.databaseType==="postgres")return ab`(${ab.ref(Y)}::jsonb)->>${X}`;let Q=`$.${X}`;return ab`json_extract(${ab.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||H9("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}}}class _J0{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 yJ0{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 tz6="mcp.mesh";class ez6 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}}class fJ0 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}}class Y3{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 ez6("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 fJ0("No resources specified for access check");for(let Q of X)if(await this.checkResource(Q)){this.grant();return}throw new fJ0(`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[tz6]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}MZ();Nb();qM();dQ0();async function YB6(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"}}}cb();async function jP(Y,X,Q){let J=Y.id,G=lQ0(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 oz6({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 SZ(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 YB6(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}iX0();function XB6(Y){let X=new oT({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}async function QB6(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(!J$(G))throw Error("STDIO connection missing parameters");let K=XB6({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 jP(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new iK(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 jP(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new Z$(new URL(Y.connection_url),{requestInit:{headers:G}});return X.getOrCreateClient(W,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}_J();c0();q$();c0();q$();XB();class JB6{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 U$(Y){return new JB6(Y)}async function b61(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 GB6(Y){let X=[];for(let[,Q]of Y)X.push(Q.close().catch(()=>{}));await Promise.all(X)}class UD extends vJ{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=U$(()=>b61(this.options.connections,this.ctx)),this._cachedTools=U$(()=>this.loadCache("tools")),this._cachedResources=U$(()=>this.loadCache("resources")),this._cachedPrompts=U$(()=>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 GB6(Y)}async close(){let Y=await this._clients;if(Y)await GB6(Y);await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions}}var WB6=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")}),x61=z.toJSONSchema(WB6),ZB6=z.object({tools:z.array(z.string()).min(1).describe("Array of tool names to get detailed schemas for")}),u61=z.toJSONSchema(ZB6);class SP extends UD{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:x61}}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:u61}}async handleSearch(Y){let X=WB6.safeParse(Y);if(!X.success)return sH({error:X.error.flatten()});let Q=await this._cachedTools,J=CZ(Q.data),G=kb(X.data.query,J,X.data.limit);return WP({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=ZB6.safeParse(Y);if(!X.success)return sH({error:X.error.flatten()});let Q=await this._cachedTools,J=CZ(Q.data),G=vb(X.data.tools,J);return WP({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,X=CZ(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 UD.prototype.callTool.call(this,Y)}}var KB6=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).")}),g61=z.toJSONSchema(KB6);class hJ0 extends SP{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:g61}}async handleRunCode(Y){let X=KB6.safeParse(Y);if(!X.success)return sH({error:X.error.flatten()});let Q=await this._cachedTools,G={tools:CZ(Q.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await _b(X.data.code,G,X.data.timeoutMs);if(K.error)return sH(K);return WP(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)}}c0();q$();var HB6=new Map;function FB6(Y){let X=Y.slice().sort().join(","),Q=HB6.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)},HB6.set(X,Q)}return Q}class bJ0 extends SP{constructor(Y,X){super(Y,X)}async getCallTool(){let Y=await this._cachedTools,Q=CZ(Y.data).map((G)=>G.name),{jsonSchema:J}=FB6(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=CZ(X.data),J=Q.map((F)=>F.name),{schema:G}=FB6(J),K=G.safeParse(Y);if(!K.success)return sH({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 xJ0(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function m61(Y,X){if(Y.connection_type!=="VIRTUAL")return!1;if(!X||hW(X))return!1;return Y.id===X}async function VB6(Y,X){let Q=Y.id,J=await X.storage.virtualMcps.findById(Q);if(!J)throw Error(`Virtual MCP not found: ${Q}`);return kP(J,X,"passthrough")}async function kP(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"&&!m61(H,Y.id)),virtualMcp:Y};return Q==="smart_tool_selection"?new bJ0(Z,X):Q==="code_execution"?new hJ0(Z,X):new UD(Z,X)}async function $B6(Y,X,Q=!1){if(Y.connection_type==="VIRTUAL")return VB6(Y,X);return QB6(Y,X,Q)}_J();Ab();mY();_J();Ab();var uJ0=new Y9;async function rb(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=xJ0(Y.req.query("mode")),F=await kP(W,Q,H),V=DM(F,{name:`mcp-virtual-mcp-${W.title??"Decopilot"}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:W.metadata?.instructions??void 0}),$=new K$({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)}}uJ0.all("/gateway/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return rb(Y,X)});uJ0.all("/virtual-mcp/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return rb(Y,X)});var qB6=uJ0;var ob=new Y9,gJ0=[404,401,406];async function zB6(Y,X){return(await X.storage.connections.findById(Y))?.connection_url??null}function l61(Y){let X=Y.toLowerCase();return X.includes("resource_metadata=")||X.includes("invalid_token")||X.includes("oauth")}async function BB6(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(l61(J))return J}if(await d61(Y))return'Bearer realm="mcp"'}return null}catch{return null}}async function d61(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 sb(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(!gJ0.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"}}),!gJ0.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 p61(Y,X){let Q=await zB6(Y,X);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await sb(Q);if(G.ok){let K=await G.json();if(K.authorization_servers?.[0])return K.authorization_servers[0]}}catch{}return J}async function UB6(Y){let X=Y.get("meshContext");if(!X)X=await X3.create(Y.req.raw),Y.set("meshContext",X);return X}async function DB6({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 BB6(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"}})}var OB6=(Y)=>{if(!(Y.hostname==="localhost"||Y.hostname==="127.0.0.1"))Y.protocol="https:";return Y},NB6=async(Y)=>{let X=Y.req.param("connectionId"),Q=await UB6(Y),J=await zB6(X,Q);if(!J)return Y.json({error:"Connection not found"},404);let G=OB6(new URL(Y.req.url)),K=`${G.origin}/mcp/${X}`,W=`${G.origin}/oauth-proxy/${X}`;try{let Z=await sb(J);if(!Z.ok&&gJ0.includes(Z.status)){if(await BB6(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)}};ob.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Y)=>NB6(Y));ob.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Y)=>NB6(Y));async function mJ0(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}ob.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=await UB6(Y),J=await p61(X,Q);if(!J)return Y.json({error:"Connection not found or no auth server"},404);try{let G=await mJ0(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=`${OB6(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)}});var LB6=ob;_J();var wB6=262144;function c61(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 n61(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 i61(Y,X){if(!Y&&!X)return;if(!Y)return X;if(!X)return Y;return{...X,...Y}}function MB6(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 a61(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 vP(Y){let{ctx:X,enabled:Q}=Y,J=Y.organizationId??X.organization?.id;if(!Q||!J)return;if(hW(Y.connectionId))return;let G=n61(Y.request.params.arguments),K=i61(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 AB6(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 vP({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:MB6(F),isError:Boolean(F.isError),errorMessage:c61(F),durationMs:V}),F}catch(F){let V=F,$=Date.now()-H;throw await vP({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}function TB6(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 a61($,wB6),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 ${wB6} bytes`:void 0;await vP({ctx:X,enabled:Q,organizationId:V,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:MB6(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let B=Date.now()-H;await vP({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 vP({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}var tb=new Y9,lJ0=300000;function r61(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 Y3(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 o61(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 Y3(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 D$(Y){return{client:{callTool:Y.callTool.bind(Y),listTools:Y.listTools.bind(Y)},callStreamableTool:Y.callStreamableTool.bind(Y)}}async function PB6(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 $B6(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:ZK6().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:Z,ctx:X},F=async(L)=>{return sT(AB6(H),Q?async(I,T)=>await T():r61(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:lJ0}),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 V6&&L.code===N6.MethodNotFound)return{resources:[]};throw L}},readResource:async(L)=>K.readResource(L),listResourceTemplates:async()=>{try{return await K.listResourceTemplates()}catch(L){if(L instanceof V6&&L.code===N6.MethodNotFound)return{resourceTemplates:[]};throw L}},listPrompts:async()=>{try{return await K.listPrompts()}catch(L){if(L instanceof V6&&L.code===N6.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 sT(TB6(H),Q?async(A,R)=>await R():o61(X,G,W))(T,async()=>{let A=await jP(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(S)=>{let _=Date.now();try{let y=await fetch(j.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(T.params.arguments),headers:{...A,"Content-Type":"application/json"}}),f=Date.now()-_;return X.meter.createHistogram("connection.proxy.streamable.duration").record(f,{"connection.id":G,"tool.name":T.params.name,status:y.ok?"success":"error"}),X.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":T.params.name,status:y.ok?"success":"error"}),S.end(),y}catch(y){let f=y,s=Date.now()-_;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:f.message}),S.recordException(f),S.end(),y}})})},[Symbol.asyncDispose]:()=>K.close()}}async function EB6(Y,X){return PB6(Y,X,{superUser:!1})}async function CB6(Y,X){return PB6(Y,X,{superUser:!0})}tb.all("/",async(Y)=>{return rb(Y,void 0)});tb.all("/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=Y.get("meshContext");try{try{let J=await Q.createMCPProxy(X),G=DM(J,{name:"mcp-mesh",version:"1.0.0"}),K=new K$({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 DB6({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 IB6(J,Y)}});var IB6=(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)};tb.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 IB6(G,Y)}});var RB6=tb;AZ();class dJ0{db;constructor(Y){this.db=Y}async create(Y){let X=Y.id??H9("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()}}}XB();function jB6(){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 vJ({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()}})}function s61(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 t61(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 e61(Y){let{auth:X,headers:Q,role:J,permissions:G,userId:K}=Y,W=X.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&jJ0.includes(J))return!0;if(G)return t61(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 Y41(Y,X,Q){if(jJ0.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 X41(Y,X,Q,J=kB6){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",()=>Y41(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",()=>sz6(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}}var SB6,X3={set:(Y)=>{SB6=Y},create:async(Y,X)=>{return await SB6(Y,X)}},kB6={measure:async(Y,X)=>{return await X()}},Q41=["x-hub-signature-256"];async function vB6(Y){let G=[];try{let X=new Q$(Y.encryption.key);let Q={connections:new cT(Y.db,X),organizationSettings:new _J0(Y.db),monitoring:new vJ0(Y.db,Y.databaseType),virtualMcps:new SJ0(Y.db),users:new yJ0(Y.db),threads:new dJ0(Y.db)};const J=NG(G,jB6(),1);return async(F,V)=>{let $=V?.timings??kB6,q=F?.headers.get("x-caller-id")??void 0,B=F?await X41(F,Y.auth,Y.db,$):{user:void 0},D=e61({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}`:ZG(),I=new Y3(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(Q41.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:s61(F?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(P)=>{return await EB6(P,T)},getOrCreateClient:J};return T}}catch(K){var W=K,Z=1}finally{var H=o7(G,W,Z);H&&await H}}class _B6{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 yB6(Y){return new _B6(Y)}function QX(Y,X,Q,J,G,K,W,Z){return QX.fromTZ(QX.tp(Y,X,Q,J,G,K,W),Z)}QX.fromTZISO=(Y,X,Q)=>QX.fromTZ(J41(Y,X),Q);QX.fromTZ=function(Y,X){let Q=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=pJ0(Y.tz,Q),G=new Date(Q.getTime()-J),K=pJ0(Y.tz,G);if(K-J===0)return G;{let W=new Date(Q.getTime()-K),Z=pJ0(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}};QX.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}};QX.tp=(Y,X,Q,J,G,K,W)=>({y:Y,m:X,d:Q,h:J,i:G,s:K,tz:W});function pJ0(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 J41(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("+")?QX.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):QX.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),X)}QX.minitz=QX;var cJ0=32,yP=31|cJ0,xB6=[1,2,4,8,16],fB6=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 $5(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,yP),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]|cJ0;else if(X===yP)this.dayOfWeek[Y]=yP;else if(X<6&&X>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|xB6[X-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${X}, Type: ${typeof X}`)}},hB6=[31,28,31,30,31,30,31,31,30,31,30,31],_Z=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],$5=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&yP&&xB6[W-1]&G)return!0;if(G&cJ0){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=QX.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>hB6[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=QX.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(QX.fromTZISO(X,this.tz))}findNext(X,Q,J,G){let K=this[Q],W;J.lastDayOfMonth&&(this.month!==1?W=hB6[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&yP)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,_Z[J][0],X,_Z[J][2]);if(G>1){let K=J+1;for(;K<_Z.length;)this[_Z[K][0]]=-_Z[K][2],K++;if(G===3)return this[_Z[J][1]]++,this[_Z[J][0]]=-_Z[J][2],this.apply(),this.recurse(X,Q,0);if(this.apply())return this.recurse(X,Q,J-1)}return J+=1,J>=_Z.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)):QX.fromTZ(QX.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function G41(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 $5(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new $5(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 _P(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function W41(Y){return _P(Y)}function Z41(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var bB6=30000,eb=[],Yx=class{name;options;_states;fn;constructor(Y,X,Q){let J,G;if(_P(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(_P(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=G41(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 fB6("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new $5(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new fB6(Y,this.options.timezone),this.name){if(eb.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");eb.push(this)}return G!==void 0&&W41(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 $5||Y instanceof Date?X.getTime()-Y.getTime():X.getTime()-new $5(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=eb.indexOf(this);Y>=0&&eb.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>bB6&&(X=bB6),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),X),this._states.currentTimeout&&this.options.unref&&Z41(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new $5(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){_P(this.options.catch)&&this.options.catch(X,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new $5(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&&_P(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 $5(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 $5(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 $5(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 $5(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 Xx={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};ub();function uB6(){return async(Y,X)=>{try{let Q=await X3.create(),J=await CB6(Y,Q),K=await hQ0.forClient(D$(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}}}}function gB6(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 K41(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(gB6(J.event))}else X.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[gB6(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 nJ0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Y,X){this.storage=Y;this.notifySubscriber=uB6(),this.config={...Xx,...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=K41(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 Yx(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)}}}class iJ0{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new nJ0(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 Yx(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}}function mB6(...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 Qx{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 H41}from"kysely";var DD="mesh_events";class aJ0{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===DD&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(X)=>{console.error("[PostgresNotify] Connection error:",X),this.cleanup()}),await this.listenClient.query(`LISTEN ${DD}`),console.log("[PostgresNotify] Started LISTEN on",DD)}catch(X){console.error("[PostgresNotify] Failed to start LISTEN:",X),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${DD}`),console.log("[PostgresNotify] Stopped LISTEN on",DD)}catch{}this.cleanup()}}async notify(Y){try{await H41`SELECT pg_notify(${DD}, ${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}}function lB6(Y,X){let Q=yB6(Y.db),J=X?.pollIntervalMs??Xx.pollIntervalMs,G=Y.type==="postgres"?mB6(new Qx(J),new aJ0(Y.db,Y.pool)):new Qx(J);return new iJ0({storage:Q,config:X,notifyStrategy:G})}var dB6={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 pB6=new Y9;pB6.get("/config",async(Y)=>{try{let X=Object.keys(F9.socialProviders??{}),Q=X.length>0,J=X.map((W)=>({name:W,icon:dB6[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:F9.emailAndPassword?.enabled??!1},magicLink:{enabled:F9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:F9.ssoConfig?{enabled:!0,providerId:F9.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)}});var cB6=pB6;var wU6="vercel.ai.error",F41=Symbol.for(wU6),nB6,iB6,w6=class Y extends(iB6=Error,nB6=F41,iB6){constructor({name:X,message:Q,cause:J}){super(Q);this[nB6]=!0,this.name=X,this.cause=J}static isInstance(X){return Y.hasMarker(X,wU6)}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}},MU6="AI_APICallError",AU6=`vercel.ai.error.${MU6}`,V41=Symbol.for(AU6),aB6,rB6,c8=class extends(rB6=w6,aB6=V41,rB6){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:MU6,message:Y,cause:W});this[aB6]=!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 w6.hasMarker(Y,AU6)}},TU6="AI_EmptyResponseBodyError",PU6=`vercel.ai.error.${TU6}`,$41=Symbol.for(PU6),oB6,sB6,EU6=class extends(sB6=w6,oB6=$41,sB6){constructor({message:Y="Empty response body"}={}){super({name:TU6,message:Y});this[oB6]=!0}static isInstance(Y){return w6.hasMarker(Y,PU6)}};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 CU6="AI_InvalidArgumentError",IU6=`vercel.ai.error.${CU6}`,q41=Symbol.for(IU6),tB6,eB6,RU6=class extends(eB6=w6,tB6=q41,eB6){constructor({message:Y,cause:X,argument:Q}){super({name:CU6,message:Y,cause:X});this[tB6]=!0,this.argument=Q}static isInstance(Y){return w6.hasMarker(Y,IU6)}},jU6="AI_InvalidPromptError",SU6=`vercel.ai.error.${jU6}`,z41=Symbol.for(SU6),YU6,XU6,O$=class extends(XU6=w6,YU6=z41,XU6){constructor({prompt:Y,message:X,cause:Q}){super({name:jU6,message:`Invalid prompt: ${X}`,cause:Q});this[YU6]=!0,this.prompt=Y}static isInstance(Y){return w6.hasMarker(Y,SU6)}},kU6="AI_InvalidResponseDataError",vU6=`vercel.ai.error.${kU6}`,B41=Symbol.for(vU6),QU6,JU6,hq8=class extends(JU6=w6,QU6=B41,JU6){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:kU6,message:X});this[QU6]=!0,this.data=Y}static isInstance(Y){return w6.hasMarker(Y,vU6)}},_U6="AI_JSONParseError",yU6=`vercel.ai.error.${_U6}`,U41=Symbol.for(yU6),GU6,WU6,fP=class extends(WU6=w6,GU6=U41,WU6){constructor({text:Y,cause:X}){super({name:_U6,message:`JSON parsing failed: Text: ${Y}.
1051
+ `})}}}var _61=[wY0({organizationCreation:{afterCreate:async(Y)=>{await lz6(Y.organization.id,Y.member.userId)}},ac:ib,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:dz6,resourceNameValidation:(Y)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(Y)}}},roles:{user:S61,admin:k61,owner:v61},sendInvitationEmail:az6}),fY0({loginPage:"/login",oidcConfig:{scopes:iz6,metadata:{scopes_supported:iz6},loginPage:"/login"}}),yY0({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}}),TY0({defaultRole:"user",adminRoles:["admin","owner"]}),uY0(),CY0({jwt:{expirationTime:"5m"}}),wW6(F9.ssoConfig?pz6(F9.ssoConfig):void 0),...F9.magicLinkConfig&&F9.emailProviders&&F9.emailProviders.length>0?[xY0(d36(F9.magicLinkConfig,F9.emailProviders))]:[]],y61=PX0(),f61=l36(y61),vZ=k90({baseURL:ZG(),database:f61,emailAndPassword:{enabled:!0},...F9,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:_61,databaseHooks:{user:{create:{after:async(Y)=>{if(yT.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} ${I61()}`,K=C61(G);try{await vZ.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}}}}}}}});iQ();import{randomBytes as h61}from"crypto";var RP=null;function rz6(){if(RP)return RP;let Y=process.env.MESH_JWT_SECRET??F9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)RP=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),RP=new Uint8Array(h61(32));return RP}async function oz6(Y,X="5m"){let Q=rz6();return await new UQ(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(X).sign(Q)}async function sz6(Y){try{let X=rz6(),{payload:Q}=await D8(Y,X);return Q}catch{return}}AZ();_J();class SJ0{db;constructor(Y){this.db=Y}async create(Y,X,Q){let J=H9("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:H9("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&&hW(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{...zM(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{...zM(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:H9("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}}import{sql as ab}from"kysely";class kJ0{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}}AZ();class vJ0{db;redactor;databaseType;constructor(Y,X="sqlite"){this.db=Y;this.redactor=new kJ0,this.databaseType=X}jsonExtract(Y,X){if(this.databaseType==="postgres")return ab`(${ab.ref(Y)}::jsonb)->>${X}`;let Q=`$.${X}`;return ab`json_extract(${ab.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||H9("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}}}class _J0{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 yJ0{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 tz6="mcp.mesh";class ez6 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}}class fJ0 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}}class Y3{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 ez6("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 fJ0("No resources specified for access check");for(let Q of X)if(await this.checkResource(Q)){this.grant();return}throw new fJ0(`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[tz6]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}MZ();Nb();qM();dQ0();async function YB6(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"}}}cb();async function jP(Y,X,Q){let J=Y.id,G=lQ0(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 oz6({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 SZ(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 YB6(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}iX0();function XB6(Y){let X=new oT({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}async function QB6(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(!J$(G))throw Error("STDIO connection missing parameters");let K=XB6({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 jP(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new iK(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 jP(Y,X,Q),K=Y.connection_headers;if(K&&"headers"in K)Object.assign(G,K.headers);let W=new Z$(new URL(Y.connection_url),{requestInit:{headers:G}});return X.getOrCreateClient(W,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}_J();c0();q$();c0();q$();XB();class JB6{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 U$(Y){return new JB6(Y)}async function b61(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 GB6(Y){let X=[];for(let[,Q]of Y)X.push(Q.close().catch(()=>{}));await Promise.all(X)}class UD extends vJ{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=U$(()=>b61(this.options.connections,this.ctx)),this._cachedTools=U$(()=>this.loadCache("tools")),this._cachedResources=U$(()=>this.loadCache("resources")),this._cachedPrompts=U$(()=>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 GB6(Y)}async close(){let Y=await this._clients;if(Y)await GB6(Y);await super.close()}getInstructions(){return this.options.virtualMcp.metadata?.instructions}}var WB6=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")}),x61=z.toJSONSchema(WB6),ZB6=z.object({tools:z.array(z.string()).min(1).describe("Array of tool names to get detailed schemas for")}),u61=z.toJSONSchema(ZB6);class SP extends UD{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:x61}}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:u61}}async handleSearch(Y){let X=WB6.safeParse(Y);if(!X.success)return sH({error:X.error.flatten()});let Q=await this._cachedTools,J=CZ(Q.data),G=kb(X.data.query,J,X.data.limit);return WP({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=ZB6.safeParse(Y);if(!X.success)return sH({error:X.error.flatten()});let Q=await this._cachedTools,J=CZ(Q.data),G=vb(X.data.tools,J);return WP({tools:G.tools,notFound:G.notFound})}async listTools(){let Y=await this._cachedTools,X=CZ(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 UD.prototype.callTool.call(this,Y)}}var KB6=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).")}),g61=z.toJSONSchema(KB6);class hJ0 extends SP{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:g61}}async handleRunCode(Y){let X=KB6.safeParse(Y);if(!X.success)return sH({error:X.error.flatten()});let Q=await this._cachedTools,G={tools:CZ(Q.data),callTool:async(W,Z)=>{return this.routeToolCall({name:W,arguments:Z})}},K=await _b(X.data.code,G,X.data.timeoutMs);if(K.error)return sH(K);return WP(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)}}c0();q$();var HB6=new Map;function FB6(Y){let X=Y.slice().sort().join(","),Q=HB6.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)},HB6.set(X,Q)}return Q}class bJ0 extends SP{constructor(Y,X){super(Y,X)}async getCallTool(){let Y=await this._cachedTools,Q=CZ(Y.data).map((G)=>G.name),{jsonSchema:J}=FB6(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=CZ(X.data),J=Q.map((F)=>F.name),{schema:G}=FB6(J),K=G.safeParse(Y);if(!K.success)return sH({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 xJ0(Y){switch(Y){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}function m61(Y,X){if(Y.connection_type!=="VIRTUAL")return!1;if(!X||hW(X))return!1;return Y.id===X}async function VB6(Y,X){let Q=Y.id,J=await X.storage.virtualMcps.findById(Q);if(!J)throw Error(`Virtual MCP not found: ${Q}`);return kP(J,X,"passthrough")}async function kP(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"&&!m61(H,Y.id)),virtualMcp:Y};return Q==="smart_tool_selection"?new bJ0(Z,X):Q==="code_execution"?new hJ0(Z,X):new UD(Z,X)}async function $B6(Y,X,Q=!1){if(Y.connection_type==="VIRTUAL")return VB6(Y,X);return QB6(Y,X,Q)}_J();Ab();mY();_J();Ab();var uJ0=new Y9;async function rb(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=xJ0(Y.req.query("mode")),F=await kP(W,Q,H),V=DM(F,{name:`mcp-virtual-mcp-${W.title??"Decopilot"}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:W.metadata?.instructions??void 0}),$=new K$({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)}}uJ0.all("/gateway/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return rb(Y,X)});uJ0.all("/virtual-mcp/:virtualMcpId?",async(Y)=>{let X=Y.req.param("virtualMcpId")||Y.req.header("x-virtual-mcp-id");return rb(Y,X)});var qB6=uJ0;var ob=new Y9,gJ0=[404,401,406];async function zB6(Y,X){return(await X.storage.connections.findById(Y))?.connection_url??null}function l61(Y){let X=Y.toLowerCase();return X.includes("resource_metadata=")||X.includes("invalid_token")||X.includes("oauth")}async function BB6(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(l61(J))return J}if(await d61(Y))return'Bearer realm="mcp"'}return null}catch{return null}}async function d61(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 sb(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(!gJ0.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"}}),!gJ0.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 p61(Y,X){let Q=await zB6(Y,X);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await sb(Q);if(G.ok){let K=await G.json();if(K.authorization_servers?.[0])return K.authorization_servers[0]}}catch{}return J}async function UB6(Y){let X=Y.get("meshContext");if(!X)X=await X3.create(Y.req.raw),Y.set("meshContext",X);return X}async function DB6({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 BB6(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"}})}var OB6=(Y)=>{if(!(Y.hostname==="localhost"||Y.hostname==="127.0.0.1"))Y.protocol="https:";return Y},NB6=async(Y)=>{let X=Y.req.param("connectionId"),Q=await UB6(Y),J=await zB6(X,Q);if(!J)return Y.json({error:"Connection not found"},404);let G=OB6(new URL(Y.req.url)),K=`${G.origin}/mcp/${X}`,W=`${G.origin}/oauth-proxy/${X}`;try{let Z=await sb(J);if(!Z.ok&&gJ0.includes(Z.status)){if(await BB6(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)}};ob.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(Y)=>NB6(Y));ob.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(Y)=>NB6(Y));async function mJ0(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}ob.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=await UB6(Y),J=await p61(X,Q);if(!J)return Y.json({error:"Connection not found or no auth server"},404);try{let G=await mJ0(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=`${OB6(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)}});var LB6=ob;_J();var wB6=262144;function c61(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 n61(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 i61(Y,X){if(!Y&&!X)return;if(!Y)return X;if(!X)return Y;return{...X,...Y}}function MB6(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 a61(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 vP(Y){let{ctx:X,enabled:Q}=Y,J=Y.organizationId??X.organization?.id;if(!Q||!J)return;if(hW(Y.connectionId))return;let G=n61(Y.request.params.arguments),K=i61(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 AB6(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 vP({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:MB6(F),isError:Boolean(F.isError),errorMessage:c61(F),durationMs:V}),F}catch(F){let V=F,$=Date.now()-H;throw await vP({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}function TB6(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 a61($,wB6),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 ${wB6} bytes`:void 0;await vP({ctx:X,enabled:Q,organizationId:V,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:MB6(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let B=Date.now()-H;await vP({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 vP({ctx:X,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:V.message,durationMs:$}),F}}}var tb=new Y9,lJ0=300000;function r61(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 Y3(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 o61(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 Y3(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 D$(Y){return{client:{callTool:Y.callTool.bind(Y),listTools:Y.listTools.bind(Y)},callStreamableTool:Y.callStreamableTool.bind(Y)}}async function PB6(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 $B6(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:ZK6().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:Z,ctx:X},F=async(L)=>{return sT(AB6(H),Q?async(I,T)=>await T():r61(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:lJ0}),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 V6&&L.code===N6.MethodNotFound)return{resources:[]};throw L}},readResource:async(L)=>K.readResource(L),listResourceTemplates:async()=>{try{return await K.listResourceTemplates()}catch(L){if(L instanceof V6&&L.code===N6.MethodNotFound)return{resourceTemplates:[]};throw L}},listPrompts:async()=>{try{return await K.listPrompts()}catch(L){if(L instanceof V6&&L.code===N6.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 sT(TB6(H),Q?async(A,R)=>await R():o61(X,G,W))(T,async()=>{let A=await jP(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(S)=>{let _=Date.now();try{let y=await fetch(j.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(T.params.arguments),headers:{...A,"Content-Type":"application/json"}}),f=Date.now()-_;return X.meter.createHistogram("connection.proxy.streamable.duration").record(f,{"connection.id":G,"tool.name":T.params.name,status:y.ok?"success":"error"}),X.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":T.params.name,status:y.ok?"success":"error"}),S.end(),y}catch(y){let f=y,s=Date.now()-_;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:f.message}),S.recordException(f),S.end(),y}})})},[Symbol.asyncDispose]:()=>K.close()}}async function EB6(Y,X){return PB6(Y,X,{superUser:!1})}async function CB6(Y,X){return PB6(Y,X,{superUser:!0})}tb.all("/",async(Y)=>{return rb(Y,void 0)});tb.all("/:connectionId",async(Y)=>{let X=Y.req.param("connectionId"),Q=Y.get("meshContext");try{try{let J=await Q.createMCPProxy(X),G=DM(J,{name:"mcp-mesh",version:"1.0.0"}),K=new K$({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 DB6({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 IB6(J,Y)}});var IB6=(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)};tb.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 IB6(G,Y)}});var RB6=tb;AZ();class dJ0{db;constructor(Y){this.db=Y}async create(Y){let X=Y.id??H9("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()}}}XB();function jB6(){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 vJ({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()}})}function s61(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 t61(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 e61(Y){let{auth:X,headers:Q,role:J,permissions:G,userId:K}=Y,W=X.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&jJ0.includes(J))return!0;if(G)return t61(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 Y41(Y,X,Q){if(jJ0.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 X41(Y,X,Q,J=kB6){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",()=>Y41(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",()=>sz6(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}}var SB6,X3={set:(Y)=>{SB6=Y},create:async(Y,X)=>{return await SB6(Y,X)}},kB6={measure:async(Y,X)=>{return await X()}},Q41=["x-hub-signature-256"];async function vB6(Y){let G=[];try{let X=new Q$(Y.encryption.key);let Q={connections:new cT(Y.db,X),organizationSettings:new _J0(Y.db),monitoring:new vJ0(Y.db,Y.databaseType),virtualMcps:new SJ0(Y.db),users:new yJ0(Y.db),threads:new dJ0(Y.db)};const J=NG(G,jB6(),1);return async(F,V)=>{let $=V?.timings??kB6,q=F?.headers.get("x-caller-id")??void 0,B=F?await X41(F,Y.auth,Y.db,$):{user:void 0},D=e61({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}`:ZG(),I=new Y3(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(Q41.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:s61(F?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(P)=>{return await EB6(P,T)},getOrCreateClient:J};return T}}catch(K){var W=K,Z=1}finally{var H=o7(G,W,Z);H&&await H}}class _B6{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 yB6(Y){return new _B6(Y)}function QX(Y,X,Q,J,G,K,W,Z){return QX.fromTZ(QX.tp(Y,X,Q,J,G,K,W),Z)}QX.fromTZISO=(Y,X,Q)=>QX.fromTZ(J41(Y,X),Q);QX.fromTZ=function(Y,X){let Q=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=pJ0(Y.tz,Q),G=new Date(Q.getTime()-J),K=pJ0(Y.tz,G);if(K-J===0)return G;{let W=new Date(Q.getTime()-K),Z=pJ0(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}};QX.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}};QX.tp=(Y,X,Q,J,G,K,W)=>({y:Y,m:X,d:Q,h:J,i:G,s:K,tz:W});function pJ0(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 J41(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("+")?QX.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):QX.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),X)}QX.minitz=QX;var cJ0=32,yP=31|cJ0,xB6=[1,2,4,8,16],fB6=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 $5(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,yP),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]|cJ0;else if(X===yP)this.dayOfWeek[Y]=yP;else if(X<6&&X>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|xB6[X-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${X}, Type: ${typeof X}`)}},hB6=[31,28,31,30,31,30,31,31,30,31,30,31],_Z=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],$5=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&yP&&xB6[W-1]&G)return!0;if(G&cJ0){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=QX.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>hB6[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=QX.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(QX.fromTZISO(X,this.tz))}findNext(X,Q,J,G){let K=this[Q],W;J.lastDayOfMonth&&(this.month!==1?W=hB6[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&yP)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,_Z[J][0],X,_Z[J][2]);if(G>1){let K=J+1;for(;K<_Z.length;)this[_Z[K][0]]=-_Z[K][2],K++;if(G===3)return this[_Z[J][1]]++,this[_Z[J][0]]=-_Z[J][2],this.apply(),this.recurse(X,Q,0);if(this.apply())return this.recurse(X,Q,J-1)}return J+=1,J>=_Z.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)):QX.fromTZ(QX.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function G41(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 $5(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new $5(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 _P(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function W41(Y){return _P(Y)}function Z41(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var bB6=30000,eb=[],Yx=class{name;options;_states;fn;constructor(Y,X,Q){let J,G;if(_P(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(_P(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=G41(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 fB6("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new $5(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new fB6(Y,this.options.timezone),this.name){if(eb.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");eb.push(this)}return G!==void 0&&W41(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 $5||Y instanceof Date?X.getTime()-Y.getTime():X.getTime()-new $5(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=eb.indexOf(this);Y>=0&&eb.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>bB6&&(X=bB6),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),X),this._states.currentTimeout&&this.options.unref&&Z41(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new $5(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){_P(this.options.catch)&&this.options.catch(X,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new $5(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&&_P(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 $5(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 $5(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 $5(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 $5(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 Xx={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};ub();function uB6(){return async(Y,X)=>{try{let Q=await X3.create(),J=await CB6(Y,Q),K=await hQ0.forClient(D$(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}}}}function gB6(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 K41(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(gB6(J.event))}else X.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[gB6(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 nJ0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(Y,X){this.storage=Y;this.notifySubscriber=uB6(),this.config={...Xx,...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=K41(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 Yx(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)}}}class iJ0{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new nJ0(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 Yx(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}}function mB6(...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 Qx{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 H41}from"kysely";var DD="mesh_events";class aJ0{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===DD&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(X)=>{console.error("[PostgresNotify] Connection error:",X),this.cleanup()}),await this.listenClient.query(`LISTEN ${DD}`),console.log("[PostgresNotify] Started LISTEN on",DD)}catch(X){console.error("[PostgresNotify] Failed to start LISTEN:",X),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${DD}`),console.log("[PostgresNotify] Stopped LISTEN on",DD)}catch{}this.cleanup()}}async notify(Y){try{await H41`SELECT pg_notify(${DD}, ${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}}function lB6(Y,X){let Q=yB6(Y.db),J=X?.pollIntervalMs??Xx.pollIntervalMs,G=Y.type==="postgres"?mB6(new Qx(J),new aJ0(Y.db,Y.pool)):new Qx(J);return new iJ0({storage:Q,config:X,notifyStrategy:G})}var dB6={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 pB6=new Y9;pB6.get("/config",async(Y)=>{try{let X=Object.keys(F9.socialProviders??{}),Q=X.length>0,J=X.map((W)=>({name:W,icon:dB6[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:F9.emailAndPassword?.enabled??!1},magicLink:{enabled:F9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:F9.ssoConfig?{enabled:!0,providerId:F9.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)}});var cB6=pB6;var wU6="vercel.ai.error",F41=Symbol.for(wU6),nB6,iB6,w6=class Y extends(iB6=Error,nB6=F41,iB6){constructor({name:X,message:Q,cause:J}){super(Q);this[nB6]=!0,this.name=X,this.cause=J}static isInstance(X){return Y.hasMarker(X,wU6)}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}},MU6="AI_APICallError",AU6=`vercel.ai.error.${MU6}`,V41=Symbol.for(AU6),aB6,rB6,c8=class extends(rB6=w6,aB6=V41,rB6){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:MU6,message:Y,cause:W});this[aB6]=!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 w6.hasMarker(Y,AU6)}},TU6="AI_EmptyResponseBodyError",PU6=`vercel.ai.error.${TU6}`,$41=Symbol.for(PU6),oB6,sB6,EU6=class extends(sB6=w6,oB6=$41,sB6){constructor({message:Y="Empty response body"}={}){super({name:TU6,message:Y});this[oB6]=!0}static isInstance(Y){return w6.hasMarker(Y,PU6)}};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 CU6="AI_InvalidArgumentError",IU6=`vercel.ai.error.${CU6}`,q41=Symbol.for(IU6),tB6,eB6,RU6=class extends(eB6=w6,tB6=q41,eB6){constructor({message:Y,cause:X,argument:Q}){super({name:CU6,message:Y,cause:X});this[tB6]=!0,this.argument=Q}static isInstance(Y){return w6.hasMarker(Y,IU6)}},jU6="AI_InvalidPromptError",SU6=`vercel.ai.error.${jU6}`,z41=Symbol.for(SU6),YU6,XU6,O$=class extends(XU6=w6,YU6=z41,XU6){constructor({prompt:Y,message:X,cause:Q}){super({name:jU6,message:`Invalid prompt: ${X}`,cause:Q});this[YU6]=!0,this.prompt=Y}static isInstance(Y){return w6.hasMarker(Y,SU6)}},kU6="AI_InvalidResponseDataError",vU6=`vercel.ai.error.${kU6}`,B41=Symbol.for(vU6),QU6,JU6,hq8=class extends(JU6=w6,QU6=B41,JU6){constructor({data:Y,message:X=`Invalid response data: ${JSON.stringify(Y)}.`}){super({name:kU6,message:X});this[QU6]=!0,this.data=Y}static isInstance(Y){return w6.hasMarker(Y,vU6)}},_U6="AI_JSONParseError",yU6=`vercel.ai.error.${_U6}`,U41=Symbol.for(yU6),GU6,WU6,fP=class extends(WU6=w6,GU6=U41,WU6){constructor({text:Y,cause:X}){super({name:_U6,message:`JSON parsing failed: Text: ${Y}.
1052
1052
  Error message: ${VG(X)}`,cause:X});this[GU6]=!0,this.text=Y}static isInstance(Y){return w6.hasMarker(Y,yU6)}},fU6="AI_LoadAPIKeyError",hU6=`vercel.ai.error.${fU6}`,D41=Symbol.for(hU6),ZU6,KU6,bq8=class extends(KU6=w6,ZU6=D41,KU6){constructor({message:Y}){super({name:fU6,message:Y});this[ZU6]=!0}static isInstance(Y){return w6.hasMarker(Y,hU6)}},bU6="AI_LoadSettingError",xU6=`vercel.ai.error.${bU6}`,O41=Symbol.for(xU6),HU6,FU6,xq8=class extends(FU6=w6,HU6=O41,FU6){constructor({message:Y}){super({name:bU6,message:Y});this[HU6]=!0}static isInstance(Y){return w6.hasMarker(Y,xU6)}},uU6="AI_NoContentGeneratedError",gU6=`vercel.ai.error.${uU6}`,N41=Symbol.for(gU6),VU6,$U6,uq8=class extends($U6=w6,VU6=N41,$U6){constructor({message:Y="No content generated."}={}){super({name:uU6,message:Y});this[VU6]=!0}static isInstance(Y){return w6.hasMarker(Y,gU6)}},mU6="AI_NoSuchModelError",lU6=`vercel.ai.error.${mU6}`,L41=Symbol.for(lU6),qU6,zU6,gq8=class extends(zU6=w6,qU6=L41,zU6){constructor({errorName:Y=mU6,modelId:X,modelType:Q,message:J=`No such ${Q}: ${X}`}){super({name:Y,message:J});this[qU6]=!0,this.modelId=X,this.modelType=Q}static isInstance(Y){return w6.hasMarker(Y,lU6)}},dU6="AI_TooManyEmbeddingValuesForCallError",pU6=`vercel.ai.error.${dU6}`,w41=Symbol.for(pU6),BU6,UU6,mq8=class extends(UU6=w6,BU6=w41,UU6){constructor(Y){super({name:dU6,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[BU6]=!0,this.provider=Y.provider,this.modelId=Y.modelId,this.maxEmbeddingsPerCall=Y.maxEmbeddingsPerCall,this.values=Y.values}static isInstance(Y){return w6.hasMarker(Y,pU6)}},cU6="AI_TypeValidationError",nU6=`vercel.ai.error.${cU6}`,M41=Symbol.for(nU6),DU6,OU6,AQ=class Y extends(OU6=w6,DU6=M41,OU6){constructor({value:X,cause:Q}){super({name:cU6,message:`Type validation failed: Value: ${JSON.stringify(X)}.
1053
1053
  Error message: ${VG(Q)}`,cause:Q});this[DU6]=!0,this.value=X}static isInstance(X){return w6.hasMarker(X,nU6)}static wrap({value:X,cause:Q}){return Y.isInstance(Q)&&Q.value===X?Q:new Y({value:X,cause:Q})}},iU6="AI_UnsupportedFunctionalityError",aU6=`vercel.ai.error.${iU6}`,A41=Symbol.for(aU6),NU6,LU6,rU6=class extends(LU6=w6,NU6=A41,LU6){constructor({functionality:Y,message:X=`'${Y}' functionality not supported.`}){super({name:iU6,message:X});this[NU6]=!0,this.functionality=Y}static isInstance(Y){return w6.hasMarker(Y,aU6)}};t4();wK();wK();wK();te();function L$(...Y){return Y.reduce((X,Q)=>({...X,...Q!=null?Q:{}}),{})}async function QD6(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(oU6());return}let K=setTimeout(()=>{W(),J()},Y),W=()=>{clearTimeout(K),Q==null||Q.removeEventListener("abort",Z)},Z=()=>{W(),G(oU6())};Q==null||Q.addEventListener("abort",Z)})}function oU6(){return new DOMException("Delay was aborted","AbortError")}var w$=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((Y,X)=>{if(this.status.type==="resolved")Y(this.status.value);else if(this.status.type==="rejected")X(this.status.error);this._resolve=Y,this._reject=X}),this._promise}resolve(Y){var X;if(this.status={type:"resolved",value:Y},this._promise)(X=this._resolve)==null||X.call(this,Y)}reject(Y){var X;if(this.status={type:"rejected",error:Y},this._promise)(X=this._reject)==null||X.call(this,Y)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function hP(Y){return Object.fromEntries([...Y.headers])}var{btoa:T41,atob:P41}=globalThis;function OD(Y){let X=Y.replace(/-/g,"+").replace(/_/g,"/"),Q=P41(X);return Uint8Array.from(Q,(J)=>J.codePointAt(0))}function M$(Y){let X="";for(let Q=0;Q<Y.length;Q++)X+=String.fromCodePoint(Y[Q]);return T41(X)}var JD6="AI_DownloadError",GD6=`vercel.ai.error.${JD6}`,E41=Symbol.for(GD6),sU6,tU6,Jx=class extends(tU6=w6,sU6=E41,tU6){constructor({url:Y,statusCode:X,statusText:Q,cause:J,message:G=J==null?`Failed to download ${Y}: ${X} ${Q}`:`Failed to download ${Y}: ${J}`}){super({name:JD6,message:G,cause:J});this[sU6]=!0,this.url=Y,this.statusCode=X,this.statusText=Q}static isInstance(Y){return w6.hasMarker(Y,GD6)}};var p7=({prefix:Y,size:X=16,alphabet:Q="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:J="-"}={})=>{let G=()=>{let K=Q.length,W=Array(X);for(let Z=0;Z<X;Z++)W[Z]=Q[Math.random()*K|0];return W.join("")};if(Y==null)return G;if(Q.includes(J))throw new RU6({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Q}".`});return()=>`${Y}${J}${G()}`},C41=p7();function ND(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 yZ(Y){return(Y instanceof Error||Y instanceof DOMException)&&(Y.name==="AbortError"||Y.name==="ResponseAborted"||Y.name==="TimeoutError")}var I41=["fetch failed","failed to fetch"],R41=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function j41(Y){if(!(Y instanceof Error))return!1;let X=Y.code;if(typeof X==="string"&&R41.includes(X))return!0;return!1}function WD6({error:Y,url:X,requestBodyValues:Q}){if(yZ(Y))return Y;if(Y instanceof TypeError&&I41.includes(Y.message.toLowerCase())){let J=Y.cause;if(J!=null)return new c8({message:`Cannot connect to API: ${J.message}`,cause:J,url:X,requestBodyValues:Q,isRetryable:!0})}if(j41(Y))return new c8({message:`Cannot connect to API: ${Y.message}`,cause:Y,url:X,requestBodyValues:Q,isRetryable:!0});return Y}function Gx(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 S41(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 fZ(Y,...X){let Q=new Headers(S41(Y)),J=Q.get("user-agent")||"";return Q.set("user-agent",[J,...X].filter(Boolean).join(" ")),Object.fromEntries(Q.entries())}var ZD6="4.0.10",k41=()=>globalThis.fetch,eJ0=async({url:Y,headers:X={},successfulResponseHandler:Q,failedResponseHandler:J,abortSignal:G,fetch:K=k41()})=>{try{let W=await K(Y,{method:"GET",headers:fZ(X,`ai-sdk/provider-utils/${ZD6}`,Gx()),signal:G}),Z=hP(W);if(!W.ok){let H;try{H=await J({response:W,url:Y,requestBodyValues:{}})}catch(F){if(yZ(F)||c8.isInstance(F))throw F;throw new c8({message:"Failed to process error response",cause:F,statusCode:W.status,url:Y,responseHeaders:Z,requestBodyValues:{}})}throw H.value}try{return await Q({response:W,url:Y,requestBodyValues:{}})}catch(H){if(H instanceof Error){if(yZ(H)||c8.isInstance(H))throw H}throw new c8({message:"Failed to process successful response",cause:H,statusCode:W.status,url:Y,responseHeaders:Z,requestBodyValues:{}})}}catch(W){throw WD6({error:W,url:Y,requestBodyValues:{}})}};function KD6(Y){return Y!=null}function HD6({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 bP({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}var v41=/"__proto__"\s*:/,_41=/"constructor"\s*:/;function eU6(Y){let X=JSON.parse(Y);if(X===null||typeof X!=="object")return X;if(v41.test(Y)===!1&&_41.test(Y)===!1)return X;return y41(X)}function y41(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 FD6(Y){let{stackTraceLimit:X}=Error;try{Error.stackTraceLimit=0}catch(Q){return eU6(Y)}try{return eU6(Y)}finally{Error.stackTraceLimit=X}}function Y50(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]=N$(Q[J])}if(Y.items!=null)Y.items=Array.isArray(Y.items)?Y.items.map(N$):N$(Y.items);if(Y.anyOf!=null)Y.anyOf=Y.anyOf.map(N$);if(Y.allOf!=null)Y.allOf=Y.allOf.map(N$);if(Y.oneOf!=null)Y.oneOf=Y.oneOf.map(N$);let{definitions:X}=Y;if(X!=null)for(let Q of Object.keys(X))X[Q]=N$(X[Q]);return Y}function N$(Y){if(typeof Y==="boolean")return Y;return Y50(Y)}var f41=Symbol("Let zodToJsonSchema decide on which parser to use"),YD6={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},h41=(Y)=>typeof Y==="string"?{...YD6,name:Y}:{...YD6,...Y};function JJ(){return{}}function b41(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=p1(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 x41(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 u41(){return{type:"boolean"}}function VD6(Y,X){return p1(Y.type._def,X)}var g41=(Y,X)=>{return p1(Y.innerType._def,X)};function $D6(Y,X,Q){let J=Q!=null?Q:X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,K)=>$D6(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 m41(Y)}}var m41=(Y)=>{let X={type:"integer",format:"unix-time"};for(let Q of Y.checks)switch(Q.kind){case"min":X.minimum=Q.value;break;case"max":X.maximum=Q.value;break}return X};function l41(Y,X){return{...p1(Y.innerType._def,X),default:Y.defaultValue()}}function d41(Y,X){return X.effectStrategy==="input"?p1(Y.schema._def,X):JJ()}function p41(Y){return{type:"string",enum:Array.from(Y.values)}}var c41=(Y)=>{if("type"in Y&&Y.type==="string")return!1;return"allOf"in Y};function n41(Y,X){let Q=[p1(Y.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),p1(Y.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Q.forEach((G)=>{if(c41(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 i41(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}}var rJ0=void 0,$G={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(rJ0===void 0)rJ0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return rJ0},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function qD6(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":qG(Q,"email",J.message,X);break;case"format:idn-email":qG(Q,"idn-email",J.message,X);break;case"pattern:zod":xX(Q,$G.email,J.message,X);break}break;case"url":qG(Q,"uri",J.message,X);break;case"uuid":qG(Q,"uuid",J.message,X);break;case"regex":xX(Q,J.regex,J.message,X);break;case"cuid":xX(Q,$G.cuid,J.message,X);break;case"cuid2":xX(Q,$G.cuid2,J.message,X);break;case"startsWith":xX(Q,RegExp(`^${oJ0(J.value,X)}`),J.message,X);break;case"endsWith":xX(Q,RegExp(`${oJ0(J.value,X)}$`),J.message,X);break;case"datetime":qG(Q,"date-time",J.message,X);break;case"date":qG(Q,"date",J.message,X);break;case"time":qG(Q,"time",J.message,X);break;case"duration":qG(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":{xX(Q,RegExp(oJ0(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")qG(Q,"ipv4",J.message,X);if(J.version!=="v4")qG(Q,"ipv6",J.message,X);break}case"base64url":xX(Q,$G.base64url,J.message,X);break;case"jwt":xX(Q,$G.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")xX(Q,$G.ipv4Cidr,J.message,X);if(J.version!=="v4")xX(Q,$G.ipv6Cidr,J.message,X);break}case"emoji":xX(Q,$G.emoji(),J.message,X);break;case"ulid":{xX(Q,$G.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{qG(Q,"binary",J.message,X);break}case"contentEncoding:base64":{Q.contentEncoding="base64";break}case"pattern:zod":{xX(Q,$G.base64,J.message,X);break}}break}case"nanoid":xX(Q,$G.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Q}function oJ0(Y,X){return X.patternStrategy==="escape"?r41(Y):Y}var a41=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function r41(Y){let X="";for(let Q=0;Q<Y.length;Q++){if(!a41.has(Y[Q]))X+="\\";X+=Y[Q]}return X}function qG(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 xX(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:XD6(X,J),...Q&&J.errorMessages&&{errorMessage:{pattern:Q}}})}else Y.pattern=XD6(X,J)}function XD6(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
1054
1054
  ]))`;continue}else if(G[F]==="$"){K+=`($|(?=[\r