@decocms/mesh 2.59.0 → 2.59.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/cli.js +2 -2
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
package/dist/server/migrate.js
CHANGED
|
@@ -404,7 +404,7 @@ ${Y.stack}`;return X}if(typeof Y==="object"&&Y!==null){let X=Y,Q="";if(typeof X.
|
|
|
404
404
|
${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}
|
|
405
405
|
|
|
406
406
|
Stack trace:
|
|
407
|
-
${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 _B(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=_B(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=_B(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=_B(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let q=vB(F),V=Y.newString(`Promise resolution error: ${q}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=vB(H),q=Y.newString(`Promise rejection: ${F}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return _B(Y,W)}catch(K){let W=vB(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 o36=()=>{};function t36(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 s36(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){t36(Y);let K=await Promise.race([G,Pd4(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 s90({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await a36({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=gB(W,J.newContext({interruptAfterMs:Q}),0);const K=gB(W,w36(G),0);try{let q=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(q),$=_B(G,Y);G.setProp(G.global,"tools",$);let B=G.runtime.hasPendingJob()?G.unwrapResult(await s36(G,V,Q)):V;if(B!==V)V.dispose();let U=G.getProp(B,"default"),D=G.typeof(U);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(U,G.undefined,$),M=G.unwrapResult(L),C=await s36(G,M,Q),R=G.unwrapResult(C);if(G.runtime.hasPendingJob())t36(G);return{returnValue:G.dump(R),consoleLogs:K.logs}}catch(q){return console.log(q),{error:vB(q),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{yP(W,H,F)}}var Pd4=(Y)=>new Promise((X)=>setTimeout(X,Y));var e36=m(()=>{r36();o36()});var YH6=m(()=>{e36()});async function Td4(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 XH6(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 Ad4(Y,X){let Q=new Map;for(let $ of Y)Q.set($.connection.id,$);let J=Y.map(($)=>$.connection),G=new Map,K=await Promise.allSettled(J.map(async($)=>{try{let B=await X.createMCPProxy($);return{connection:$,proxy:B}}catch(B){return console.error(`[code-execution] Failed to create proxy for connection ${$.id}:`,B),null}}));for(let $ of K)if($.status==="fulfilled"&&$.value)G.set($.value.connection.id,$.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([$,B])=>{try{let D=(await B.proxy.listTools()).tools,L=Q.get($);if(L?.selectedTools&&L.selectedTools.length>0){let M=new Set(L.selectedTools);D=D.filter((C)=>M.has(C.name))}return{connectionId:$,connectionTitle:B.connection.title,tools:D}}catch(U){return console.error(`[code-execution] Failed to list tools for connection ${$}:`,U),null}})),Z=new Set,H=[],F=new Map;for(let $ of W){if($.status!=="fulfilled"||!$.value)continue;let{connectionId:B,connectionTitle:U,tools:D}=$.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:B,connectionTitle:U}}),F.set(L.name,B)}}let q=async($,B)=>{let U=F.get($);if(!U)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};let D=G.get(U);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${$}`}],isError:!0};return await D.proxy.callTool({name:$,arguments:B})},V=[];for(let[,$]of G)V.push($.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:q}}async function yB(Y){let X=S6(Y),Q;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)Q=await Td4(J,Y);else Q=await XH6(X.id,Y)}else Q=await XH6(X.id,Y);return Ad4(Q,Y)}function Ed4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function Cd4(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 QH6(Y,X,Q){let J=Ed4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:Cd4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function JH6(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 GH6(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return s90({code:Y,tools:J,timeoutMs:Q})}var Ff=m(()=>{YH6()});var t90;var WH6=m(()=>{J4();qP();Ff();t90=X6({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:U36,outputSchema:D36,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await yB(X),J=QH6(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 e90;var ZH6=m(()=>{J4();qP();Ff();e90=X6({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:O36,outputSchema:N36,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await yB(X);return JH6(Y.tools,Q.tools)}})});var YY0;var KH6=m(()=>{J4();qP();Ff();YY0=X6({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:L36,outputSchema:M36,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await yB(X);return await GH6(Y.code,Q,Y.timeoutMs)}})});var HH6=m(()=>{WH6();ZH6();KH6();qP()});var Rd4,Sd4,XY0;var FH6=m(()=>{NB();t0();J4();Gf();oK();Rd4=N.object({data:iZ6.describe("Data for the new connection (id is auto-generated if not provided)")}),Sd4=N.object({item:fJ.describe("The created connection entity")}),XY0=X6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Rd4,outputSchema:Sd4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=_8(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=sy(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=ty(H)}let K=await SB({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,k5.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function $P(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)=>$P(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)&&$P(Y[G],X[G]))}return!1}function td4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>$P(Q,G)))return!1;return X.push(Q),!0})}}function qf(Y,X){return Y.safeParse(X).success}function VY(Y){if(typeof Y==="boolean")return Y?N.any():N.never();let X={};for(let G of $p4)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||N.string());if(X.number!==!1)Q.push(X.number||N.number());if(X.boolean!==!1)Q.push(X.boolean||N.boolean());if(X.null!==!1)Q.push(X.null||N.null());if(X.array!==!1)Q.push(X.array||N.array(N.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=N.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=N.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=N.any();else J=N.union(Q);for(let G of zp4)J=G.apply(J,Y);return J}var jd4=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||N.number();if(G instanceof N.ZodNumber)Y.number=G.int()}}},kd4=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=N.literal(Q);else if(typeof Q==="number")Y.number=N.literal(Q);else if(typeof Q==="boolean")Y.boolean=N.literal(Q);else if(Q===null)Y.null=N.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},vd4=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?N.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 N.literal(Y[0]);if(X==="string")return N.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return N.union([N.literal(Q),N.literal(J),...G.map((K)=>N.literal(K))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},_d4=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=N.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}}},yd4=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=N.string()}}},fd4=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},hd4=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},bd4=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},xd4=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.min(Q.minimum)}}},ud4=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.max(Q.maximum)}}},gd4=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},md4=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},ld4=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.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}`})}}},dd4=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=N.array(N.any())}}},pd4=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).min(Q.minItems)}},cd4=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).max(Q.maxItems)}},nd4=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||N.array(N.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=VY(Q.items),G=N.array(J);if(Y.array&&Y.array instanceof N.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=N.array(N.any()).max(0);else Y.array=Y.array||N.array(N.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||N.array(N.any());else if(Q.prefixItems)Y.array=Y.array||N.array(N.any())}},id4=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)=>VY(K)),G;if(J.length===0)G=N.tuple([]);else G=N.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}},ad4=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||N.object({}).passthrough()}},rd4=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=N.object({}).passthrough()}}},od4=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},sd4=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},ed4=class{apply(Y,X){if(!X.not)return Y;let Q=VY(X.not);return Y.refine((J)=>!qf(Q,J),{message:"Value must not match the 'not' schema"})}},Yp4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(td4(),{message:"Array items must be unique"})}},Xp4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>VY(J)).reduce((J,G)=>N.intersection(J,G),Y)}},Qp4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?VY(X.anyOf[0]):N.union([VY(X.anyOf[0]),VY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>VY(J))]);return N.intersection(Y,Q)}},Jp4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>VY(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"})}},Gp4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>VY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!qf(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=VY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!qf(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},Wp4=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof N.ZodObject||Y instanceof N.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=VY(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 N.object(J);else return N.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(!VY(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"})}},Zp4=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)=>$P(J,G))},{message:"Value must match one of the enum values"})}},Kp4=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)=>$P(J,Q),{message:"Value must equal the const value"})}},Hp4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},Fp4=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 N.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))}},qp4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=VY(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(qf(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"})}},Vp4=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)}},$p4,zp4;var qH6=m(()=>{I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();$p4=[new kd4,new vd4,new jd4,new _d4,new yd4,new dd4,new rd4,new fd4,new hd4,new bd4,new xd4,new ud4,new gd4,new md4,new ld4,new id4,new pd4,new cd4,new nd4,new od4,new sd4,new ad4],zp4=[new Fp4,new Zp4,new Kp4,new Xp4,new Qp4,new Jp4,new Gp4,new Wp4,new qp4,new ed4,new Yp4,new Vp4,new Hp4]});class QY0{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,Bp4),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=SQ.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 Bp4="mcp";var VH6=m(()=>{cX()});function Up4(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 JY0;var $H6=m(()=>{ny();JY0=class JY0 extends OB{constructor(Y,X){super(Y,X)}send(Y,X){let Q=Up4(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 zH6,BH6=async(Y,X,Q)=>{let J=Dp4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new zH6({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[V,$]of Object.entries(Y.connection.headers??{}))H.set(V,$);let F=new URL(Y.connection.url),q=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${q}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},Dp4=(Y,X,Q)=>{if(Y.type==="Websocket")return new QY0(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 FP(new URL(Y.url),K)}return new JY0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var UH6=m(()=>{jy();U90();VH6();cX();$H6();zH6=class zH6 extends iK{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},Cw,X)}}});function OH6(Y){let X=(Q)=>{if("connection"in Y)return BH6({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 q=Y?.debugId?.(),V=q?{"x-trace-debug-id":q}:void 0,{client:$,callStreamableTool:B}=await X(V);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:U,isError:D,content:L}=await $.callTool({name:String(F),arguments:H});if(D){let M=L?.[0]?.text,C=typeof M==="string"?Op4(M):null,R=C?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(R)throw R;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(U??L)}`)}return U}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(!Vf.has(F))Vf.set(F,K());return await Vf.get(F)}catch(q){console.error("Failed to list tools",q),Vf.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>DH6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((q)=>q.name===J);if(!F)throw Error(`Tool ${J} not found`);return DH6(F,G)},G}})}var Op4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},Vf,DH6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?VY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?VY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var NH6=m(()=>{qH6();UH6();Vf=new Map});function $f(Y){return OH6(Y)}var Ro1;var LH6=m(()=>{NH6();Ro1=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>$f({connection:Q});return global[X]}})});function zf(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 Xq=(Y)=>{return{...zf(Y),forClient:(X)=>{return $f({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return $f({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var zP=m(()=>{LH6()});var GY0,_o1;var MH6=m(()=>{aM();GY0=R1(iM(),1),_o1=GY0.createContext(null)});function hW(Y){return N.object({items:N.array(Y).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function UP(Y){return N.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function Mp4(Y){return N.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function wp4(Y){return N.object({item:Y.describe("The created entity with generated id")})}function Pp4(Y){return N.object({id:N.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function Tp4(Y){return N.object({item:Y.describe("The updated entity")})}function OP(Y){return N.object({item:Y.describe("The deleted entity")})}function hB(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:fW,outputSchema:hW(X)},{name:`COLLECTION_${J}_GET`,inputSchema:BP,outputSchema:UP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Mp4(X),outputSchema:wp4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:Pp4(X),outputSchema:Tp4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:DP,outputSchema:OP(X),opt:!0});return K}var fB,Np4,wH6,Lp4,fW,BP,DP;var hJ=m(()=>{t0();fB=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),Np4=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),wH6=N.lazy(()=>N.union([Np4,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(wH6)})])),Lp4=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),fW=N.object({where:wH6.optional().describe("Filter expression"),orderBy:N.array(Lp4).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});BP=N.object({id:N.string().describe("ID of the entity to retrieve")});DP=N.object({id:N.string().describe("ID of the entity to delete")})});var Ap4,PH6,go1;var TH6=m(()=>{t0();hJ();Ap4=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),PH6=fB.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Ap4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),go1=hB("registry_app",PH6,{readOnly:!0})});var AH6,EH6,CH6,IH6,RH6,Ep4;var SH6=m(()=>{t0();zP();AH6=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),EH6=N.object({events:N.array(AH6).min(1).describe("Batch of CloudEvents to process")}),CH6=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),IH6=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),CH6).optional().describe("Per-event results keyed by event ID")}),RH6=[{name:"ON_EVENTS",inputSchema:EH6,outputSchema:IH6}],Ep4=Xq(RH6)});var NP,LP,MP,wP,jH6,kH6,PP,TP,AP,EP,CP,IP,RP,SP,vH6,Cp4;var _H6=m(()=>{t0();zP();NP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),LP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),MP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),wP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),jH6=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),kH6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),PP=N.object({subscriptions:N.array(jH6).describe("Desired subscriptions - system will create/update/delete to match")}),TP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(kH6).describe("Current subscriptions after sync")}),AP=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),EP=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),CP=N.object({eventId:N.string().describe("Event ID to cancel")}),IP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),RP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),SP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),vH6=[{name:"EVENT_PUBLISH",inputSchema:NP,outputSchema:LP},{name:"EVENT_SUBSCRIBE",inputSchema:MP,outputSchema:wP},{name:"EVENT_UNSUBSCRIBE",inputSchema:AP,outputSchema:EP},{name:"EVENT_CANCEL",inputSchema:CP,outputSchema:IP},{name:"EVENT_ACK",inputSchema:RP,outputSchema:SP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:PP,outputSchema:TP}],Cp4=Xq(vH6)});var Ip4,Rp4,Sp4,jp4,kp4,vp4,_p4,yp4,fp4,hp4,bp4,xp4,jP;var Bf=m(()=>{t0();Ip4=N.object({prefix:N.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N.string().optional().describe("Token for pagination from previous response"),delimiter:N.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Rp4=N.object({objects:N.array(N.object({key:N.string().describe("Object key/path"),size:N.number().describe("Object size in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object")})),nextContinuationToken:N.string().optional().describe("Token for fetching next page of results"),isTruncated:N.boolean().describe("Whether there are more results available"),commonPrefixes:N.array(N.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Sp4=N.object({key:N.string().describe("Object key/path to get metadata for")}),jp4=N.object({contentType:N.string().optional().describe("MIME type of the object"),contentLength:N.number().describe("Size of the object in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object"),metadata:N.record(N.string(),N.string()).optional().describe("Custom metadata key-value pairs")}),kp4=N.object({key:N.string().describe("Object key/path to generate URL for"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),vp4=N.object({url:N.string().describe("Presigned URL for downloading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),_p4=N.object({key:N.string().describe("Object key/path for the upload"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N.string().optional().describe("MIME type for the object being uploaded")}),yp4=N.object({url:N.string().describe("Presigned URL for uploading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),fp4=N.object({key:N.string().describe("Object key/path to delete")}),hp4=N.object({success:N.boolean().describe("Whether the deletion was successful"),key:N.string().describe("The key that was deleted")}),bp4=N.object({keys:N.array(N.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),xp4=N.object({deleted:N.array(N.string()).describe("Array of successfully deleted keys"),errors:N.array(N.object({key:N.string(),message:N.string()})).describe("Array of errors for failed deletions")}),jP=[{name:"LIST_OBJECTS",inputSchema:Ip4,outputSchema:Rp4},{name:"GET_OBJECT_METADATA",inputSchema:Sp4,outputSchema:jp4},{name:"GET_PRESIGNED_URL",inputSchema:kp4,outputSchema:vp4},{name:"PUT_PRESIGNED_URL",inputSchema:_p4,outputSchema:yp4},{name:"DELETE_OBJECT",inputSchema:fp4,outputSchema:hp4},{name:"DELETE_OBJECTS",inputSchema:bp4,outputSchema:xp4}]});var WY0=m(()=>{zP();MH6();TH6();SH6();_H6();Bf()});var up4,gp4,yH6;var fH6=m(()=>{t0();hJ();up4=fB.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:N.string().describe("Virtual MCP ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),gp4=hB("assistant",up4),yH6=[...gp4]});var kP,bW,bH6,mp4,lp4,xH6,dp4,pp4,cp4,np4,ip4,ap4,uH6,rp4,op4,sp4,tp4,ep4,Yc4,Xc4,Qc4,Jc4,Gc4,zs1,Wc4,Bs1,hH6,Zc4,Kc4,ZY0,Us1;var gH6=m(()=>{t0();zP();hJ();kP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),kP),N.array(kP)])),bW=N.record(N.string(),N.record(N.string(),kP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),bH6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:bW}),mp4=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),lp4=N.string().describe("File data as URL string"),xH6=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:lp4,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:bW}),dp4=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),pp4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:bW}),cp4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),np4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:bW}),ip4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),ap4=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:kP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:kP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),uH6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:ap4.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:bW}),rp4=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),op4=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),sp4=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:bW}),tp4=N.object({role:N.literal("user"),content:N.array(N.union([bH6,xH6])).describe("User message content parts (text or file)"),providerOptions:bW}),ep4=N.object({role:N.literal("assistant"),content:N.array(N.union([bH6,xH6,pp4,np4,uH6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:bW}),Yc4=N.object({role:N.literal("tool"),content:N.array(uH6).describe("Tool message content (tool results)"),providerOptions:bW}),Xc4=N.union([sp4,tp4,ep4,Yc4]),Qc4=N.array(Xc4).describe("A list of messages forming the prompt"),Jc4=N.object({prompt:Qc4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.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:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),Gc4=N.object({content:N.array(N.union([mp4,dp4,cp4,ip4,rp4,op4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),zs1=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Wc4=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),Bs1=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),hH6=N.object({modelId:N.string().describe("The ID of the model"),callOptions:Jc4}),Zc4=fB.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Kc4=hB("llm",Zc4,{readOnly:!0}),ZY0=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:Wc4},{name:"LLM_DO_STREAM",inputSchema:hH6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:hH6,outputSchema:Gc4},...Kc4],Us1=Xq(ZY0)});function Uf(){return!1}function mH6(Y,X){return Y===k5.DEV_ASSETS(X)}function Df(Y,X){let Q=d80(X,Y),J=new Date().toISOString();return{id:Q.id??k5.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:Hc4,bindings:["OBJECT_STORAGE"],status:"active"}}var Hc4;var KY0=m(()=>{Bf();NB();t0();Hc4=jP.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:N.toJSONSchema(Y.outputSchema)}))});function qc4(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 eK(Y){return typeof Y==="string"||typeof Y==="number"}function Of(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>Of(Y,F));case"or":return H.some((F)=>Of(Y,F));case"not":return!H.every((F)=>Of(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=HY0(Y,K);switch(J){case"eq":return W===G;case"gt":return eK(W)&&eK(G)&&W>G;case"gte":return eK(W)&&eK(G)&&W>=G;case"lt":return eK(W)&&eK(G)&&W<G;case"lte":return eK(W)&&eK(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=qc4(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 HY0(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 Vc4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=HY0(Q,K),Z=HY0(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 Fc4,$c4,zc4,FY0;var lH6=m(()=>{WY0();fH6();hJ();gH6();Bf();NB();t0();J4();KY0();oK();Fc4={LLM:ZY0,ASSISTANTS:yH6,OBJECT_STORAGE:jP};$c4=fW.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),zc4=hW(fJ),FY0=X6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:$c4,outputSchema:zc4,handler:async(Y,X)=>{await X.access.check();let Q=S6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=Fc4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?zf(J):void 0,K=await X.storage.connections.list(Q.id);if(Uf()){let B=o7(),U=k5.DEV_ASSETS(Q.id);if(!K.some((D)=>D.id===U)){let D=Df(Q.id,B);K.unshift(D)}}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((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):W;if(Y.where)Z=Z.filter((B)=>Of(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=Vc4(Z,Y.orderBy);let H=Z.length,F=Y.offset??0,q=Y.limit??100,V=Z.slice(F,F+q),$=F+q<H;return{items:V,totalCount:H,hasMore:$}}})});var Bc4,qY0;var dH6=m(()=>{hJ();J4();KY0();oK();Bc4=UP(fJ),qY0=X6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:BP,outputSchema:Bc4,handler:async(Y,X)=>{let Q=S6(X);if(await X.access.check(),Uf()&&mH6(Y.id,Q.id))return{item:Df(Q.id,o7())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var Nf=(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 pH6(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 Uc4(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function Dc4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function Oc4(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=Uc4(J);if(!G)continue;let[K,W]=G,Z=Nf(K,Y),H=Dc4(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function cH6(Y,X){let Q=Oc4(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var nH6=()=>{};class VY0{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=MB("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 iH6=m(()=>{ey()});async function Mc4(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=pH6(K),Z=Nf(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=cH6(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 Nc4,Lc4,$Y0;var aH6=m(()=>{nH6();iH6();t0();J4();Gf();oK();Nc4=N.object({id:N.string().describe("ID of the connection to update"),data:aZ6.describe("Partial connection data to update")}),Lc4=N.object({item:fJ.describe("The updated connection entity")});$Y0=X6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:Nc4,outputSchema:Lc4,handler:async(Y,X)=>{$6(X);let Q=S6(X);if(await X.access.check(),!_8(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 T=sy(H);if(!T)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let I=await X.storage.virtualMcps.findById(T);if(!I)throw Error(`Virtual MCP not found: ${T}`);if(I.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=ty(T)}let F=K.configuration_state??W.configuration_state,q=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)q=K.configuration_scopes??[];if(q.length>0&&F)await Mc4(F,q,Q.id,X)}let V=K.connection_token??W.connection_token;if(!V)try{let I=await new VY0(X.db,X.vault).get(G);if(I?.accessToken)V=I.accessToken}catch{}let $=await SB({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:V,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=$?.length?$:null,U={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:q},D=await X.storage.connections.update(G,U);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&q.length>0)try{let L=[];try{const T=gB(L,await X.createMCPProxy(G),1);await T.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:q}});await T.close().catch(console.error)}catch(M){var C=M,R=1}finally{var E=yP(L,C,R);E&&await E}}catch(T){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",T)}return{item:D}}})});var zY0;var rH6=m(()=>{hJ();J4();oK();zY0=X6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:DP,outputSchema:OP(fJ),handler:async(Y,X)=>{$6(X);let Q=S6(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 BY0;var oH6=m(()=>{t0();J4();BY0=X6({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Y,X)=>{let Q=S6(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 sH6=m(()=>{FH6();lH6();dH6();aH6();rH6();oH6()});import{sql as s4}from"kysely";function tH6(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 Tc4(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,tH6(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=tH6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function eH6(Y){return Y.replace(/-/g,"_")}function Ec4(Y){return`app_${eH6(Y)}`}function Cc4(Y){return`app_role_${eH6(Y)}`}function Ic4(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 Rc4(Y,X,Q){if(await s4`CREATE SCHEMA IF NOT EXISTS ${s4.id(X)}`.execute(Y),!(await s4`
|
|
407
|
+
${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 _B(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=_B(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=_B(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=_B(Y,H);Z.resolve(F),F.dispose(),Y.runtime.executePendingJobs()}catch(F){let q=vB(F),V=Y.newString(`Promise resolution error: ${q}`);Z.reject(V),V.dispose(),Y.runtime.executePendingJobs()}}).catch((H)=>{let F=vB(H),q=Y.newString(`Promise rejection: ${F}`);Z.reject(q),q.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return _B(Y,W)}catch(K){let W=vB(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 o36=()=>{};function t36(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 s36(Y,X,Q){let J=Date.now(),G=Y.resolvePromise(X);while(!0){t36(Y);let K=await Promise.race([G,Pd4(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 s90({tools:Y,code:X,timeoutMs:Q}){let W=[];try{let J=await a36({memoryLimitBytes:33554432,stackSizeBytes:524288});const G=gB(W,J.newContext({interruptAfterMs:Q}),0);const K=gB(W,w36(G),0);try{let q=G.evalCode(X,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(q),$=_B(G,Y);G.setProp(G.global,"tools",$);let B=G.runtime.hasPendingJob()?G.unwrapResult(await s36(G,V,Q)):V;if(B!==V)V.dispose();let U=G.getProp(B,"default"),D=G.typeof(U);if(D!=="function")return{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(U,G.undefined,$),M=G.unwrapResult(L),C=await s36(G,M,Q),R=G.unwrapResult(C);if(G.runtime.hasPendingJob())t36(G);return{returnValue:G.dump(R),consoleLogs:K.logs}}catch(q){return console.log(q),{error:vB(q),consoleLogs:K.logs}}}catch(Z){var H=Z,F=1}finally{yP(W,H,F)}}var Pd4=(Y)=>new Promise((X)=>setTimeout(X,Y));var e36=m(()=>{r36();o36()});var YH6=m(()=>{e36()});async function Td4(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 XH6(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 Ad4(Y,X){let Q=new Map;for(let $ of Y)Q.set($.connection.id,$);let J=Y.map(($)=>$.connection),G=new Map,K=await Promise.allSettled(J.map(async($)=>{try{let B=await X.createMCPProxy($);return{connection:$,proxy:B}}catch(B){return console.warn(`[code-execution] Failed to create proxy for connection ${$.id}:`,B),null}}));for(let $ of K)if($.status==="fulfilled"&&$.value)G.set($.value.connection.id,$.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([$,B])=>{try{let D=(await B.proxy.listTools()).tools,L=Q.get($);if(L?.selectedTools&&L.selectedTools.length>0){let M=new Set(L.selectedTools);D=D.filter((C)=>M.has(C.name))}return{connectionId:$,connectionTitle:B.connection.title,tools:D}}catch(U){return console.error(`[code-execution] Failed to list tools for connection ${$}:`,U),null}})),Z=new Set,H=[],F=new Map;for(let $ of W){if($.status!=="fulfilled"||!$.value)continue;let{connectionId:B,connectionTitle:U,tools:D}=$.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:B,connectionTitle:U}}),F.set(L.name,B)}}let q=async($,B)=>{let U=F.get($);if(!U)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};let D=G.get(U);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${$}`}],isError:!0};return await D.proxy.callTool({name:$,arguments:B})},V=[];for(let[,$]of G)V.push($.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:q}}async function yB(Y){let X=S6(Y),Q;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)Q=await Td4(J,Y);else Q=await XH6(X.id,Y)}else Q=await XH6(X.id,Y);return Ad4(Q,Y)}function Ed4(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((X)=>X.length>=2)}function Cd4(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 QH6(Y,X,Q){let J=Ed4(Y);if(J.length===0)return X.slice(0,Q);return X.map((G)=>({tool:G,score:Cd4(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,Q).map((G)=>G.tool)}function JH6(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 GH6(Y,X,Q){let J=Object.fromEntries(X.tools.map((G)=>[G.name,async(K)=>X.callTool(G.name,K??{})]));return s90({code:Y,tools:J,timeoutMs:Q})}var Ff=m(()=>{YH6()});var t90;var WH6=m(()=>{J4();qP();Ff();t90=X6({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:U36,outputSchema:D36,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await yB(X),J=QH6(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 e90;var ZH6=m(()=>{J4();qP();Ff();e90=X6({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:O36,outputSchema:N36,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await yB(X);return JH6(Y.tools,Q.tools)}})});var YY0;var KH6=m(()=>{J4();qP();Ff();YY0=X6({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:L36,outputSchema:M36,handler:async(Y,X)=>{$6(X),S6(X),await X.access.check();let Q=await yB(X);return await GH6(Y.code,Q,Y.timeoutMs)}})});var HH6=m(()=>{WH6();ZH6();KH6();qP()});var Rd4,Sd4,XY0;var FH6=m(()=>{NB();t0();J4();Gf();oK();Rd4=N.object({data:iZ6.describe("Data for the new connection (id is auto-generated if not provided)")}),Sd4=N.object({item:fJ.describe("The created connection entity")}),XY0=X6({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",inputSchema:Rd4,outputSchema:Sd4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=_8(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=sy(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=ty(H)}let K=await SB({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,k5.SELF(Q.id),{type:"connection.created",data:Z}),{item:Z}}})});function $P(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)=>$P(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)&&$P(Y[G],X[G]))}return!1}function td4(){return(Y)=>{if(!Array.isArray(Y))return!0;let X=[];return Y.every((Q)=>{if(X.some((G)=>$P(Q,G)))return!1;return X.push(Q),!0})}}function qf(Y,X){return Y.safeParse(X).success}function VY(Y){if(typeof Y==="boolean")return Y?N.any():N.never();let X={};for(let G of $p4)G.apply(X,Y);let Q=[];if(X.string!==!1)Q.push(X.string||N.string());if(X.number!==!1)Q.push(X.number||N.number());if(X.boolean!==!1)Q.push(X.boolean||N.boolean());if(X.null!==!1)Q.push(X.null||N.null());if(X.array!==!1)Q.push(X.array||N.array(N.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=N.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=N.never();else if(Q.length===1)J=Q[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=N.any();else J=N.union(Q);for(let G of zp4)J=G.apply(J,Y);return J}var jd4=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||N.number();if(G instanceof N.ZodNumber)Y.number=G.int()}}},kd4=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=N.literal(Q);else if(typeof Q==="number")Y.number=N.literal(Q);else if(typeof Q==="boolean")Y.boolean=N.literal(Q);else if(Q===null)Y.null=N.null();else if(Array.isArray(Q))Y.array=void 0;else if(typeof Q==="object")Y.object=void 0}},vd4=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?N.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 N.literal(Y[0]);if(X==="string")return N.enum(Y);if(X==="number"){let[Q,J,...G]=Y;return N.union([N.literal(Q),N.literal(J),...G.map((K)=>N.literal(K))])}if(X==="boolean")return N.union([N.literal(!0),N.literal(!1)]);return!1}},_d4=class{apply(Y,X){let Q=X;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let J=N.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}}},yd4=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=N.string()}}},fd4=class{apply(Y,X){let Q=X;if(Q.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},hd4=class{apply(Y,X){let Q=X;if(Q.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},bd4=class{apply(Y,X){let Q=X;if(!Q.pattern)return;if(Y.string!==!1){let J=Y.string||N.string();if(J instanceof N.ZodString){let G=new RegExp(Q.pattern);Y.string=J.regex(G)}}}},xd4=class{apply(Y,X){let Q=X;if(Q.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.min(Q.minimum)}}},ud4=class{apply(Y,X){let Q=X;if(Q.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)Y.number=J.max(Q.maximum)}}},gd4=class{apply(Y,X){let Q=X;if(Q.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMinimum==="number")Y.number=J.gt(Q.exclusiveMinimum);else Y.number=!1}}},md4=class{apply(Y,X){let Q=X;if(Q.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.ZodNumber)if(typeof Q.exclusiveMaximum==="number")Y.number=J.lt(Q.exclusiveMaximum);else Y.number=!1}}},ld4=class{apply(Y,X){let Q=X;if(Q.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||N.number();if(J instanceof N.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}`})}}},dd4=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=N.array(N.any())}}},pd4=class{apply(Y,X){let Q=X;if(Q.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).min(Q.minItems)}},cd4=class{apply(Y,X){let Q=X;if(Q.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||N.array(N.any())).max(Q.maxItems)}},nd4=class{apply(Y,X){let Q=X;if(Y.array===!1)return;if(Array.isArray(Q.items))Y.array=Y.array||N.array(N.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let J=VY(Q.items),G=N.array(J);if(Y.array&&Y.array instanceof N.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=N.array(N.any()).max(0);else Y.array=Y.array||N.array(N.any());else if(typeof Q.items==="boolean"&&Q.items===!0)Y.array=Y.array||N.array(N.any());else if(Q.prefixItems)Y.array=Y.array||N.array(N.any())}},id4=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)=>VY(K)),G;if(J.length===0)G=N.tuple([]);else G=N.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}},ad4=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||N.object({}).passthrough()}},rd4=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=N.object({}).passthrough()}}},od4=class{apply(Y,X){let Q=X;if(Q.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},sd4=class{apply(Y,X){let Q=X;if(Q.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||N.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},ed4=class{apply(Y,X){if(!X.not)return Y;let Q=VY(X.not);return Y.refine((J)=>!qf(Q,J),{message:"Value must not match the 'not' schema"})}},Yp4=class{apply(Y,X){if(X.uniqueItems!==!0)return Y;return Y.refine(td4(),{message:"Array items must be unique"})}},Xp4=class{apply(Y,X){if(!X.allOf||X.allOf.length===0)return Y;return X.allOf.map((J)=>VY(J)).reduce((J,G)=>N.intersection(J,G),Y)}},Qp4=class{apply(Y,X){if(!X.anyOf||X.anyOf.length===0)return Y;let Q=X.anyOf.length===1?VY(X.anyOf[0]):N.union([VY(X.anyOf[0]),VY(X.anyOf[1]),...X.anyOf.slice(2).map((J)=>VY(J))]);return N.intersection(Y,Q)}},Jp4=class{apply(Y,X){if(!X.oneOf||X.oneOf.length===0)return Y;let Q=X.oneOf.map((J)=>VY(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"})}},Gp4=class{apply(Y,X){let Q=X;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let G=Q.prefixItems.map((K)=>VY(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!qf(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=VY(Q.items);for(let Z=G.length;Z<K.length;Z++)if(!qf(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},Wp4=class{apply(Y,X){let Q=X;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return Y;if(Y instanceof N.ZodObject||Y instanceof N.ZodRecord){let J={};if(Q.properties){for(let[G,K]of Object.entries(Q.properties))if(K!==void 0)J[G]=VY(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 N.object(J);else return N.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(!VY(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"})}},Zp4=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)=>$P(J,G))},{message:"Value must match one of the enum values"})}},Kp4=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)=>$P(J,Q),{message:"Value must equal the const value"})}},Hp4=class{apply(Y,X){if(X.description)Y=Y.describe(X.description);return Y}},Fp4=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 N.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))}},qp4=class{apply(Y,X){var Q;let J=X;if(J.contains===void 0)return Y;let G=VY(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(qf(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"})}},Vp4=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)}},$p4,zp4;var qH6=m(()=>{I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();I9();$p4=[new kd4,new vd4,new jd4,new _d4,new yd4,new dd4,new rd4,new fd4,new hd4,new bd4,new xd4,new ud4,new gd4,new md4,new ld4,new id4,new pd4,new cd4,new nd4,new od4,new sd4,new ad4],zp4=[new Fp4,new Zp4,new Kp4,new Xp4,new Qp4,new Jp4,new Gp4,new Wp4,new qp4,new ed4,new Yp4,new Vp4,new Hp4]});class QY0{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,Bp4),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=SQ.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 Bp4="mcp";var VH6=m(()=>{cX()});function Up4(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 JY0;var $H6=m(()=>{ny();JY0=class JY0 extends OB{constructor(Y,X){super(Y,X)}send(Y,X){let Q=Up4(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 zH6,BH6=async(Y,X,Q)=>{let J=Dp4(Y.connection,X,Q);if(!J)throw Error("Unknown MCP connection type");let G=new zH6({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[V,$]of Object.entries(Y.connection.headers??{}))H.set(V,$);let F=new URL(Y.connection.url),q=F.pathname.replace(/\/+$/,"")||"/";return F.pathname=`${q}/call-tool/${encodeURIComponent(K)}`,fetch(F.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},Dp4=(Y,X,Q)=>{if(Y.type==="Websocket")return new QY0(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 FP(new URL(Y.url),K)}return new JY0(new URL(Y.url),{requestInit:{headers:G,signal:X,credentials:"include"}})};var UH6=m(()=>{jy();U90();VH6();cX();$H6();zH6=class zH6 extends iK{constructor(Y,X){super(Y,X)}async listTools(Y,X){return await this.request({method:"tools/list",params:Y},Cw,X)}}});function OH6(Y){let X=(Q)=>{if("connection"in Y)return BH6({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 q=Y?.debugId?.(),V=q?{"x-trace-debug-id":q}:void 0,{client:$,callStreamableTool:B}=await X(V);if(Y?.streamable?.[String(F)])return B(String(F),H);let{structuredContent:U,isError:D,content:L}=await $.callTool({name:String(F),arguments:H});if(D){let M=L?.[0]?.text,C=typeof M==="string"?Op4(M):null,R=C?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(C.code,C.message,C.traceId):null;if(R)throw R;throw Error(`Tool ${String(F)} returned an error: ${JSON.stringify(U??L)}`)}return U}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(!Vf.has(F))Vf.set(F,K());return await Vf.get(F)}catch(q){console.error("Failed to list tools",q),Vf.delete(F);return}}async function Z(){return(await W()??[]).map((F)=>DH6(F,G))}return G.asTool=async()=>{let F=(await W()??[]).find((q)=>q.name===J);if(!F)throw Error(`Tool ${J} not found`);return DH6(F,G)},G}})}var Op4=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},Vf,DH6=(Y,X)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?VY(Y.inputSchema):void 0,outputSchema:Y.outputSchema?VY(Y.outputSchema):void 0,execute:(Q)=>{return X(Q.context,Y.name)}}};var NH6=m(()=>{qH6();UH6();Vf=new Map});function $f(Y){return OH6(Y)}var Ro1;var LH6=m(()=>{NH6();Ro1=new Proxy({},{get(Y,X){if(X==="toJSON")return null;if(X==="forConnection")return(Q)=>$f({connection:Q});return global[X]}})});function zf(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 Xq=(Y)=>{return{...zf(Y),forClient:(X)=>{return $f({client:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})},forConnection:(X)=>{return $f({connection:X,streamable:Y.reduce((Q,J)=>{return Q[J.name]=J.streamable===!0,Q},{})})}}};var zP=m(()=>{LH6()});var GY0,_o1;var MH6=m(()=>{aM();GY0=R1(iM(),1),_o1=GY0.createContext(null)});function hW(Y){return N.object({items:N.array(Y).describe("Array of collection items"),totalCount:N.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:N.boolean().optional().describe("Whether there are more items available")})}function UP(Y){return N.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function Mp4(Y){return N.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function wp4(Y){return N.object({item:Y.describe("The created entity with generated id")})}function Pp4(Y){return N.object({id:N.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function Tp4(Y){return N.object({item:Y.describe("The updated entity")})}function OP(Y){return N.object({item:Y.describe("The deleted entity")})}function hB(Y,X,Q){let J=Y.toUpperCase(),G=Q?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:fW,outputSchema:hW(X)},{name:`COLLECTION_${J}_GET`,inputSchema:BP,outputSchema:UP(X)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:Mp4(X),outputSchema:wp4(X),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:Pp4(X),outputSchema:Tp4(X),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:DP,outputSchema:OP(X),opt:!0});return K}var fB,Np4,wH6,Lp4,fW,BP,DP;var hJ=m(()=>{t0();fB=N.object({id:N.string().describe("Unique identifier for the entity"),title:N.string().describe("Human-readable title for the entity"),description:N.string().nullish().describe("Description of the entity"),created_at:N.string().datetime(),updated_at:N.string().datetime(),created_by:N.string().optional(),updated_by:N.string().optional()}),Np4=N.object({field:N.array(N.string()),operator:N.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:N.unknown()}),wH6=N.lazy(()=>N.union([Np4,N.object({operator:N.enum(["and","or","not"]),conditions:N.array(wH6)})])),Lp4=N.object({field:N.array(N.string()),direction:N.enum(["asc","desc"]),nulls:N.enum(["first","last"]).optional()}),fW=N.object({where:wH6.optional().describe("Filter expression"),orderBy:N.array(Lp4).optional().describe("Sort expressions"),limit:N.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:N.number().int().min(0).optional().describe("Number of items to skip")});BP=N.object({id:N.string().describe("ID of the entity to retrieve")});DP=N.object({id:N.string().describe("ID of the entity to delete")})});var Ap4,PH6,go1;var TH6=m(()=>{t0();hJ();Ap4=N.object({id:N.string(),name:N.string(),description:N.string().optional(),inputSchema:N.record(N.string(),N.unknown()),outputSchema:N.record(N.string(),N.unknown()).optional()}),PH6=fB.extend({_meta:N.object({"io.decocms":N.object({id:N.string(),verified:N.boolean(),scopeName:N.string(),appName:N.string(),friendlyName:N.string().nullable().optional(),metadata:N.record(N.string(),N.unknown()).nullable().optional(),publishedAt:N.string().datetime().optional(),updatedAt:N.string().datetime().optional(),tools:N.array(Ap4).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:N.object({$schema:N.string().optional(),_meta:N.record(N.string(),N.unknown()).optional(),name:N.string().describe("The server name (scope/app)"),title:N.string().optional().describe("User-friendly title"),description:N.string().optional().describe("Server description"),icons:N.array(N.object({src:N.string(),mimeType:N.string().optional(),sizes:N.array(N.string()).optional(),theme:N.enum(["light","dark"]).optional()})).optional(),remotes:N.array(N.object({type:N.enum(["http","stdio","sse"]),url:N.string().optional(),headers:N.array(N.unknown()).optional()})).optional(),packages:N.array(N.unknown()).optional(),repository:N.object({url:N.string(),source:N.string().optional(),subfolder:N.string().optional()}).optional(),version:N.string().optional(),websiteUrl:N.string().optional()})}),go1=hB("registry_app",PH6,{readOnly:!0})});var AH6,EH6,CH6,IH6,RH6,Ep4;var SH6=m(()=>{t0();zP();AH6=N.object({specversion:N.literal("1.0").describe("CloudEvents specification version"),id:N.string().describe("Unique identifier for this event (UUID recommended)"),source:N.string().describe("Connection ID of the event publisher"),type:N.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:N.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:N.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:N.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:N.string().url().optional().describe("URI to the schema for the data attribute"),data:N.unknown().optional().describe("Event payload (any JSON value)")}),EH6=N.object({events:N.array(AH6).min(1).describe("Batch of CloudEvents to process")}),CH6=N.object({success:N.boolean().optional().describe("Whether this event was processed successfully"),error:N.string().optional().describe("Error message for this event"),retryAfter:N.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),IH6=N.object({success:N.boolean().optional().describe("Batch success - applies to events not in results"),error:N.string().optional().describe("Batch error message - applies to events not in results"),processedCount:N.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:N.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:N.record(N.string(),CH6).optional().describe("Per-event results keyed by event ID")}),RH6=[{name:"ON_EVENTS",inputSchema:EH6,outputSchema:IH6}],Ep4=Xq(RH6)});var NP,LP,MP,wP,jH6,kH6,PP,TP,AP,EP,CP,IP,RP,SP,vH6,Cp4;var _H6=m(()=>{t0();zP();NP=N.object({type:N.string().min(1).max(255).describe("Event type identifier"),subject:N.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:N.unknown().optional().describe("Event payload"),deliverAt:N.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:N.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),LP=N.object({id:N.string().describe("Unique event ID"),type:N.string().describe("Event type"),source:N.string().describe("Source connection ID"),time:N.string().describe("Event timestamp")}),MP=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),wP=N.object({subscription:N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")})}),jH6=N.object({eventType:N.string().min(1).max(255).describe("Event type to subscribe to"),publisher:N.string().optional().describe("Filter events by publisher connection ID"),filter:N.string().max(1000).optional().describe("JSONPath filter expression on event data")}),kH6=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),PP=N.object({subscriptions:N.array(jH6).describe("Desired subscriptions - system will create/update/delete to match")}),TP=N.object({created:N.number().int().min(0).describe("Number of subscriptions created"),updated:N.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:N.number().int().min(0).describe("Number of subscriptions removed"),unchanged:N.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:N.array(kH6).describe("Current subscriptions after sync")}),AP=N.object({subscriptionId:N.string().describe("Subscription ID to remove")}),EP=N.object({success:N.boolean().describe("Whether unsubscribe was successful"),subscriptionId:N.string().describe("Subscription ID that was removed")}),CP=N.object({eventId:N.string().describe("Event ID to cancel")}),IP=N.object({success:N.boolean().describe("Whether cancellation was successful"),eventId:N.string().describe("Event ID that was cancelled")}),RP=N.object({eventId:N.string().describe("Event ID to acknowledge")}),SP=N.object({success:N.boolean().describe("Whether ACK was successful"),eventId:N.string().describe("Event ID that was acknowledged")}),vH6=[{name:"EVENT_PUBLISH",inputSchema:NP,outputSchema:LP},{name:"EVENT_SUBSCRIBE",inputSchema:MP,outputSchema:wP},{name:"EVENT_UNSUBSCRIBE",inputSchema:AP,outputSchema:EP},{name:"EVENT_CANCEL",inputSchema:CP,outputSchema:IP},{name:"EVENT_ACK",inputSchema:RP,outputSchema:SP},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:PP,outputSchema:TP}],Cp4=Xq(vH6)});var Ip4,Rp4,Sp4,jp4,kp4,vp4,_p4,yp4,fp4,hp4,bp4,xp4,jP;var Bf=m(()=>{t0();Ip4=N.object({prefix:N.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N.string().optional().describe("Token for pagination from previous response"),delimiter:N.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Rp4=N.object({objects:N.array(N.object({key:N.string().describe("Object key/path"),size:N.number().describe("Object size in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object")})),nextContinuationToken:N.string().optional().describe("Token for fetching next page of results"),isTruncated:N.boolean().describe("Whether there are more results available"),commonPrefixes:N.array(N.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Sp4=N.object({key:N.string().describe("Object key/path to get metadata for")}),jp4=N.object({contentType:N.string().optional().describe("MIME type of the object"),contentLength:N.number().describe("Size of the object in bytes"),lastModified:N.string().describe("Last modified timestamp"),etag:N.string().describe("Entity tag for the object"),metadata:N.record(N.string(),N.string()).optional().describe("Custom metadata key-value pairs")}),kp4=N.object({key:N.string().describe("Object key/path to generate URL for"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),vp4=N.object({url:N.string().describe("Presigned URL for downloading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),_p4=N.object({key:N.string().describe("Object key/path for the upload"),expiresIn:N.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N.string().optional().describe("MIME type for the object being uploaded")}),yp4=N.object({url:N.string().describe("Presigned URL for uploading the object"),expiresIn:N.number().describe("Expiration time in seconds that was used")}),fp4=N.object({key:N.string().describe("Object key/path to delete")}),hp4=N.object({success:N.boolean().describe("Whether the deletion was successful"),key:N.string().describe("The key that was deleted")}),bp4=N.object({keys:N.array(N.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),xp4=N.object({deleted:N.array(N.string()).describe("Array of successfully deleted keys"),errors:N.array(N.object({key:N.string(),message:N.string()})).describe("Array of errors for failed deletions")}),jP=[{name:"LIST_OBJECTS",inputSchema:Ip4,outputSchema:Rp4},{name:"GET_OBJECT_METADATA",inputSchema:Sp4,outputSchema:jp4},{name:"GET_PRESIGNED_URL",inputSchema:kp4,outputSchema:vp4},{name:"PUT_PRESIGNED_URL",inputSchema:_p4,outputSchema:yp4},{name:"DELETE_OBJECT",inputSchema:fp4,outputSchema:hp4},{name:"DELETE_OBJECTS",inputSchema:bp4,outputSchema:xp4}]});var WY0=m(()=>{zP();MH6();TH6();SH6();_H6();Bf()});var up4,gp4,yH6;var fH6=m(()=>{t0();hJ();up4=fB.extend({avatar:N.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:N.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:N.string().describe("Virtual MCP ID to use for this assistant"),model:N.object({id:N.string().describe("Model ID"),connectionId:N.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),gp4=hB("assistant",up4),yH6=[...gp4]});var kP,bW,bH6,mp4,lp4,xH6,dp4,pp4,cp4,np4,ip4,ap4,uH6,rp4,op4,sp4,tp4,ep4,Yc4,Xc4,Qc4,Jc4,Gc4,zs1,Wc4,Bs1,hH6,Zc4,Kc4,ZY0,Us1;var gH6=m(()=>{t0();zP();hJ();kP=N.lazy(()=>N.union([N.null(),N.string(),N.number(),N.boolean(),N.record(N.string(),kP),N.array(kP)])),bW=N.record(N.string(),N.record(N.string(),kP)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),bH6=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerOptions:bW}),mp4=N.object({type:N.literal("text"),text:N.string().describe("The text content"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),lp4=N.string().describe("File data as URL string"),xH6=N.object({type:N.literal("file"),filename:N.string().optional().describe("Optional filename of the file"),data:lp4,mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:bW}),dp4=N.object({type:N.literal("file"),mediaType:N.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:N.string().describe("Generated file data as base64 encoded string")}),pp4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerOptions:bW}),cp4=N.object({type:N.literal("reasoning"),text:N.string().describe("The reasoning text"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),np4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call, used to match with tool result"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:bW}),ip4=N.object({type:N.literal("tool-call"),toolCallId:N.string().describe("ID of the tool call"),toolName:N.string().describe("Name of the tool being called"),input:N.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:N.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),ap4=N.union([N.object({type:N.literal("text"),value:N.string()}),N.object({type:N.literal("json"),value:kP}),N.object({type:N.literal("error-text"),value:N.string()}),N.object({type:N.literal("error-json"),value:kP}),N.object({type:N.literal("content"),value:N.array(N.union([N.object({type:N.literal("text"),text:N.string().describe("Text content")}),N.object({type:N.literal("media"),data:N.string().describe("Base-64 encoded media data"),mediaType:N.string().describe("IANA media type")})]))})]),uH6=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),output:ap4.describe("Result of the tool call"),result:N.unknown().describe("Unknown result of the tool call"),providerOptions:bW}),rp4=N.object({type:N.literal("tool-result"),toolCallId:N.string().describe("ID of the tool call that this result is associated with"),toolName:N.string().describe("Name of the tool that generated this result"),result:N.any().describe("Result of the tool call (JSON-serializable)"),isError:N.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:N.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),op4=N.union([N.object({type:N.literal("source"),sourceType:N.literal("url"),id:N.string().describe("The ID of the source"),url:N.string().describe("The URL of the source"),title:N.string().optional().describe("The title of the source"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")}),N.object({type:N.literal("source"),sourceType:N.literal("document"),id:N.string().describe("The ID of the source"),mediaType:N.string().describe("IANA media type of the document (e.g., application/pdf)"),title:N.string().describe("The title of the document"),filename:N.string().optional().describe("Optional filename of the document"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata")})]),sp4=N.object({role:N.literal("system"),content:N.string().describe("System message content"),providerOptions:bW}),tp4=N.object({role:N.literal("user"),content:N.array(N.union([bH6,xH6])).describe("User message content parts (text or file)"),providerOptions:bW}),ep4=N.object({role:N.literal("assistant"),content:N.array(N.union([bH6,xH6,pp4,np4,uH6])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:bW}),Yc4=N.object({role:N.literal("tool"),content:N.array(uH6).describe("Tool message content (tool results)"),providerOptions:bW}),Xc4=N.union([sp4,tp4,ep4,Yc4]),Qc4=N.array(Xc4).describe("A list of messages forming the prompt"),Jc4=N.object({prompt:Qc4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:N.number().optional().describe("Maximum number of tokens to generate"),temperature:N.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:N.number().optional().describe("Nucleus sampling parameter"),topK:N.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:N.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:N.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:N.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:N.array(N.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:N.union([N.object({type:N.literal("text")}),N.object({type:N.literal("json"),schema:N.any().optional().describe("JSON schema that the generated output should conform to"),name:N.string().optional().describe("Name of output that should be generated"),description:N.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:N.array(N.any()).optional().describe("The tools that are available for the model"),toolChoice:N.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:N.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:N.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:N.any().optional().describe("Additional provider-specific options")}),Gc4=N.object({content:N.array(N.union([mp4,dp4,cp4,ip4,rp4,op4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:N.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:N.looseObject({inputTokens:N.number().optional(),outputTokens:N.number().optional(),totalTokens:N.number().optional(),reasoningTokens:N.number().optional()}).describe("Usage information for the language model call"),providerMetadata:N.any().optional().describe("Additional provider-specific metadata"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({id:N.string().optional().describe("ID for the generated response"),timestamp:N.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:N.string().optional().describe("The ID of the response model that was used"),headers:N.record(N.string(),N.string()).optional().describe("Response headers"),body:N.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:N.array(N.any()).describe("Warnings for the call, e.g. unsupported settings")}),zs1=N.object({stream:N.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:N.object({body:N.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:N.object({headers:N.record(N.string(),N.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),Wc4=N.object({supportedUrls:N.record(N.string(),N.array(N.string())).describe("Supported URL patterns by media type for the provider")}),Bs1=N.object({modelId:N.string().describe("The ID of the model"),logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),hH6=N.object({modelId:N.string().describe("The ID of the model"),callOptions:Jc4}),Zc4=fB.extend({logo:N.string().nullable(),description:N.string().nullable(),capabilities:N.array(N.string()),limits:N.object({contextWindow:N.number(),maxOutputTokens:N.number()}).nullable(),costs:N.object({input:N.number(),output:N.number()}).nullable(),provider:N.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),Kc4=hB("llm",Zc4,{readOnly:!0}),ZY0=[{name:"LLM_METADATA",inputSchema:N.object({modelId:N.string().describe("The ID of the model")}),outputSchema:Wc4},{name:"LLM_DO_STREAM",inputSchema:hH6,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:hH6,outputSchema:Gc4},...Kc4],Us1=Xq(ZY0)});function Uf(){return!1}function mH6(Y,X){return Y===k5.DEV_ASSETS(X)}function Df(Y,X){let Q=d80(X,Y),J=new Date().toISOString();return{id:Q.id??k5.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:Hc4,bindings:["OBJECT_STORAGE"],status:"active"}}var Hc4;var KY0=m(()=>{Bf();NB();t0();Hc4=jP.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:N.toJSONSchema(Y.inputSchema),outputSchema:N.toJSONSchema(Y.outputSchema)}))});function qc4(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 eK(Y){return typeof Y==="string"||typeof Y==="number"}function Of(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>Of(Y,F));case"or":return H.some((F)=>Of(Y,F));case"not":return!H.every((F)=>Of(Y,F));default:return!0}}let{field:Q,operator:J,value:G}=X,K=Q.join("."),W=HY0(Y,K);switch(J){case"eq":return W===G;case"gt":return eK(W)&&eK(G)&&W>G;case"gte":return eK(W)&&eK(G)&&W>=G;case"lt":return eK(W)&&eK(G)&&W<G;case"lte":return eK(W)&&eK(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=qc4(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 HY0(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 Vc4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=HY0(Q,K),Z=HY0(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 Fc4,$c4,zc4,FY0;var lH6=m(()=>{WY0();fH6();hJ();gH6();Bf();NB();t0();J4();KY0();oK();Fc4={LLM:ZY0,ASSISTANTS:yH6,OBJECT_STORAGE:jP};$c4=fW.extend({binding:N.union([N.object({}).passthrough(),N.string()]).optional()}),zc4=hW(fJ),FY0=X6({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",inputSchema:$c4,outputSchema:zc4,handler:async(Y,X)=>{await X.access.check();let Q=S6(X),J=Y.binding?typeof Y.binding==="string"?(()=>{let B=Fc4[Y.binding.toUpperCase()];if(!B)throw Error(`Unknown binding: ${Y.binding}`);return B})():Y.binding:void 0,G=J?zf(J):void 0,K=await X.storage.connections.list(Q.id);if(Uf()){let B=o7(),U=k5.DEV_ASSETS(Q.id);if(!K.some((D)=>D.id===U)){let D=Df(Q.id,B);K.unshift(D)}}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((D)=>({name:D.name,inputSchema:D.inputSchema,outputSchema:D.outputSchema})))?B:null})).then((B)=>B.filter((U)=>U!==null)):W;if(Y.where)Z=Z.filter((B)=>Of(B,Y.where));if(Y.orderBy&&Y.orderBy.length>0)Z=Vc4(Z,Y.orderBy);let H=Z.length,F=Y.offset??0,q=Y.limit??100,V=Z.slice(F,F+q),$=F+q<H;return{items:V,totalCount:H,hasMore:$}}})});var Bc4,qY0;var dH6=m(()=>{hJ();J4();KY0();oK();Bc4=UP(fJ),qY0=X6({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",inputSchema:BP,outputSchema:Bc4,handler:async(Y,X)=>{let Q=S6(X);if(await X.access.check(),Uf()&&mH6(Y.id,Q.id))return{item:Df(Q.id,o7())};let J=await X.storage.connections.findById(Y.id);if(!J||J.organization_id!==Q.id)return{item:null};return{item:J}}})});var Nf=(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 pH6(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 Uc4(Y){let X=Y.split("::");if(X.length!==2||!X[0]||!X[1])return null;return X}function Dc4(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let X=Y.value;if(typeof X==="string")return X}return null}function Oc4(Y,X){let Q={};if(!Y||!X)return Q;for(let J of X){if(J==="*"){Q["*"]=["*"];continue}let G=Uc4(J);if(!G)continue;let[K,W]=G,Z=Nf(K,Y),H=Dc4(Z);if(H){if(!Q[H])Q[H]=[];Q[H].push(W)}}return Q}function cH6(Y,X){let Q=Oc4(Y,X);return new Set(Object.keys(Q).filter((J)=>J!=="*"))}var nH6=()=>{};class VY0{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=MB("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 iH6=m(()=>{ey()});async function Mc4(Y,X,Q,J){for(let K of X){if(K==="*")continue;let[W]=pH6(K),Z=Nf(W,Y);if(Z===void 0||Z===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let G=cH6(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 Nc4,Lc4,$Y0;var aH6=m(()=>{nH6();iH6();t0();J4();Gf();oK();Nc4=N.object({id:N.string().describe("ID of the connection to update"),data:aZ6.describe("Partial connection data to update")}),Lc4=N.object({item:fJ.describe("The updated connection entity")});$Y0=X6({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update an existing MCP connection in the organization",inputSchema:Nc4,outputSchema:Lc4,handler:async(Y,X)=>{$6(X);let Q=S6(X);if(await X.access.check(),!_8(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 T=sy(H);if(!T)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let I=await X.storage.virtualMcps.findById(T);if(!I)throw Error(`Virtual MCP not found: ${T}`);if(I.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=ty(T)}let F=K.configuration_state??W.configuration_state,q=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)q=K.configuration_scopes??[];if(q.length>0&&F)await Mc4(F,q,Q.id,X)}let V=K.connection_token??W.connection_token;if(!V)try{let I=await new VY0(X.db,X.vault).get(G);if(I?.accessToken)V=I.accessToken}catch{}let $=await SB({id:W.id,title:K.title??W.title,connection_type:Z,connection_url:H,connection_token:V,connection_headers:K.connection_headers??W.connection_headers}).catch(()=>null),B=$?.length?$:null,U={...K,connection_url:H,tools:B,configuration_state:F,configuration_scopes:q},D=await X.storage.connections.update(G,U);if((K.configuration_state!==void 0||K.configuration_scopes!==void 0)&&F&&q.length>0)try{let L=[];try{const T=gB(L,await X.createMCPProxy(G),1);await T.callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:F,scopes:q}});await T.close().catch(console.error)}catch(M){var C=M,R=1}finally{var E=yP(L,C,R);E&&await E}}catch(T){console.error("Failed to invoke ON_MCP_CONFIGURATION callback",T)}return{item:D}}})});var zY0;var rH6=m(()=>{hJ();J4();oK();zY0=X6({name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete a connection",inputSchema:DP,outputSchema:OP(fJ),handler:async(Y,X)=>{$6(X);let Q=S6(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 BY0;var oH6=m(()=>{t0();J4();BY0=X6({name:"CONNECTION_TEST",description:"Test connection health and latency",inputSchema:N.object({id:N.string()}),outputSchema:N.object({id:N.string(),healthy:N.boolean(),latencyMs:N.number()}),handler:async(Y,X)=>{let Q=S6(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 sH6=m(()=>{FH6();lH6();dH6();aH6();rH6();oH6()});import{sql as s4}from"kysely";function tH6(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 Tc4(Y,X){let Q=Y;for(let G=X.length;G>=1;G--){let K=`$${G}`;if(Q.includes(K))Q=Q.replaceAll(K,tH6(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=tH6(X[G]);Q=Q.slice(0,K)+W+Q.slice(K+1)}return Q}function eH6(Y){return Y.replace(/-/g,"_")}function Ec4(Y){return`app_${eH6(Y)}`}function Cc4(Y){return`app_role_${eH6(Y)}`}function Ic4(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 Rc4(Y,X,Q){if(await s4`CREATE SCHEMA IF NOT EXISTS ${s4.id(X)}`.execute(Y),!(await s4`
|
|
408
408
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
409
409
|
`.execute(Y)).rows[0]?.exists)await s4`CREATE ROLE ${s4.id(Q)} NOLOGIN`.execute(Y);await s4`GRANT ${s4.id(Q)} TO CURRENT_USER`.execute(Y),await s4`GRANT USAGE, CREATE ON SCHEMA ${s4.id(X)} TO ${s4.id(Q)}`.execute(Y),await s4`GRANT ALL ON ALL TABLES IN SCHEMA ${s4.id(X)} TO ${s4.id(Q)}`.execute(Y),await s4`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${s4.id(X)} TO ${s4.id(Q)}`.execute(Y),await s4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s4.id(X)} GRANT ALL ON TABLES TO ${s4.id(Q)}`.execute(Y),await s4`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s4.id(X)} GRANT ALL ON SEQUENCES TO ${s4.id(Q)}`.execute(Y),await s4`REVOKE ALL ON SCHEMA public FROM ${s4.id(Q)}`.execute(Y)}async function Sc4(Y,X,Q,J){try{return await Y.transaction().execute(async(G)=>{return await s4`SET LOCAL ROLE ${s4.id(Q)}`.execute(G),await s4`SET LOCAL search_path TO ${s4.id(X)}`.execute(G),await s4.raw(J).execute(G)})}catch(G){if(Ic4(G))return await Rc4(Y,X,Q),await Y.transaction().execute(async(K)=>{return await s4`SET LOCAL ROLE ${s4.id(Q)}`.execute(K),await s4`SET LOCAL search_path TO ${s4.id(X)}`.execute(K),await s4.raw(J).execute(K)});throw G}}var Pc4,Ac4,YF6;var XF6=m(()=>{t0();J4();Pc4=N.object({results:N.array(N.unknown()).optional(),success:N.boolean().optional()});Ac4=N.object({sql:N.string().describe("The SQL query to run"),params:N.array(N.any()).describe("The parameters to pass to the SQL query").optional()});YF6=X6({name:"DATABASES_RUN_SQL",description:"Run a SQL query against the database",inputSchema:Ac4,outputSchema:N.object({result:N.array(Pc4)}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=Tc4(Y.sql,Y.params||[]);if(!X.connectionId)throw Error("Connection context required for database access");let J=Ec4(X.connectionId),G=Cc4(X.connectionId);return{result:[{results:(await Sc4(X.db,J,G,Q)).rows,success:!0}]}}})});var QF6,kc4,JF6;var xW=m(()=>{t0();WY0();QF6=N.object({connectionId:N.string().optional().describe("Filter subscriptions by connection ID (optional)")}),kc4=N.object({id:N.string().describe("Subscription ID"),connectionId:N.string().describe("Subscriber connection ID"),eventType:N.string().describe("Event type pattern"),publisher:N.string().nullable().describe("Publisher connection filter (null = all publishers)"),filter:N.string().nullable().describe("JSONPath filter expression"),enabled:N.boolean().describe("Whether subscription is enabled"),createdAt:N.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:N.string().datetime().describe("Updated timestamp (ISO 8601)")}),JF6=N.object({subscriptions:N.array(kc4).describe("List of subscriptions")})});var UY0;var GF6=m(()=>{J4();xW();UY0=X6({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:NP,outputSchema:LP,handler:async(Y,X)=>{$6(X);let Q=S6(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 DY0;var WF6=m(()=>{J4();xW();DY0=X6({name:"EVENT_SUBSCRIBE",description:"Subscribe to events of a specific type. The subscriber is automatically set to the caller's connection.",inputSchema:MP,outputSchema:wP,handler:async(Y,X)=>{$6(X);let Q=S6(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 OY0;var ZF6=m(()=>{J4();xW();OY0=X6({name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events by removing a subscription.",inputSchema:AP,outputSchema:EP,handler:async(Y,X)=>{$6(X);let Q=S6(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 NY0;var KF6=m(()=>{J4();xW();NY0=X6({name:"EVENT_CANCEL",description:"Cancel a recurring event to stop future deliveries. Only the publisher can cancel their own events.",inputSchema:CP,outputSchema:IP,handler:async(Y,X)=>{$6(X);let Q=S6(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 LY0;var HF6=m(()=>{J4();xW();LY0=X6({name:"EVENT_ACK",description:"Acknowledge delivery of an event. Call after successfully processing an event received via ON_EVENTS with retryAfter.",inputSchema:RP,outputSchema:SP,handler:async(Y,X)=>{$6(X);let Q=S6(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 MY0;var FF6=m(()=>{J4();xW();MY0=X6({name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions, optionally filtered by connection ID.",inputSchema:QF6,outputSchema:JF6,handler:async(Y,X)=>{$6(X);let Q=S6(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 wY0;var qF6=m(()=>{J4();xW();wY0=X6({name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state. Creates new, deletes removed, updates changed filters. Subscriptions are identified by (eventType, publisher).",inputSchema:PP,outputSchema:TP,handler:async(Y,X)=>{$6(X);let Q=S6(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 VF6=m(()=>{GF6();WF6();ZF6();KF6();HF6();FF6();qF6();xW()});var _c4,Z7,$F6,zF6;var bB=m(()=>{t0();_c4=N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:N.array(N.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:N.array(N.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),Z7=N.object({id:N.string().nullable().describe("Unique identifier for the virtual MCP (null for synthetic Decopilot agent)"),title:N.string().describe("Human-readable name for the virtual MCP"),description:N.string().nullable().describe("Description of the virtual MCP"),icon:N.string().nullable().optional().describe("Icon URL for the virtual MCP"),created_at:N.string().describe("When the virtual MCP was created"),updated_at:N.string().describe("When the virtual MCP was last updated"),created_by:N.string().describe("User ID who created the virtual MCP"),updated_by:N.string().optional().describe("User ID who last updated the virtual MCP"),organization_id:N.string().describe("Organization ID this virtual MCP belongs to"),status:N.enum(["active","inactive"]).describe("Current status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(_c4).describe("Connections with their selected tools, resources, and prompts")}),$F6=N.object({title:N.string().min(1).max(255).describe("Name for the virtual MCP"),description:N.string().nullable().optional().describe("Optional description"),icon:N.string().nullable().optional().describe("Optional icon URL"),status:N.enum(["active","inactive"]).optional().default("active").describe("Initial status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools included)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources included)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts included)")})).describe("Connections to include with their selected tools/resources/prompts")}),zF6=N.object({title:N.string().min(1).max(255).optional().describe("New name"),description:N.string().nullable().optional().describe("New description (null to clear)"),icon:N.string().nullable().optional().describe("New icon URL (null to clear)"),status:N.enum(["active","inactive"]).optional().describe("New status"),metadata:N.object({instructions:N.string().optional().describe("MCP server instructions")}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:N.array(N.object({connection_id:N.string().describe("Connection ID"),selected_tools:N.array(N.string()).nullable().optional().describe("Selected tool names (null/undefined = all tools included)"),selected_resources:N.array(N.string()).nullable().optional().describe("Selected resource URIs or patterns with * and ** wildcards (null/undefined = all resources included)"),selected_prompts:N.array(N.string()).nullable().optional().describe("Selected prompt names (null/undefined = all prompts included)")})).optional().describe("New connections (replaces existing)")})});var yc4,fc4,PY0;var BF6=m(()=>{t0();J4();bB();yc4=N.object({data:$F6.describe("Data for the new virtual MCP")}),fc4=N.object({item:Z7.describe("The created virtual MCP entity")}),PY0=X6({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a new MCP virtual MCP in the organization",inputSchema:yc4,outputSchema:fc4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=_8(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 hc4(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 Y3(Y){return typeof Y==="string"||typeof Y==="number"}function TY0(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 bc4(Y,X){return Y.connections.some((Q)=>Q.connection_id===X)}function Lf(Y,X){if("conditions"in X){let{operator:Z,conditions:H}=X;switch(Z){case"and":return H.every((F)=>Lf(Y,F));case"or":return H.some((F)=>Lf(Y,F));case"not":return!H.every((F)=>Lf(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 bc4(Y,G)}let W=TY0(Y,K);switch(J){case"eq":return W===G;case"gt":return Y3(W)&&Y3(G)&&W>G;case"gte":return Y3(W)&&Y3(G)&&W>=G;case"lt":return Y3(W)&&Y3(G)&&W<G;case"lte":return Y3(W)&&Y3(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=hc4(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 xc4(Y,X){return[...Y].sort((Q,J)=>{for(let G of X){let K=G.field.join("."),W=TY0(Q,K),Z=TY0(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 uc4,gc4,AY0;var UF6=m(()=>{hJ();J4();bB();uc4=fW,gc4=hW(Z7),AY0=X6({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",inputSchema:uc4,outputSchema:gc4,handler:async(Y,X)=>{await X.access.check();let Q=S6(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((V)=>Lf(V,Y.where));if(Y.orderBy&&Y.orderBy.length>0)K=xc4(K,Y.orderBy);let W=K.length,Z=Y.offset??0,H=Y.limit??100,F=K.slice(Z,Z+H),q=Z+H<W;return{items:F,totalCount:W,hasMore:q}}})});var mc4,lc4,EY0;var DF6=m(()=>{t0();J4();bB();mc4=N.object({id:N.string().describe("ID of the virtual MCP to retrieve")}),lc4=N.object({item:Z7.nullable().describe("The retrieved virtual MCP, or null if not found")}),EY0=X6({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get an MCP virtual MCP by ID",inputSchema:mc4,outputSchema:lc4,handler:async(Y,X)=>{$6(X);let Q=S6(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 dc4,pc4,CY0;var OF6=m(()=>{t0();J4();bB();dc4=N.object({id:N.string().describe("ID of the virtual MCP to update"),data:zF6.describe("Partial virtual MCP data to update")}),pc4=N.object({item:Z7.describe("The updated virtual MCP entity")}),CY0=X6({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update an MCP virtual MCP",inputSchema:dc4,outputSchema:pc4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=_8(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 cc4,nc4,IY0;var NF6=m(()=>{t0();J4();bB();cc4=N.object({id:N.string().describe("ID of the virtual MCP to delete")}),nc4=N.object({item:Z7.describe("The deleted virtual MCP entity")}),IY0=X6({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete an MCP virtual MCP",inputSchema:cc4,outputSchema:nc4,handler:async(Y,X)=>{$6(X);let Q=S6(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 LF6=m(()=>{BF6();UF6();DF6();OF6();NF6()});var ac4,RY0;var MF6=m(()=>{J4();t0();ac4=N.object({id:N.string().optional().describe("Unique log identifier"),organizationId:N.string().describe("Organization ID"),connectionId:N.string().describe("Connection ID"),connectionTitle:N.string().describe("Connection display name"),toolName:N.string().describe("Name of the tool that was called"),input:N.record(N.string(),N.unknown()).describe("Redacted tool input"),output:N.record(N.string(),N.unknown()).describe("Redacted tool output"),isError:N.boolean().describe("Whether the call resulted in an error"),errorMessage:N.string().nullish().describe("Error message if applicable"),durationMs:N.number().describe("Call duration in milliseconds"),timestamp:N.string().describe("ISO 8601 timestamp of the call"),userId:N.string().nullish().describe("User who triggered the call"),requestId:N.string().describe("Unique request identifier"),userAgent:N.string().nullish().describe("Client identifier (x-mesh-client header)"),virtualMcpId:N.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:N.record(N.string(),N.string()).nullish().describe("Custom key-value metadata attached to the log")}),RY0=X6({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls in the organization",inputSchema:N.object({connectionId:N.string().optional().describe("Filter by connection ID"),virtualMcpId:N.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:N.string().optional().describe("Filter by tool name"),isError:N.boolean().optional().describe("Filter by error status"),startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:N.number().default(20).describe("Maximum number of results"),offset:N.number().default(0).describe("Offset for pagination"),properties:N.record(N.string(),N.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:N.array(N.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:N.record(N.string(),N.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)")}),outputSchema:N.object({logs:N.array(ac4).describe("Array of monitoring logs"),total:N.number().describe("Total number of logs matching filters"),offset:N.number().describe("Current offset for pagination"),limit:N.number().describe("Current limit for pagination")}),handler:async(Y,X)=>{let Q=S6(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 SY0;var wF6=m(()=>{J4();t0();SY0=X6({name:"MONITORING_STATS",description:"Get aggregated statistics for tool call monitoring",inputSchema:N.object({startDate:N.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:N.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:N.object({totalCalls:N.number().describe("Total number of tool calls"),errorRate:N.number().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:N.number().describe("Average call duration in milliseconds"),errorRatePercent:N.string().describe("Error rate as a percentage string")}),handler:async(Y,X)=>{let J={organizationId:S6(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 PF6=m(()=>{MF6();wF6()});var jY0;var TF6=m(()=>{t0();J4();jY0=X6({name:"ORGANIZATION_CREATE",description:"Create a new organization",inputSchema:N.object({slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens"),name:N.string().min(1).max(255),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional()}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=_8(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 kY0;var AF6=m(()=>{t0();J4();kY0=X6({name:"ORGANIZATION_LIST",description:"List all organizations user has access to",inputSchema:N.object({userId:N.string().optional()}),outputSchema:N.object({organizations:N.array(N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async(Y,X)=>{$6(X),await X.access.check();let Q=_8(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 vY0;var EF6=m(()=>{t0();J4();vY0=X6({name:"ORGANIZATION_GET",description:"Get organization details by slug or ID",inputSchema:N.object({}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),members:N.array(N.any()).optional(),invitations:N.array(N.any()).optional()}),handler:async(Y,X)=>{$6(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 _Y0;var CF6=m(()=>{t0();J4();_Y0=X6({name:"ORGANIZATION_UPDATE",description:"Update an existing organization",inputSchema:N.object({id:N.string(),slug:N.string().min(1).max(50).regex(/^[a-z0-9-]+$/).optional(),name:N.string().min(1).max(255).optional(),description:N.string().optional()}),outputSchema:N.object({id:N.string(),name:N.string(),slug:N.string(),logo:N.string().nullable().optional(),metadata:N.any().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{$6(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 yY0;var IF6=m(()=>{t0();J4();yY0=X6({name:"ORGANIZATION_DELETE",description:"Delete an organization",inputSchema:N.object({id:N.string()}),outputSchema:N.object({success:N.boolean(),id:N.string()}),handler:async(Y,X)=>{return $6(X),await X.access.check(),await X.boundAuth.organization.delete(Y.id),{success:!0,id:Y.id}}})});var vP;var fY0=m(()=>{t0();vP=N.object({title:N.string(),url:N.string(),icon:N.string()})});var hY0;var RF6=m(()=>{t0();J4();fY0();hY0=X6({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings",inputSchema:N.object({}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(vP).nullable().optional(),enabled_plugins:N.array(N.string()).nullable().optional(),createdAt:N.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{$6(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 bY0;var SF6=m(()=>{t0();J4();fY0();bY0=X6({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings",inputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(vP).optional(),enabled_plugins:N.array(N.string()).optional()}),outputSchema:N.object({organizationId:N.string(),sidebar_items:N.array(vP).nullable().optional(),enabled_plugins:N.array(N.string()).nullable().optional(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),updatedAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{if($6(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 xY0;var jF6=m(()=>{t0();J4();xY0=X6({name:"ORGANIZATION_MEMBER_ADD",description:"Add a member to an organization",inputSchema:N.object({organizationId:N.string().optional(),userId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.string(),N.array(N.string())]),createdAt:N.string().datetime().describe("ISO 8601 timestamp")}),handler:async(Y,X)=>{$6(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 uY0;var kF6=m(()=>{t0();J4();uY0=X6({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from an organization",inputSchema:N.object({organizationId:N.string().optional(),memberIdOrEmail:N.string()}),outputSchema:N.object({success:N.boolean(),memberIdOrEmail:N.string()}),handler:async(Y,X)=>{$6(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 gY0;var vF6=m(()=>{t0();J4();gY0=X6({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in an organization",inputSchema:N.object({limit:N.number().optional(),offset:N.number().optional()}),outputSchema:N.object({members:N.array(N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.string(),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().optional()}).optional()}))}),handler:async(Y,X)=>{$6(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 mY0;var _F6=m(()=>{t0();J4();mY0=X6({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update a member's role in an organization",inputSchema:N.object({organizationId:N.string().optional(),memberId:N.string(),role:N.array(N.string())}),outputSchema:N.object({id:N.string(),organizationId:N.string(),userId:N.string(),role:N.union([N.literal("admin"),N.literal("member"),N.literal("owner")]),createdAt:N.string().datetime().describe("ISO 8601 timestamp"),user:N.object({email:N.string(),name:N.string(),image:N.string().optional()})}),handler:async(Y,X)=>{$6(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 yF6=m(()=>{TF6();AF6();EF6();CF6();IF6();RF6();SF6();jF6();kF6();vF6();_F6()});var fF6,K7,hF6,bF6;var Qq=m(()=>{t0();fF6=N.object({id:N.string().describe("Unique message ID"),threadId:N.string().describe("ID of the parent thread"),metadata:N.unknown().optional().describe("Optional message metadata"),parts:N.array(N.record(N.string(),N.unknown())).describe("Message content parts (AI SDK UIMessagePart format)"),role:N.enum(["user","assistant","system"]).describe("Message role"),createdAt:N.string().datetime().describe("Timestamp of creation"),updatedAt:N.string().datetime().describe("Timestamp of last update")}),K7=N.object({id:N.string().describe("Unique thread ID"),organizationId:N.string().describe("Organization this thread belongs to"),title:N.string().describe("Thread title"),description:N.string().nullable().describe("Thread description"),createdAt:N.string().datetime().describe("Timestamp of creation"),updatedAt:N.string().datetime().describe("Timestamp of last update"),hidden:N.boolean().optional().describe("Whether the thread is hidden"),createdBy:N.string().describe("User ID who created the thread"),updatedBy:N.string().nullable().describe("User ID who last updated the thread")}),hF6=N.object({id:N.string().optional().describe("Optional custom ID for the thread"),title:N.string().describe("Thread title"),description:N.string().nullish().describe("Thread description")}),bF6=N.object({title:N.string().optional().describe("New thread title"),description:N.string().nullish().describe("New thread description"),hidden:N.boolean().optional().describe("Whether the thread is hidden")})});var sc4,tc4,lY0;var xF6=m(()=>{t0();J4();Qq();ey();sc4=N.object({data:hF6.describe("Data for the new thread (id is auto-generated if not provided)")}),tc4=N.object({item:K7.describe("The created thread entity")}),lY0=X6({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread in the organization",inputSchema:sc4,outputSchema:tc4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=_8(X);if(!J)throw Error("User ID required to create thread");let G=Y.data.id??MB("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 ec4,Yn4,dY0;var uF6=m(()=>{hJ();J4();Qq();t0();ec4=fW.extend({where:N.object({created_by:N.string().optional()}).optional()}),Yn4=hW(K7),dY0=X6({name:"COLLECTION_THREADS_LIST",description:"List all threads in the organization with filtering, sorting, and pagination",inputSchema:ec4,outputSchema:Yn4,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=S6(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 Xn4,pY0;var gF6=m(()=>{hJ();J4();Qq();Xn4=UP(K7),pY0=X6({name:"COLLECTION_THREADS_GET",description:"Get thread details by ID",inputSchema:BP,outputSchema:Xn4,handler:async(Y,X)=>{$6(X);let Q=S6(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 Qn4,Jn4,cY0;var mF6=m(()=>{t0();J4();Qq();Qn4=N.object({id:N.string().describe("ID of the thread to update"),data:bF6.describe("Partial thread data to update")}),Jn4=N.object({item:K7.describe("The updated thread entity")}),cY0=X6({name:"COLLECTION_THREADS_UPDATE",description:"Update an existing thread in the organization",inputSchema:Qn4,outputSchema:Jn4,handler:async(Y,X)=>{$6(X);let Q=S6(X);await X.access.check();let J=_8(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 nY0;var lF6=m(()=>{hJ();J4();Qq();nY0=X6({name:"COLLECTION_THREADS_DELETE",description:"Delete a thread",inputSchema:DP,outputSchema:OP(K7),handler:async(Y,X)=>{$6(X);let Q=S6(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 dF6(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=dF6(X);if(Q)return Q}return null}var Gn4,iY0;var pF6=m(()=>{hJ();J4();Qq();Gn4=hW(fF6),iY0=X6({name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List all messages for a specific thread",inputSchema:fW,outputSchema:Gn4,handler:async(Y,X)=>{let Q=S6(X);await X.access.check();let J=dF6(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 cF6=m(()=>{xF6();uF6();gF6();mF6();lF6();pF6()});var Zn4,Kn4,aY0;var nF6=m(()=>{t0();J4();Zn4=N.object({id:N.string().min(1)}),Kn4=N.object({user:N.object({id:N.string(),name:N.string(),email:N.string(),image:N.string().nullable()}).nullable()}),aY0=X6({name:"USER_GET",description:"Get a user by id (restricted to shared organizations)",inputSchema:Zn4,outputSchema:Kn4,handler:async(Y,X)=>{await X.access.check(),$6(X);let Q=_8(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 iF6=m(()=>{nF6()});var rF6={};l6(rF6,{managementMCP:()=>Vn4,ALL_TOOLS:()=>aF6});var Fn4,qn4,aF6,Vn4=async(Y)=>{let X=null;if(Y.organization)X=(await Y.storage.organizationSettings.get(Y.organization.id))?.enabled_plugins??null;let J=lJ0(aF6,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 eK6({name:"mcp-mesh-management",version:"1.0.0"}).withTools(J).build()};var oF6=m(()=>{Y36();cu();B36();HH6();sH6();XF6();VF6();LF6();PF6();yF6();cF6();iF6();Fn4=[jY0,kY0,vY0,_Y0,yY0,hY0,bY0,xY0,uY0,gY0,mY0,XY0,FY0,qY0,$Y0,zY0,BY0,PY0,AY0,EY0,CY0,IY0,YF6,RY0,SY0,S90,k90,v90,j90,UY0,DY0,OY0,NY0,LY0,MY0,wY0,aY0,t90,e90,YY0,lY0,dY0,pY0,cY0,nY0,iY0],qn4=dJ0(),aF6=[...Fn4,...qn4]});Pg();import{Migrator as Wq6}from"kysely";var $50={benchmark:()=>Promise.resolve().then(() => (V50(),q50)).then((Y)=>Y.seed)};async function z50(Y,X){let Q=$50[X];if(!Q)throw Error(`Unknown seed: ${X}. Available: ${Object.keys($50).join(", ")}`);let J=await Q();console.log(`\uD83C\uDF31 Running seed: ${X}`);let G=await J(Y);return console.log(`\u2705 Seed "${X}" completed`),G}z7();fQ();z7();fQ();PY();N9();var P8=(Y,X="ms")=>{return new Date(Date.now()+(X==="sec"?Y*1000:Y))},lC=new WeakMap;function n70(Y,X){let Q=X.fields,J={};for(let G in Y){let K=Q[G];if(!K){J[G]=Y[G];continue}if(K.returned===!1)continue;J[G]=Y[G]}return J}function dC(Y,X){if(!lC.has(Y))lC.set(Y,new Map);let Q=lC.get(Y);if(Q.has(X))return Q.get(X);let J={...X==="user"?Y.user?.additionalFields:{},...X==="session"?Y.session?.additionalFields:{}};for(let G of Y.plugins||[])if(G.schema&&G.schema[X])J={...J,...G.schema[X].fields};return lC.get(Y).set(X,J),J}function L9(Y,X){return{...n70(X,{fields:dC(Y,"user")}),id:X.id}}function o5(Y,X){return n70(X,{fields:dC(Y,"session")})}function gm(Y,X){let Q=X.action||"create",J=X.fields,G=Object.assign(Object.create(null),null);for(let K in J){if(K in Y){if(J[K].input===!1){if(J[K].defaultValue!==void 0){if(Q!=="update"){G[K]=J[K].defaultValue;continue}}if(Y[K])throw new i("BAD_REQUEST",{message:`${K} is not allowed to be set`});continue}if(J[K].validator?.input&&Y[K]!==void 0){G[K]=J[K].validator.input["~standard"].validate(Y[K]);continue}if(J[K].transform?.input&&Y[K]!==void 0){G[K]=J[K].transform?.input(Y[K]);continue}G[K]=Y[K];continue}if(J[K].defaultValue!==void 0&&Q==="create"){if(typeof J[K].defaultValue==="function"){G[K]=J[K].defaultValue();continue}G[K]=J[K].defaultValue;continue}if(J[K].required&&Q==="create")throw new i("BAD_REQUEST",{message:`${K} is required`})}return G}function pC(Y,X={},Q){return gm(X,{fields:dC(Y,"user"),action:Q})}function mm(Y,X){return gm(X,{fields:dC(Y,"session")})}function lY(Y,X){if(!X)return Y;for(let Q in X){let J=X[Q]?.modelName;if(J)Y[Q].modelName=J;for(let G in Y[Q].fields){let K=X[Q]?.fields?.[G];if(!K)continue;Y[Q].fields[G].fieldName=K}}return Y}TX();t0();var AD6="127.0.0.1";function OZ(Y,X){if(X.advanced?.ipAddress?.disableIpTracking)return null;if(T7()||eq())return AD6;let Q="headers"in Y?Y.headers:Y,J=X.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"];for(let G of J){let K="get"in Q?Q.get(G):Q[G];if(typeof K==="string"){let W=K.split(",")[0].trim();if(ED6(W))return W}}return null}function ED6(Y){if(P3().safeParse(Y).success)return!0;if(T3().safeParse(Y).success)return!0;return!1}TY();a5();TX();y8();import{sql as t5}from"kysely";async function s70(Y,X){let Q;if(!Y.database){let J=QQ(Y),G=Object.keys(J).reduce((W,Z)=>{return W[Z]=[],W},{}),{memoryAdapter:K}=await Promise.resolve().then(() => (o70(),r70));Q=K(G)(Y)}else if(typeof Y.database==="function")Q=Y.database(Y);else Q=await X(Y);if(!Q.transaction)f6.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),Q.transaction=async(J)=>{return J(Q)};return Q}async function im(Y){return s70(Y,async(X)=>{let{createKyselyAdapter:Q}=await Promise.resolve().then(() => (nm(),cm)),{kysely:J,databaseType:G,transaction:K}=await Q(X);if(!J)throw new C6("Failed to initialize database adapter");let{kyselyAdapter:W}=await Promise.resolve().then(() => (nm(),cm));return W(J,{type:G||"sqlite",debugLogs:X.database&&"debugLogs"in X.database?X.database.debugLogs:!1,transaction:K})(X)})}function t70(Y,X){let Q=X.hooks;async function J(H,F,q){let V=await JQ(),$=H;for(let D of Q||[]){let L=D[F]?.create?.before;if(L){let M=await L($,V);if(M===!1)return null;if(typeof M==="object"&&"data"in M)$={...$,...M.data}}}let B=q?await q.fn($):null,U=!q||q.executeMainFn?await(await U1(Y)).create({model:F,data:$,forceAllowId:!0}):B;for(let D of Q||[]){let L=D[F]?.create?.after;if(L)await L(U,V)}return U}async function G(H,F,q,V){let $=await JQ(),B=H;for(let L of Q||[]){let M=L[q]?.update?.before;if(M){let C=await M(H,$);if(C===!1)return null;if(typeof C==="object"&&"data"in C)B={...B,...C.data}}}let U=V?await V.fn(B):null,D=!V||V.executeMainFn?await(await U1(Y)).update({model:q,update:B,where:F}):U;for(let L of Q||[]){let M=L[q]?.update?.after;if(M)await M(D,$)}return D}async function K(H,F,q,V){let $=await JQ(),B=H;for(let L of Q||[]){let M=L[q]?.update?.before;if(M){let C=await M(H,$);if(C===!1)return null;if(typeof C==="object"&&"data"in C)B={...B,...C.data}}}let U=V?await V.fn(B):null,D=!V||V.executeMainFn?await(await U1(Y)).updateMany({model:q,update:B,where:F}):U;for(let L of Q||[]){let M=L[q]?.update?.after;if(M)await M(D,$)}return D}async function W(H,F,q){let V=await JQ(),$=null;try{$=(await(await U1(Y)).findMany({model:F,where:H,limit:1}))[0]||null}catch(D){}if($)for(let D of Q||[]){let L=D[F]?.delete?.before;if(L){if(await L($,V)===!1)return null}}let B=q?await q.fn(H):null,U=!q||q.executeMainFn?await(await U1(Y)).delete({model:F,where:H}):B;if($)for(let D of Q||[]){let L=D[F]?.delete?.after;if(L)await L($,V)}return U}async function Z(H,F,q){let V=await JQ(),$=[];try{$=await(await U1(Y)).findMany({model:F,where:H})}catch(D){}for(let D of $)for(let L of Q||[]){let M=L[F]?.delete?.before;if(M){if(await M(D,V)===!1)return null}}let B=q?await q.fn(H):null,U=!q||q.executeMainFn?await(await U1(Y)).deleteMany({model:F,where:H}):B;for(let D of $)for(let L of Q||[]){let M=L[F]?.delete?.after;if(M)await M(D,V)}return U}return{createWithHooks:J,updateWithHooks:G,updateManyWithHooks:K,deleteWithHooks:W,deleteManyWithHooks:Z}}var sC=(Y,X)=>{let{logger:Q,options:J}=X,G=J.secondaryStorage,K=J.session?.expiresIn||604800,{createWithHooks:W,updateWithHooks:Z,updateManyWithHooks:H,deleteWithHooks:F,deleteManyWithHooks:q}=t70(Y,X);async function V($){if(!G)return;let B=await G.get(`active-sessions-${$.id}`);if(!B)return;let U=Date.now(),D=(T1(B)||[]).filter((L)=>L.expiresAt>U);await Promise.all(D.map(async({token:L})=>{let M=await G.get(L);if(!M)return;let C=T1(M);if(!C)return;let R=Math.max(Math.floor(new Date(C.session.expiresAt).getTime()-U)/1000,0);await G.set(L,JSON.stringify({session:C.session,user:$}),Math.floor(R))}))}return{createOAuthUser:async($,B)=>{return dD(Y,async()=>{let U=await W({createdAt:new Date,updatedAt:new Date,...$},"user",void 0);return{user:U,account:await W({...B,userId:U.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}})},createUser:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$,email:$.email?.toLowerCase()},"user",void 0)},createAccount:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"account",void 0)},listSessions:async($)=>{if(G){let B=await G.get(`active-sessions-${$}`);if(!B)return[];let U=T1(B)||[],D=Date.now(),L=U.filter((C)=>C.expiresAt>D),M=[];for(let C of L){let R=await G.get(C.token);if(R){let E=T1(R);if(!E)return[];let T=o5(X.options,{...E.session,expiresAt:new Date(E.session.expiresAt)});M.push(T)}}return M}return await(await U1(Y)).findMany({model:"session",where:[{field:"userId",value:$}]})},listUsers:async($,B,U,D)=>{return await(await U1(Y)).findMany({model:"user",limit:$,offset:B,sortBy:U,where:D})},countTotalUsers:async($)=>{let B=await(await U1(Y)).count({model:"user",where:$});if(typeof B==="string")return parseInt(B);return B},deleteUser:async($)=>{if(G)await G.delete(`active-sessions-${$}`);if(!G||J.session?.storeSessionInDatabase)await q([{field:"userId",value:$}],"session",void 0);await q([{field:"userId",value:$}],"account",void 0),await F([{field:"id",value:$}],"user",void 0)},createSession:async($,B,U,D)=>{let L=await JQ().catch(()=>null),M=L?.headers||L?.request?.headers,{id:C,...R}=U||{},E=mm(L?.context.options??J,{}),T={ipAddress:L?.request||L?.headers?OZ(L?.request||L?.headers,L?.context.options)||"":"",userAgent:M?.get("user-agent")||"",...R,expiresAt:B?P8(86400,"sec"):P8(K,"sec"),userId:$,token:a8(32),createdAt:new Date,updatedAt:new Date,...E,...D?R:{}};return await W(T,"session",G?{fn:async(I)=>{let S=await G.get(`active-sessions-${$}`),k=[],_=Date.now();if(S)k=T1(S)||[],k=k.filter((d)=>d.expiresAt>_);let y=k.sort((d,Y0)=>d.expiresAt-Y0.expiresAt),f=y.at(-1)?.expiresAt;if(y.push({token:T.token,expiresAt:T.expiresAt.getTime()}),!f||f<T.expiresAt.getTime())f=T.expiresAt.getTime();let o=Math.max(Math.floor((f-_)/1000),0);if(o>0)await G.set(`active-sessions-${$}`,JSON.stringify(y),o);let g=await Y.findOne({model:"user",where:[{field:"id",value:$}]}),v=Math.max(Math.floor((T.expiresAt.getTime()-_)/1000),0);if(v>0)await G.set(T.token,JSON.stringify({session:I,user:g}),v);return I},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},findSession:async($)=>{if(G){let L=await G.get($);if(!L&&!J.session?.storeSessionInDatabase)return null;if(L){let M=T1(L);if(!M)return null;return{session:o5(X.options,{...M.session,expiresAt:new Date(M.session.expiresAt),createdAt:new Date(M.session.createdAt),updatedAt:new Date(M.session.updatedAt)}),user:L9(X.options,{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)})}}}let B=await(await U1(Y)).findOne({model:"session",where:[{value:$,field:"token"}],join:{user:!0}});if(!B)return null;let{user:U,...D}=B;if(!U)return null;return{session:o5(X.options,D),user:L9(X.options,U)}},findSessions:async($)=>{if(G){let U=[];for(let D of $){let L=await G.get(D);if(L){let M=T1(L);if(!M)return[];let C={session:{...M.session,expiresAt:new Date(M.session.expiresAt)},user:{...M.user,createdAt:new Date(M.user.createdAt),updatedAt:new Date(M.user.updatedAt)}};U.push(C)}}return U}let B=await(await U1(Y)).findMany({model:"session",where:[{field:"token",value:$,operator:"in"}],join:{user:!0}});if(!B.length)return[];if(B.some((U)=>!U.user))return[];return B.map((U)=>{let{user:D,...L}=U;return{session:L,user:D}})},updateSession:async($,B)=>{return await Z(B,[{field:"token",value:$}],"session",G?{async fn(U){let D=await G.get($),L=null;if(D){let M=T1(D);if(!M)return null;return L={...M.session,...U},L}else return null},executeMainFn:J.session?.storeSessionInDatabase}:void 0)},deleteSession:async($)=>{if(G){let B=await G.get($);if(B){let{session:U}=T1(B)??{};if(!U){Q.error("Session not found in secondary storage");return}let D=U.userId,L=await G.get(`active-sessions-${D}`);if(L){let M=T1(L)||[],C=Date.now(),R=M.filter((T)=>T.expiresAt>C&&T.token!==$),E=R.sort((T,I)=>T.expiresAt-I.expiresAt).at(-1)?.expiresAt;if(R.length>0&&E&&E>Date.now())await G.set(`active-sessions-${D}`,JSON.stringify(R),Math.floor((E-C)/1000));else await G.delete(`active-sessions-${D}`)}else Q.error("Active sessions list not found in secondary storage")}if(await G.delete($),!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await(await U1(Y)).delete({model:"session",where:[{field:"token",value:$}]})},deleteAccounts:async($)=>{await q([{field:"userId",value:$}],"account",void 0)},deleteAccount:async($)=>{await F([{field:"id",value:$}],"account",void 0)},deleteSessions:async($)=>{if(G){if(typeof $==="string"){let B=await G.get(`active-sessions-${$}`),U=B?T1(B):[];if(!U)return;for(let D of U)await G.delete(D.token)}else for(let B of $)if(await G.get(B))await G.delete(B);if(!J.session?.storeSessionInDatabase||X.options.session?.preserveSessionInDatabase)return}await q([{field:Array.isArray($)?"token":"userId",value:$,operator:Array.isArray($)?"in":void 0}],"session",void 0)},findOAuthUser:async($,B,U)=>{let D=await(await U1(Y)).findMany({model:"account",where:[{value:B,field:"accountId"}],join:{user:!0}}).then((L)=>{return L.find((M)=>M.providerId===U)});if(D)if(D.user)return{user:D.user,accounts:[D]};else{let L=await(await U1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:[D]};return null}else{let L=await(await U1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}]});if(L)return{user:L,accounts:await(await U1(Y)).findMany({model:"account",where:[{value:L.id,field:"userId"}]})||[]};else return null}},findUserByEmail:async($,B)=>{let U=await(await U1(Y)).findOne({model:"user",where:[{value:$.toLowerCase(),field:"email"}],join:{...B?.includeAccounts?{account:!0}:{}}});if(!U)return null;let{account:D,...L}=U;return{user:L,accounts:D??[]}},findUserById:async($)=>{if(!$)return null;return await(await U1(Y)).findOne({model:"user",where:[{field:"id",value:$}]})},linkAccount:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"account",void 0)},updateUser:async($,B)=>{let U=await Z(B,[{field:"id",value:$}],"user",void 0);return await V(U),await V(U),U},updateUserByEmail:async($,B)=>{let U=await Z(B,[{field:"email",value:$.toLowerCase()}],"user",void 0);return await V(U),await V(U),U},updatePassword:async($,B)=>{await H({password:B},[{field:"userId",value:$},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async($)=>{return await(await U1(Y)).findMany({model:"account",where:[{field:"userId",value:$}]})},findAccount:async($)=>{return await(await U1(Y)).findOne({model:"account",where:[{field:"accountId",value:$}]})},findAccountByProviderId:async($,B)=>{return await(await U1(Y)).findOne({model:"account",where:[{field:"accountId",value:$},{field:"providerId",value:B}]})},findAccountByUserId:async($)=>{return await(await U1(Y)).findMany({model:"account",where:[{field:"userId",value:$}]})},updateAccount:async($,B)=>{return await Z(B,[{field:"id",value:$}],"account",void 0)},createVerificationValue:async($)=>{return await W({createdAt:new Date,updatedAt:new Date,...$},"verification",void 0)},findVerificationValue:async($)=>{let B=await(await U1(Y)).findMany({model:"verification",where:[{field:"identifier",value:$}],sortBy:{field:"createdAt",direction:"desc"},limit:1});if(!J.verification?.disableCleanup)await(await U1(Y)).deleteMany({model:"verification",where:[{field:"expiresAt",value:new Date,operator:"lt"}]});return B[0]},deleteVerificationValue:async($)=>{await(await U1(Y)).delete({model:"verification",where:[{field:"id",value:$}]})},deleteVerificationByIdentifier:async($)=>{await(await U1(Y)).delete({model:"verification",where:[{field:"identifier",value:$}]})},updateVerificationValue:async($,B)=>{return await Z(B,[{field:"id",value:$}],"verification",void 0)}}};function e70(Y){let X=QQ(Y),Q={};for(let J in X){let G=X[J],K=G.fields,W={};if(Object.entries(K).forEach(([Z,H])=>{if(W[H.fieldName||Z]=H,H.references){let F=X[H.references.model];if(F)W[H.fieldName||Z].references={...H.references,model:F.modelName,field:H.references.field}}}),Q[G.modelName]){Q[G.modelName].fields={...Q[G.modelName].fields,...W};continue}Q[G.modelName]={fields:W,order:G.order||1/0}}return Q}var kD6={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};function YW0(Y,X,Q){function J(K){return K.toLowerCase().split("(")[0].trim()}if(X==="string[]"||X==="number[]")return Y.toLowerCase().includes("json");let G=kD6[Q];return(Array.isArray(X)?G.string.map((K)=>K.toLowerCase()):G[X].map((K)=>K.toLowerCase())).includes(J(Y))}async function vD6(Y){try{let X=await t5`SHOW search_path`.execute(Y);if(X.rows[0]?.search_path)return X.rows[0].search_path.split(",").map((Q)=>Q.trim()).map((Q)=>Q.replace(/^["']|["']$/g,"")).filter((Q)=>!Q.startsWith("$"))[0]||"public"}catch(X){}return"public"}async function rD(Y){let X=e70(Y),Q=XV(Y.logger),{kysely:J,databaseType:G}=await XC(Y);if(!G)Q.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),G="sqlite";if(!J)Q.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1);let K="public";if(G==="postgres"){K=await vD6(J),Q.debug(`PostgreSQL migration: Using schema '${K}' (from search_path)`);try{if(!(await t5`
|
|
410
410
|
SELECT schema_name
|