@decocms/mesh 2.39.0 → 2.39.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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var mz1=Object.create;var{getPrototypeOf:lz1,defineProperty:dh,getOwnPropertyNames:dz1}=Object;var pz1=Object.prototype.hasOwnProperty;var w6=(X,Y,Q)=>{Q=X!=null?mz1(lz1(X)):{};let J=Y||!X||!X.__esModule?dh(Q,"default",{value:X,enumerable:!0}):Q;for(let G of dz1(X))if(!pz1.call(J,G))dh(J,G,{get:()=>X[G],enumerable:!0});return J};var I=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var c1=(X,Y)=>{for(var Q in Y)dh(X,Q,{get:Y[Q],enumerable:!0,configurable:!0,set:(J)=>Y[Q]=()=>J})};var S=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var B0=import.meta.require,ph=(X,Y,Q)=>{if(Y!=null){if(typeof Y!=="object"&&typeof Y!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let J;if(Q)J=Y[Symbol.asyncDispose];if(J===void 0)J=Y[Symbol.dispose];if(typeof J!=="function")throw TypeError("Object not disposable");X.push([Q,J,Y])}else if(Q)X.push([Q]);return Y},U50=(X,Y,Q)=>{let J=(W)=>Y=Q?new SuppressedError(W,Y,"An error was suppressed during disposal"):(Q=!0,W),G=(W)=>{while(W=X.pop())try{var Z=W[1]&&W[1].call(W[2]);if(W[0])return Promise.resolve(Z).then(G,($)=>(J($),G()))}catch($){J($)}if(Q)throw Y};return G()};var AA="user-sandbox",B50="Create embeddable integration flows for platform end-users";import{sql as UD}from"kysely";var z50;var D50=S(()=>{z50={name:"001-user-sandbox",async up(X){await X.schema.createTable("user_sandbox").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Y)=>Y.notNull()).addColumn("description","text").addColumn("icon","text").addColumn("required_apps","text",(Y)=>Y.notNull()).addColumn("redirect_url","text").addColumn("webhook_url","text").addColumn("event_type","text",(Y)=>Y.notNull().defaultTo("integration.completed")).addColumn("agent_title_template","text",(Y)=>Y.notNull().defaultTo("Agent for {{externalUserId}}")).addColumn("agent_instructions","text").addColumn("tool_selection_mode","text",(Y)=>Y.notNull().defaultTo("inclusion")).addColumn("status","text",(Y)=>Y.notNull().defaultTo("active")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Y)=>Y.references("user.id").onDelete("set null")).execute(),await X.schema.createIndex("idx_user_sandbox_org").on("user_sandbox").column("organization_id").execute(),await X.schema.createTable("user_sandbox_sessions").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("template_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("status","text",(Y)=>Y.notNull().defaultTo("pending")).addColumn("app_statuses","text",(Y)=>Y.notNull().defaultTo("{}")).addColumn("created_agent_id","text",(Y)=>Y.references("connections.id").onDelete("set null")).addColumn("redirect_url","text").addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("expires_at","text",(Y)=>Y.notNull()).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_template").on("user_sandbox_sessions").column("template_id").execute(),await X.schema.createIndex("idx_user_sandbox_sessions_external_user").on("user_sandbox_sessions").columns(["template_id","external_user_id"]).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_org").on("user_sandbox_sessions").column("organization_id").execute(),await X.schema.createTable("user_sandbox_agents").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("user_sandbox_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("connection_id","text",(Y)=>Y.notNull().references("connections.id").onDelete("cascade")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).execute(),await X.schema.createIndex("idx_user_sandbox_agents_unique").on("user_sandbox_agents").columns(["user_sandbox_id","external_user_id"]).unique().execute(),await X.schema.createIndex("idx_user_sandbox_agents_connection").on("user_sandbox_agents").column("connection_id").execute()},async down(X){await X.schema.dropIndex("idx_user_sandbox_agents_connection").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_agents_unique").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_org").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_external_user").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_template").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_org").ifExists().execute(),await X.schema.dropTable("user_sandbox_agents").ifExists().execute(),await X.schema.dropTable("user_sandbox_sessions").ifExists().execute(),await X.schema.dropTable("user_sandbox").ifExists().execute()}}});var N50;var O50=S(()=>{D50();N50=[z50]});function EA(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}class BD{db;constructor(X){this.db=X}async create(X){let Y=EA("usb"),Q=new Date().toISOString(),J={id:Y,organization_id:X.organization_id,title:X.title,description:X.description??null,icon:X.icon??null,required_apps:JSON.stringify(X.required_apps),redirect_url:X.redirect_url??null,webhook_url:X.webhook_url??null,event_type:X.event_type??"integration.completed",agent_title_template:X.agent_title_template??"{{externalUserId}}'s Agent",agent_instructions:X.agent_instructions??null,tool_selection_mode:X.tool_selection_mode??"inclusion",status:"active",created_at:Q,updated_at:Q,created_by:X.created_by??null};await this.db.insertInto("user_sandbox").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create user sandbox with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async list(X){return(await this.db.selectFrom("user_sandbox").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.icon!==void 0)J.icon=Y.icon;if(Y.required_apps!==void 0)J.required_apps=JSON.stringify(Y.required_apps);if(Y.redirect_url!==void 0)J.redirect_url=Y.redirect_url;if(Y.webhook_url!==void 0)J.webhook_url=Y.webhook_url;if(Y.event_type!==void 0)J.event_type=Y.event_type;if(Y.agent_title_template!==void 0)J.agent_title_template=Y.agent_title_template;if(Y.agent_instructions!==void 0)J.agent_instructions=Y.agent_instructions;if(Y.tool_selection_mode!==void 0)J.tool_selection_mode=Y.tool_selection_mode;if(Y.status!==void 0)J.status=Y.status;await this.db.updateTable("user_sandbox").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Template not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox").where("id","=",X).execute()}deserialize(X){let Y=[];try{Y=JSON.parse(X.required_apps)}catch{Y=[]}return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,icon:X.icon,required_apps:Y,redirect_url:X.redirect_url,webhook_url:X.webhook_url,event_type:X.event_type,agent_title_template:X.agent_title_template,agent_instructions:X.agent_instructions,tool_selection_mode:X.tool_selection_mode,status:X.status,created_at:X.created_at,updated_at:X.updated_at,created_by:X.created_by}}}var ch=()=>{};class zD{db;constructor(X){this.db=X}async create(X){let Y=EA("uss"),Q=new Date().toISOString(),J={id:Y,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:"pending",app_statuses:"{}",created_agent_id:X.created_agent_id??null,redirect_url:X.redirect_url??null,created_at:Q,updated_at:Q,expires_at:X.expires_at};await this.db.insertInto("user_sandbox_sessions").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create session with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async findExisting(X,Y){let Q=new Date().toISOString(),J=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).where("external_user_id","=",Y).where("expires_at",">",Q).where("status","!=","completed").orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return this.deserialize(J)}async listByTemplate(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async listByOrganization(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.status!==void 0)J.status=Y.status;if(Y.app_statuses!==void 0)J.app_statuses=JSON.stringify(Y.app_statuses);if(Y.created_agent_id!==void 0)J.created_agent_id=Y.created_agent_id;await this.db.updateTable("user_sandbox_sessions").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Session not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox_sessions").where("id","=",X).execute()}async deleteExpired(){let X=new Date().toISOString(),Y=await this.db.deleteFrom("user_sandbox_sessions").where("expires_at","<",X).where("status","!=","completed").executeTakeFirst();return Number(Y.numDeletedRows??0)}deserialize(X){let Y={};try{Y=JSON.parse(X.app_statuses)}catch{Y={}}return{id:X.id,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:X.status,app_statuses:Y,created_agent_id:X.created_agent_id,redirect_url:X.redirect_url,created_at:X.created_at,updated_at:X.updated_at,expires_at:X.expires_at}}}var nh=()=>{};function DD(X){ih=X}function p9(){if(!ih)throw Error(`Plugin storage not initialized. Make sure the "${AA}" plugin is enabled.`);return ih}function ah(){return process.env.MESH_PUBLIC_URL||"http://localhost:3000"}var ih=null;var DG=()=>{};function L50(X){let Y=X.db,Q={templates:new BD(Y),sessions:new zD(Y)};return DD(Q),Q}var w50=S(()=>{ch();nh();DG()});function F0(X,Y,Q){function J($,K){if(!$._zod)Object.defineProperty($,"_zod",{value:{def:K,constr:Z,traits:new Set},enumerable:!1});if($._zod.traits.has(X))return;$._zod.traits.add(X),Y($,K);let H=Z.prototype,F=Object.keys(H);for(let V=0;V<F.length;V++){let q=F[V];if(!(q in $))$[q]=H[q].bind($)}}let G=Q?.Parent??Object;class W extends G{}Object.defineProperty(W,"name",{value:X});function Z($){var K;let H=Q?.Parent?new W:this;J(H,$),(K=H._zod).deferred??(K.deferred=[]);for(let F of H._zod.deferred)F();return H}return Object.defineProperty(Z,"init",{value:J}),Object.defineProperty(Z,Symbol.hasInstance,{value:($)=>{if(Q?.Parent&&$ instanceof Q.Parent)return!0;return $?._zod?.traits?.has(X)}}),Object.defineProperty(Z,"name",{value:X}),Z}function f8(X){if(X)Object.assign(ND,X);return ND}var LV,jA,NG,tK,ND;var wV=S(()=>{LV=Object.freeze({status:"aborted"});jA=Symbol("zod_brand");NG=class NG extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};tK=class tK extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}};ND={}});var i0={};c1(i0,{unwrapMessage:()=>OD,uint8ArrayToHex:()=>HD1,uint8ArrayToBase64url:()=>$D1,uint8ArrayToBase64:()=>R50,stringifyPrimitive:()=>p0,slugify:()=>sh,shallowClone:()=>RA,safeExtend:()=>E50,required:()=>C50,randomString:()=>XD1,propertyKeyTypes:()=>MD,promiseAllObject:()=>ez1,primitiveTypes:()=>eh,prefixIssues:()=>SQ,pick:()=>P50,partial:()=>j50,parsedType:()=>r0,optionalKeys:()=>Xx,omit:()=>T50,objectClone:()=>oz1,numKeys:()=>YD1,nullish:()=>yZ,normalizeParams:()=>s0,mergeDefs:()=>e7,merge:()=>GD1,jsonStringifyReplacer:()=>MV,joinValues:()=>A0,issue:()=>TV,isPlainObject:()=>fZ,isObject:()=>eK,hexToUint8Array:()=>KD1,getSizableOrigin:()=>PD,getParsedType:()=>QD1,getLengthableOrigin:()=>TD,getEnumValues:()=>LD,getElementAtPath:()=>tz1,floatSafeRemainder:()=>oh,finalizeIssue:()=>c9,extend:()=>A50,escapeRegex:()=>VJ,esc:()=>CA,defineLazy:()=>D6,createTransparentProxy:()=>JD1,cloneDef:()=>sz1,clone:()=>_X,cleanRegex:()=>wD,cleanEnum:()=>WD1,captureStackTrace:()=>IA,cached:()=>PV,base64urlToUint8Array:()=>ZD1,base64ToUint8Array:()=>I50,assignProp:()=>bZ,assertNotEqual:()=>nz1,assertNever:()=>az1,assertIs:()=>iz1,assertEqual:()=>cz1,assert:()=>rz1,allowsEval:()=>th,aborted:()=>hZ,NUMBER_FORMAT_RANGES:()=>Yx,Class:()=>S50,BIGINT_FORMAT_RANGES:()=>Qx});function cz1(X){return X}function nz1(X){return X}function iz1(X){}function az1(X){throw Error("Unexpected value in exhaustive check")}function rz1(X){}function LD(X){let Y=Object.values(X).filter((J)=>typeof J==="number");return Object.entries(X).filter(([J,G])=>Y.indexOf(+J)===-1).map(([J,G])=>G)}function A0(X,Y="|"){return X.map((Q)=>p0(Q)).join(Y)}function MV(X,Y){if(typeof Y==="bigint")return Y.toString();return Y}function PV(X){return{get value(){{let Q=X();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function yZ(X){return X===null||X===void 0}function wD(X){let Y=X.startsWith("^")?1:0,Q=X.endsWith("$")?X.length-1:X.length;return X.slice(Y,Q)}function oh(X,Y){let Q=(X.toString().split(".")[1]||"").length,J=Y.toString(),G=(J.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(J)){let K=J.match(/\d?e-(\d?)/);if(K?.[1])G=Number.parseInt(K[1])}let W=Q>G?Q:G,Z=Number.parseInt(X.toFixed(W).replace(".","")),$=Number.parseInt(Y.toFixed(W).replace(".",""));return Z%$/10**W}function D6(X,Y,Q){let J=void 0;Object.defineProperty(X,Y,{get(){if(J===M50)return;if(J===void 0)J=M50,J=Q();return J},set(G){Object.defineProperty(X,Y,{value:G})},configurable:!0})}function oz1(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function bZ(X,Y,Q){Object.defineProperty(X,Y,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function e7(...X){let Y={};for(let Q of X){let J=Object.getOwnPropertyDescriptors(Q);Object.assign(Y,J)}return Object.defineProperties({},Y)}function sz1(X){return e7(X._zod.def)}function tz1(X,Y){if(!Y)return X;return Y.reduce((Q,J)=>Q?.[J],X)}function ez1(X){let Y=Object.keys(X),Q=Y.map((J)=>X[J]);return Promise.all(Q).then((J)=>{let G={};for(let W=0;W<Y.length;W++)G[Y[W]]=J[W];return G})}function XD1(X=10){let Q="";for(let J=0;J<X;J++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function CA(X){return JSON.stringify(X)}function sh(X){return X.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function eK(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function fZ(X){if(eK(X)===!1)return!1;let Y=X.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let Q=Y.prototype;if(eK(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function RA(X){if(fZ(X))return{...X};if(Array.isArray(X))return[...X];return X}function YD1(X){let Y=0;for(let Q in X)if(Object.prototype.hasOwnProperty.call(X,Q))Y++;return Y}function VJ(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _X(X,Y,Q){let J=new X._zod.constr(Y??X._zod.def);if(!Y||Q?.parent)J._zod.parent=X;return J}function s0(X){let Y=X;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function JD1(X){let Y;return new Proxy({},{get(Q,J,G){return Y??(Y=X()),Reflect.get(Y,J,G)},set(Q,J,G,W){return Y??(Y=X()),Reflect.set(Y,J,G,W)},has(Q,J){return Y??(Y=X()),Reflect.has(Y,J)},deleteProperty(Q,J){return Y??(Y=X()),Reflect.deleteProperty(Y,J)},ownKeys(Q){return Y??(Y=X()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(Q,J){return Y??(Y=X()),Reflect.getOwnPropertyDescriptor(Y,J)},defineProperty(Q,J,G){return Y??(Y=X()),Reflect.defineProperty(Y,J,G)}})}function p0(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function Xx(X){return Object.keys(X).filter((Y)=>{return X[Y]._zod.optin==="optional"&&X[Y]._zod.optout==="optional"})}function P50(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let W=e7(X._zod.def,{get shape(){let Z={};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;Z[$]=Q.shape[$]}return bZ(this,"shape",Z),Z},checks:[]});return _X(X,W)}function T50(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let W=e7(X._zod.def,{get shape(){let Z={...X._zod.def.shape};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete Z[$]}return bZ(this,"shape",Z),Z},checks:[]});return _X(X,W)}function A50(X,Y){if(!fZ(Y))throw Error("Invalid input to extend: expected a plain object");let Q=X._zod.def.checks;if(Q&&Q.length>0){let W=X._zod.def.shape;for(let Z in Y)if(Object.getOwnPropertyDescriptor(W,Z)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let G=e7(X._zod.def,{get shape(){let W={...X._zod.def.shape,...Y};return bZ(this,"shape",W),W}});return _X(X,G)}function E50(X,Y){if(!fZ(Y))throw Error("Invalid input to safeExtend: expected a plain object");let Q=e7(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y};return bZ(this,"shape",J),J}});return _X(X,Q)}function GD1(X,Y){let Q=e7(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y._zod.def.shape};return bZ(this,"shape",J),J},get catchall(){return Y._zod.def.catchall},checks:[]});return _X(X,Q)}function j50(X,Y,Q){let G=Y._zod.def.checks;if(G&&G.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let Z=e7(Y._zod.def,{get shape(){let $=Y._zod.def.shape,K={...$};if(Q)for(let H in Q){if(!(H in $))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;K[H]=X?new X({type:"optional",innerType:$[H]}):$[H]}else for(let H in $)K[H]=X?new X({type:"optional",innerType:$[H]}):$[H];return bZ(this,"shape",K),K},checks:[]});return _X(Y,Z)}function C50(X,Y,Q){let J=e7(Y._zod.def,{get shape(){let G=Y._zod.def.shape,W={...G};if(Q)for(let Z in Q){if(!(Z in W))throw Error(`Unrecognized key: "${Z}"`);if(!Q[Z])continue;W[Z]=new X({type:"nonoptional",innerType:G[Z]})}else for(let Z in G)W[Z]=new X({type:"nonoptional",innerType:G[Z]});return bZ(this,"shape",W),W}});return _X(Y,J)}function hZ(X,Y=0){if(X.aborted===!0)return!0;for(let Q=Y;Q<X.issues.length;Q++)if(X.issues[Q]?.continue!==!0)return!0;return!1}function SQ(X,Y){return Y.map((Q)=>{var J;return(J=Q).path??(J.path=[]),Q.path.unshift(X),Q})}function OD(X){return typeof X==="string"?X:X?.message}function c9(X,Y,Q){let J={...X,path:X.path??[]};if(!X.message){let G=OD(X.inst?._zod.def?.error?.(X))??OD(Y?.error?.(X))??OD(Q.customError?.(X))??OD(Q.localeError?.(X))??"Invalid input";J.message=G}if(delete J.inst,delete J.continue,!Y?.reportInput)delete J.input;return J}function PD(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function TD(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function r0(X){let Y=typeof X;switch(Y){case"number":return Number.isNaN(X)?"nan":"number";case"object":{if(X===null)return"null";if(Array.isArray(X))return"array";let Q=X;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return Y}function TV(...X){let[Y,Q,J]=X;if(typeof Y==="string")return{message:Y,code:"custom",input:Q,inst:J};return{...Y}}function WD1(X){return Object.entries(X).filter(([Y,Q])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function I50(X){let Y=atob(X),Q=new Uint8Array(Y.length);for(let J=0;J<Y.length;J++)Q[J]=Y.charCodeAt(J);return Q}function R50(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCharCode(X[Q]);return btoa(Y)}function ZD1(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-Y.length%4)%4);return I50(Y+Q)}function $D1(X){return R50(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function KD1(X){let Y=X.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(Y.length/2);for(let J=0;J<Y.length;J+=2)Q[J/2]=Number.parseInt(Y.slice(J,J+2),16);return Q}function HD1(X){return Array.from(X).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class S50{constructor(...X){}}var M50,IA,th,QD1=(X)=>{let Y=typeof X;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(X)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(X))return"array";if(X===null)return"null";if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return"promise";if(typeof Map<"u"&&X instanceof Map)return"map";if(typeof Set<"u"&&X instanceof Set)return"set";if(typeof Date<"u"&&X instanceof Date)return"date";if(typeof File<"u"&&X instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},MD,eh,Yx,Qx;var b1=S(()=>{M50=Symbol("evaluating");IA="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};th=PV(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});MD=new Set(["string","number","symbol"]),eh=new Set(["string","number","bigint","boolean","symbol","undefined"]);Yx={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Qx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function AV(X,Y=(Q)=>Q.message){let Q={},J=[];for(let G of X.issues)if(G.path.length>0)Q[G.path[0]]=Q[G.path[0]]||[],Q[G.path[0]].push(Y(G));else J.push(Y(G));return{formErrors:J,fieldErrors:Q}}function EV(X,Y=(Q)=>Q.message){let Q={_errors:[]},J=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((Z)=>J({issues:Z}));else if(W.code==="invalid_key")J({issues:W.issues});else if(W.code==="invalid_element")J({issues:W.issues});else if(W.path.length===0)Q._errors.push(Y(W));else{let Z=Q,$=0;while($<W.path.length){let K=W.path[$];if($!==W.path.length-1)Z[K]=Z[K]||{_errors:[]};else Z[K]=Z[K]||{_errors:[]},Z[K]._errors.push(Y(W));Z=Z[K],$++}}};return J(X),Q}function SA(X,Y=(Q)=>Q.message){let Q={errors:[]},J=(G,W=[])=>{var Z,$;for(let K of G.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((H)=>J({issues:H},K.path));else if(K.code==="invalid_key")J({issues:K.issues},K.path);else if(K.code==="invalid_element")J({issues:K.issues},K.path);else{let H=[...W,...K.path];if(H.length===0){Q.errors.push(Y(K));continue}let F=Q,V=0;while(V<H.length){let q=H[V],B=V===H.length-1;if(typeof q==="string")F.properties??(F.properties={}),(Z=F.properties)[q]??(Z[q]={errors:[]}),F=F.properties[q];else F.items??(F.items=[]),($=F.items)[q]??($[q]={errors:[]}),F=F.items[q];if(B)F.errors.push(Y(K));V++}}};return J(X),Q}function v50(X){let Y=[],Q=X.map((J)=>typeof J==="object"?J.key:J);for(let J of Q)if(typeof J==="number")Y.push(`[${J}]`);else if(typeof J==="symbol")Y.push(`[${JSON.stringify(String(J))}]`);else if(/[^\w$]/.test(J))Y.push(`[${JSON.stringify(J)}]`);else{if(Y.length)Y.push(".");Y.push(J)}return Y.join("")}function kA(X){let Y=[],Q=[...X.issues].sort((J,G)=>(J.path??[]).length-(G.path??[]).length);for(let J of Q)if(Y.push(`\u2716 ${J.message}`),J.path?.length)Y.push(` \u2192 at ${v50(J.path)}`);return Y.join(`
3
+ var mz1=Object.create;var{getPrototypeOf:lz1,defineProperty:dh,getOwnPropertyNames:dz1}=Object;var pz1=Object.prototype.hasOwnProperty;var w6=(X,Y,Q)=>{Q=X!=null?mz1(lz1(X)):{};let J=Y||!X||!X.__esModule?dh(Q,"default",{value:X,enumerable:!0}):Q;for(let G of dz1(X))if(!pz1.call(J,G))dh(J,G,{get:()=>X[G],enumerable:!0});return J};var I=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var c1=(X,Y)=>{for(var Q in Y)dh(X,Q,{get:Y[Q],enumerable:!0,configurable:!0,set:(J)=>Y[Q]=()=>J})};var S=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var B0=import.meta.require,ph=(X,Y,Q)=>{if(Y!=null){if(typeof Y!=="object"&&typeof Y!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let J;if(Q)J=Y[Symbol.asyncDispose];if(J===void 0)J=Y[Symbol.dispose];if(typeof J!=="function")throw TypeError("Object not disposable");X.push([Q,J,Y])}else if(Q)X.push([Q]);return Y},U50=(X,Y,Q)=>{let J=(W)=>Y=Q?new SuppressedError(W,Y,"An error was suppressed during disposal"):(Q=!0,W),G=(W)=>{while(W=X.pop())try{var Z=W[1]&&W[1].call(W[2]);if(W[0])return Promise.resolve(Z).then(G,($)=>(J($),G()))}catch($){J($)}if(Q)throw Y};return G()};var AA="user-sandbox",B50="Create embeddable integration flows for platform end-users";import{sql as UD}from"kysely";var z50;var D50=S(()=>{z50={name:"001-user-sandbox",async up(X){await X.schema.createTable("user_sandbox").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Y)=>Y.notNull()).addColumn("description","text").addColumn("icon","text").addColumn("required_apps","text",(Y)=>Y.notNull()).addColumn("redirect_url","text").addColumn("webhook_url","text").addColumn("event_type","text",(Y)=>Y.notNull().defaultTo("integration.completed")).addColumn("agent_title_template","text",(Y)=>Y.notNull().defaultTo("Agent for {{externalUserId}}")).addColumn("agent_instructions","text").addColumn("tool_selection_mode","text",(Y)=>Y.notNull().defaultTo("inclusion")).addColumn("status","text",(Y)=>Y.notNull().defaultTo("active")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Y)=>Y.references("user.id").onDelete("set null")).execute(),await X.schema.createIndex("idx_user_sandbox_org").on("user_sandbox").column("organization_id").execute(),await X.schema.createTable("user_sandbox_sessions").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("template_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("status","text",(Y)=>Y.notNull().defaultTo("pending")).addColumn("app_statuses","text",(Y)=>Y.notNull().defaultTo("{}")).addColumn("created_agent_id","text",(Y)=>Y.references("connections.id").onDelete("set null")).addColumn("redirect_url","text").addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).addColumn("expires_at","text",(Y)=>Y.notNull()).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_template").on("user_sandbox_sessions").column("template_id").execute(),await X.schema.createIndex("idx_user_sandbox_sessions_external_user").on("user_sandbox_sessions").columns(["template_id","external_user_id"]).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_org").on("user_sandbox_sessions").column("organization_id").execute(),await X.schema.createTable("user_sandbox_agents").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("user_sandbox_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("connection_id","text",(Y)=>Y.notNull().references("connections.id").onDelete("cascade")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(UD`CURRENT_TIMESTAMP`)).execute(),await X.schema.createIndex("idx_user_sandbox_agents_unique").on("user_sandbox_agents").columns(["user_sandbox_id","external_user_id"]).unique().execute(),await X.schema.createIndex("idx_user_sandbox_agents_connection").on("user_sandbox_agents").column("connection_id").execute()},async down(X){await X.schema.dropIndex("idx_user_sandbox_agents_connection").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_agents_unique").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_org").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_external_user").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_template").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_org").ifExists().execute(),await X.schema.dropTable("user_sandbox_agents").ifExists().execute(),await X.schema.dropTable("user_sandbox_sessions").ifExists().execute(),await X.schema.dropTable("user_sandbox").ifExists().execute()}}});var N50;var O50=S(()=>{D50();N50=[z50]});function EA(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}class BD{db;constructor(X){this.db=X}async create(X){let Y=EA("usb"),Q=new Date().toISOString(),J={id:Y,organization_id:X.organization_id,title:X.title,description:X.description??null,icon:X.icon??null,required_apps:JSON.stringify(X.required_apps),redirect_url:X.redirect_url??null,webhook_url:X.webhook_url??null,event_type:X.event_type??"integration.completed",agent_title_template:X.agent_title_template??"{{externalUserId}}'s Agent",agent_instructions:X.agent_instructions??null,tool_selection_mode:X.tool_selection_mode??"inclusion",status:"active",created_at:Q,updated_at:Q,created_by:X.created_by??null};await this.db.insertInto("user_sandbox").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create user sandbox with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async list(X){return(await this.db.selectFrom("user_sandbox").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.icon!==void 0)J.icon=Y.icon;if(Y.required_apps!==void 0)J.required_apps=JSON.stringify(Y.required_apps);if(Y.redirect_url!==void 0)J.redirect_url=Y.redirect_url;if(Y.webhook_url!==void 0)J.webhook_url=Y.webhook_url;if(Y.event_type!==void 0)J.event_type=Y.event_type;if(Y.agent_title_template!==void 0)J.agent_title_template=Y.agent_title_template;if(Y.agent_instructions!==void 0)J.agent_instructions=Y.agent_instructions;if(Y.tool_selection_mode!==void 0)J.tool_selection_mode=Y.tool_selection_mode;if(Y.status!==void 0)J.status=Y.status;await this.db.updateTable("user_sandbox").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Template not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox").where("id","=",X).execute()}deserialize(X){let Y=[];try{Y=JSON.parse(X.required_apps)}catch{Y=[]}return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,icon:X.icon,required_apps:Y,redirect_url:X.redirect_url,webhook_url:X.webhook_url,event_type:X.event_type,agent_title_template:X.agent_title_template,agent_instructions:X.agent_instructions,tool_selection_mode:X.tool_selection_mode,status:X.status,created_at:X.created_at,updated_at:X.updated_at,created_by:X.created_by}}}var ch=()=>{};class zD{db;constructor(X){this.db=X}async create(X){let Y=EA("uss"),Q=new Date().toISOString(),J={id:Y,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:"pending",app_statuses:"{}",created_agent_id:X.created_agent_id??null,redirect_url:X.redirect_url??null,created_at:Q,updated_at:Q,expires_at:X.expires_at};await this.db.insertInto("user_sandbox_sessions").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create session with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async findExisting(X,Y){let Q=new Date().toISOString(),J=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).where("external_user_id","=",Y).where("expires_at",">",Q).where("status","!=","completed").orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return this.deserialize(J)}async listByTemplate(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async listByOrganization(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.status!==void 0)J.status=Y.status;if(Y.app_statuses!==void 0)J.app_statuses=JSON.stringify(Y.app_statuses);if(Y.created_agent_id!==void 0)J.created_agent_id=Y.created_agent_id;await this.db.updateTable("user_sandbox_sessions").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Session not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox_sessions").where("id","=",X).execute()}async deleteExpired(){let X=new Date().toISOString(),Y=await this.db.deleteFrom("user_sandbox_sessions").where("expires_at","<",X).where("status","!=","completed").executeTakeFirst();return Number(Y.numDeletedRows??0)}deserialize(X){let Y={};try{Y=JSON.parse(X.app_statuses)}catch{Y={}}return{id:X.id,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:X.status,app_statuses:Y,created_agent_id:X.created_agent_id,redirect_url:X.redirect_url,created_at:X.created_at,updated_at:X.updated_at,expires_at:X.expires_at}}}var nh=()=>{};function DD(X){ih=X}function p9(){if(!ih)throw Error(`Plugin storage not initialized. Make sure the "${AA}" plugin is enabled.`);return ih}function ah(){return process.env.BASE_URL||"http://localhost:3000"}var ih=null;var DG=()=>{};function L50(X){let Y=X.db,Q={templates:new BD(Y),sessions:new zD(Y)};return DD(Q),Q}var w50=S(()=>{ch();nh();DG()});function F0(X,Y,Q){function J($,K){if(!$._zod)Object.defineProperty($,"_zod",{value:{def:K,constr:Z,traits:new Set},enumerable:!1});if($._zod.traits.has(X))return;$._zod.traits.add(X),Y($,K);let H=Z.prototype,F=Object.keys(H);for(let V=0;V<F.length;V++){let q=F[V];if(!(q in $))$[q]=H[q].bind($)}}let G=Q?.Parent??Object;class W extends G{}Object.defineProperty(W,"name",{value:X});function Z($){var K;let H=Q?.Parent?new W:this;J(H,$),(K=H._zod).deferred??(K.deferred=[]);for(let F of H._zod.deferred)F();return H}return Object.defineProperty(Z,"init",{value:J}),Object.defineProperty(Z,Symbol.hasInstance,{value:($)=>{if(Q?.Parent&&$ instanceof Q.Parent)return!0;return $?._zod?.traits?.has(X)}}),Object.defineProperty(Z,"name",{value:X}),Z}function f8(X){if(X)Object.assign(ND,X);return ND}var LV,jA,NG,tK,ND;var wV=S(()=>{LV=Object.freeze({status:"aborted"});jA=Symbol("zod_brand");NG=class NG extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};tK=class tK extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}};ND={}});var i0={};c1(i0,{unwrapMessage:()=>OD,uint8ArrayToHex:()=>HD1,uint8ArrayToBase64url:()=>$D1,uint8ArrayToBase64:()=>R50,stringifyPrimitive:()=>p0,slugify:()=>sh,shallowClone:()=>RA,safeExtend:()=>E50,required:()=>C50,randomString:()=>XD1,propertyKeyTypes:()=>MD,promiseAllObject:()=>ez1,primitiveTypes:()=>eh,prefixIssues:()=>SQ,pick:()=>P50,partial:()=>j50,parsedType:()=>r0,optionalKeys:()=>Xx,omit:()=>T50,objectClone:()=>oz1,numKeys:()=>YD1,nullish:()=>yZ,normalizeParams:()=>s0,mergeDefs:()=>e7,merge:()=>GD1,jsonStringifyReplacer:()=>MV,joinValues:()=>A0,issue:()=>TV,isPlainObject:()=>fZ,isObject:()=>eK,hexToUint8Array:()=>KD1,getSizableOrigin:()=>PD,getParsedType:()=>QD1,getLengthableOrigin:()=>TD,getEnumValues:()=>LD,getElementAtPath:()=>tz1,floatSafeRemainder:()=>oh,finalizeIssue:()=>c9,extend:()=>A50,escapeRegex:()=>VJ,esc:()=>CA,defineLazy:()=>D6,createTransparentProxy:()=>JD1,cloneDef:()=>sz1,clone:()=>_X,cleanRegex:()=>wD,cleanEnum:()=>WD1,captureStackTrace:()=>IA,cached:()=>PV,base64urlToUint8Array:()=>ZD1,base64ToUint8Array:()=>I50,assignProp:()=>bZ,assertNotEqual:()=>nz1,assertNever:()=>az1,assertIs:()=>iz1,assertEqual:()=>cz1,assert:()=>rz1,allowsEval:()=>th,aborted:()=>hZ,NUMBER_FORMAT_RANGES:()=>Yx,Class:()=>S50,BIGINT_FORMAT_RANGES:()=>Qx});function cz1(X){return X}function nz1(X){return X}function iz1(X){}function az1(X){throw Error("Unexpected value in exhaustive check")}function rz1(X){}function LD(X){let Y=Object.values(X).filter((J)=>typeof J==="number");return Object.entries(X).filter(([J,G])=>Y.indexOf(+J)===-1).map(([J,G])=>G)}function A0(X,Y="|"){return X.map((Q)=>p0(Q)).join(Y)}function MV(X,Y){if(typeof Y==="bigint")return Y.toString();return Y}function PV(X){return{get value(){{let Q=X();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function yZ(X){return X===null||X===void 0}function wD(X){let Y=X.startsWith("^")?1:0,Q=X.endsWith("$")?X.length-1:X.length;return X.slice(Y,Q)}function oh(X,Y){let Q=(X.toString().split(".")[1]||"").length,J=Y.toString(),G=(J.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(J)){let K=J.match(/\d?e-(\d?)/);if(K?.[1])G=Number.parseInt(K[1])}let W=Q>G?Q:G,Z=Number.parseInt(X.toFixed(W).replace(".","")),$=Number.parseInt(Y.toFixed(W).replace(".",""));return Z%$/10**W}function D6(X,Y,Q){let J=void 0;Object.defineProperty(X,Y,{get(){if(J===M50)return;if(J===void 0)J=M50,J=Q();return J},set(G){Object.defineProperty(X,Y,{value:G})},configurable:!0})}function oz1(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function bZ(X,Y,Q){Object.defineProperty(X,Y,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function e7(...X){let Y={};for(let Q of X){let J=Object.getOwnPropertyDescriptors(Q);Object.assign(Y,J)}return Object.defineProperties({},Y)}function sz1(X){return e7(X._zod.def)}function tz1(X,Y){if(!Y)return X;return Y.reduce((Q,J)=>Q?.[J],X)}function ez1(X){let Y=Object.keys(X),Q=Y.map((J)=>X[J]);return Promise.all(Q).then((J)=>{let G={};for(let W=0;W<Y.length;W++)G[Y[W]]=J[W];return G})}function XD1(X=10){let Q="";for(let J=0;J<X;J++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function CA(X){return JSON.stringify(X)}function sh(X){return X.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function eK(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function fZ(X){if(eK(X)===!1)return!1;let Y=X.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let Q=Y.prototype;if(eK(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function RA(X){if(fZ(X))return{...X};if(Array.isArray(X))return[...X];return X}function YD1(X){let Y=0;for(let Q in X)if(Object.prototype.hasOwnProperty.call(X,Q))Y++;return Y}function VJ(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _X(X,Y,Q){let J=new X._zod.constr(Y??X._zod.def);if(!Y||Q?.parent)J._zod.parent=X;return J}function s0(X){let Y=X;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function JD1(X){let Y;return new Proxy({},{get(Q,J,G){return Y??(Y=X()),Reflect.get(Y,J,G)},set(Q,J,G,W){return Y??(Y=X()),Reflect.set(Y,J,G,W)},has(Q,J){return Y??(Y=X()),Reflect.has(Y,J)},deleteProperty(Q,J){return Y??(Y=X()),Reflect.deleteProperty(Y,J)},ownKeys(Q){return Y??(Y=X()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(Q,J){return Y??(Y=X()),Reflect.getOwnPropertyDescriptor(Y,J)},defineProperty(Q,J,G){return Y??(Y=X()),Reflect.defineProperty(Y,J,G)}})}function p0(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function Xx(X){return Object.keys(X).filter((Y)=>{return X[Y]._zod.optin==="optional"&&X[Y]._zod.optout==="optional"})}function P50(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let W=e7(X._zod.def,{get shape(){let Z={};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;Z[$]=Q.shape[$]}return bZ(this,"shape",Z),Z},checks:[]});return _X(X,W)}function T50(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let W=e7(X._zod.def,{get shape(){let Z={...X._zod.def.shape};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete Z[$]}return bZ(this,"shape",Z),Z},checks:[]});return _X(X,W)}function A50(X,Y){if(!fZ(Y))throw Error("Invalid input to extend: expected a plain object");let Q=X._zod.def.checks;if(Q&&Q.length>0){let W=X._zod.def.shape;for(let Z in Y)if(Object.getOwnPropertyDescriptor(W,Z)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let G=e7(X._zod.def,{get shape(){let W={...X._zod.def.shape,...Y};return bZ(this,"shape",W),W}});return _X(X,G)}function E50(X,Y){if(!fZ(Y))throw Error("Invalid input to safeExtend: expected a plain object");let Q=e7(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y};return bZ(this,"shape",J),J}});return _X(X,Q)}function GD1(X,Y){let Q=e7(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y._zod.def.shape};return bZ(this,"shape",J),J},get catchall(){return Y._zod.def.catchall},checks:[]});return _X(X,Q)}function j50(X,Y,Q){let G=Y._zod.def.checks;if(G&&G.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let Z=e7(Y._zod.def,{get shape(){let $=Y._zod.def.shape,K={...$};if(Q)for(let H in Q){if(!(H in $))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;K[H]=X?new X({type:"optional",innerType:$[H]}):$[H]}else for(let H in $)K[H]=X?new X({type:"optional",innerType:$[H]}):$[H];return bZ(this,"shape",K),K},checks:[]});return _X(Y,Z)}function C50(X,Y,Q){let J=e7(Y._zod.def,{get shape(){let G=Y._zod.def.shape,W={...G};if(Q)for(let Z in Q){if(!(Z in W))throw Error(`Unrecognized key: "${Z}"`);if(!Q[Z])continue;W[Z]=new X({type:"nonoptional",innerType:G[Z]})}else for(let Z in G)W[Z]=new X({type:"nonoptional",innerType:G[Z]});return bZ(this,"shape",W),W}});return _X(Y,J)}function hZ(X,Y=0){if(X.aborted===!0)return!0;for(let Q=Y;Q<X.issues.length;Q++)if(X.issues[Q]?.continue!==!0)return!0;return!1}function SQ(X,Y){return Y.map((Q)=>{var J;return(J=Q).path??(J.path=[]),Q.path.unshift(X),Q})}function OD(X){return typeof X==="string"?X:X?.message}function c9(X,Y,Q){let J={...X,path:X.path??[]};if(!X.message){let G=OD(X.inst?._zod.def?.error?.(X))??OD(Y?.error?.(X))??OD(Q.customError?.(X))??OD(Q.localeError?.(X))??"Invalid input";J.message=G}if(delete J.inst,delete J.continue,!Y?.reportInput)delete J.input;return J}function PD(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function TD(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function r0(X){let Y=typeof X;switch(Y){case"number":return Number.isNaN(X)?"nan":"number";case"object":{if(X===null)return"null";if(Array.isArray(X))return"array";let Q=X;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return Y}function TV(...X){let[Y,Q,J]=X;if(typeof Y==="string")return{message:Y,code:"custom",input:Q,inst:J};return{...Y}}function WD1(X){return Object.entries(X).filter(([Y,Q])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function I50(X){let Y=atob(X),Q=new Uint8Array(Y.length);for(let J=0;J<Y.length;J++)Q[J]=Y.charCodeAt(J);return Q}function R50(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCharCode(X[Q]);return btoa(Y)}function ZD1(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-Y.length%4)%4);return I50(Y+Q)}function $D1(X){return R50(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function KD1(X){let Y=X.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(Y.length/2);for(let J=0;J<Y.length;J+=2)Q[J/2]=Number.parseInt(Y.slice(J,J+2),16);return Q}function HD1(X){return Array.from(X).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class S50{constructor(...X){}}var M50,IA,th,QD1=(X)=>{let Y=typeof X;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(X)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(X))return"array";if(X===null)return"null";if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return"promise";if(typeof Map<"u"&&X instanceof Map)return"map";if(typeof Set<"u"&&X instanceof Set)return"set";if(typeof Date<"u"&&X instanceof Date)return"date";if(typeof File<"u"&&X instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},MD,eh,Yx,Qx;var b1=S(()=>{M50=Symbol("evaluating");IA="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};th=PV(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});MD=new Set(["string","number","symbol"]),eh=new Set(["string","number","bigint","boolean","symbol","undefined"]);Yx={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Qx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function AV(X,Y=(Q)=>Q.message){let Q={},J=[];for(let G of X.issues)if(G.path.length>0)Q[G.path[0]]=Q[G.path[0]]||[],Q[G.path[0]].push(Y(G));else J.push(Y(G));return{formErrors:J,fieldErrors:Q}}function EV(X,Y=(Q)=>Q.message){let Q={_errors:[]},J=(G)=>{for(let W of G.issues)if(W.code==="invalid_union"&&W.errors.length)W.errors.map((Z)=>J({issues:Z}));else if(W.code==="invalid_key")J({issues:W.issues});else if(W.code==="invalid_element")J({issues:W.issues});else if(W.path.length===0)Q._errors.push(Y(W));else{let Z=Q,$=0;while($<W.path.length){let K=W.path[$];if($!==W.path.length-1)Z[K]=Z[K]||{_errors:[]};else Z[K]=Z[K]||{_errors:[]},Z[K]._errors.push(Y(W));Z=Z[K],$++}}};return J(X),Q}function SA(X,Y=(Q)=>Q.message){let Q={errors:[]},J=(G,W=[])=>{var Z,$;for(let K of G.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((H)=>J({issues:H},K.path));else if(K.code==="invalid_key")J({issues:K.issues},K.path);else if(K.code==="invalid_element")J({issues:K.issues},K.path);else{let H=[...W,...K.path];if(H.length===0){Q.errors.push(Y(K));continue}let F=Q,V=0;while(V<H.length){let q=H[V],B=V===H.length-1;if(typeof q==="string")F.properties??(F.properties={}),(Z=F.properties)[q]??(Z[q]={errors:[]}),F=F.properties[q];else F.items??(F.items=[]),($=F.items)[q]??($[q]={errors:[]}),F=F.items[q];if(B)F.errors.push(Y(K));V++}}};return J(X),Q}function v50(X){let Y=[],Q=X.map((J)=>typeof J==="object"?J.key:J);for(let J of Q)if(typeof J==="number")Y.push(`[${J}]`);else if(typeof J==="symbol")Y.push(`[${JSON.stringify(String(J))}]`);else if(/[^\w$]/.test(J))Y.push(`[${JSON.stringify(J)}]`);else{if(Y.length)Y.push(".");Y.push(J)}return Y.join("")}function kA(X){let Y=[],Q=[...X.issues].sort((J,G)=>(J.path??[]).length-(G.path??[]).length);for(let J of Q)if(Y.push(`\u2716 ${J.message}`),J.path?.length)Y.push(` \u2192 at ${v50(J.path)}`);return Y.join(`
4
4
  `)}var k50=(X,Y)=>{X.name="$ZodError",Object.defineProperty(X,"_zod",{value:X._zod,enumerable:!1}),Object.defineProperty(X,"issues",{value:Y,enumerable:!1}),X.message=JSON.stringify(Y,MV,2),Object.defineProperty(X,"toString",{value:()=>X.message,enumerable:!1})},AD,n9;var Jx=S(()=>{wV();b1();AD=F0("$ZodError",k50),n9=F0("$ZodError",k50,{Parent:Error})});var jV=(X)=>(Y,Q,J,G)=>{let W=J?Object.assign(J,{async:!1}):{async:!1},Z=Y._zod.run({value:Q,issues:[]},W);if(Z instanceof Promise)throw new NG;if(Z.issues.length){let $=new(G?.Err??X)(Z.issues.map((K)=>c9(K,W,f8())));throw IA($,G?.callee),$}return Z.value},XH,CV=(X)=>async(Y,Q,J,G)=>{let W=J?Object.assign(J,{async:!0}):{async:!0},Z=Y._zod.run({value:Q,issues:[]},W);if(Z instanceof Promise)Z=await Z;if(Z.issues.length){let $=new(G?.Err??X)(Z.issues.map((K)=>c9(K,W,f8())));throw IA($,G?.callee),$}return Z.value},YH,IV=(X)=>(Y,Q,J)=>{let G=J?{...J,async:!1}:{async:!1},W=Y._zod.run({value:Q,issues:[]},G);if(W instanceof Promise)throw new NG;return W.issues.length?{success:!1,error:new(X??AD)(W.issues.map((Z)=>c9(Z,G,f8())))}:{success:!0,data:W.value}},xZ,RV=(X)=>async(Y,Q,J)=>{let G=J?Object.assign(J,{async:!0}):{async:!0},W=Y._zod.run({value:Q,issues:[]},G);if(W instanceof Promise)W=await W;return W.issues.length?{success:!1,error:new X(W.issues.map((Z)=>c9(Z,G,f8())))}:{success:!0,data:W.value}},gZ,vA=(X)=>(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return jV(X)(Y,Q,G)},_50,_A=(X)=>(Y,Q,J)=>{return jV(X)(Y,Q,J)},y50,yA=(X)=>async(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return CV(X)(Y,Q,G)},b50,bA=(X)=>async(Y,Q,J)=>{return CV(X)(Y,Q,J)},f50,fA=(X)=>(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return IV(X)(Y,Q,G)},h50,hA=(X)=>(Y,Q,J)=>{return IV(X)(Y,Q,J)},x50,xA=(X)=>async(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return RV(X)(Y,Q,G)},g50,gA=(X)=>async(Y,Q,J)=>{return RV(X)(Y,Q,J)},u50;var Gx=S(()=>{wV();Jx();b1();XH=jV(n9),YH=CV(n9),xZ=IV(n9),gZ=RV(n9),_50=vA(n9),y50=_A(n9),b50=yA(n9),f50=bA(n9),h50=fA(n9),x50=hA(n9),g50=xA(n9),u50=gA(n9)});var i9={};c1(i9,{xid:()=>Kx,uuid7:()=>BD1,uuid6:()=>UD1,uuid4:()=>qD1,uuid:()=>QH,uppercase:()=>vx,unicodeEmail:()=>m50,undefined:()=>Sx,ulid:()=>$x,time:()=>Tx,string:()=>Ex,sha512_hex:()=>bD1,sha512_base64url:()=>hD1,sha512_base64:()=>fD1,sha384_hex:()=>vD1,sha384_base64url:()=>yD1,sha384_base64:()=>_D1,sha256_hex:()=>RD1,sha256_base64url:()=>kD1,sha256_base64:()=>SD1,sha1_hex:()=>jD1,sha1_base64url:()=>ID1,sha1_base64:()=>CD1,rfc5322Email:()=>DD1,number:()=>ED,null:()=>Rx,nanoid:()=>Fx,md5_hex:()=>TD1,md5_base64url:()=>ED1,md5_base64:()=>AD1,mac:()=>Nx,lowercase:()=>kx,ksuid:()=>Hx,ipv6:()=>Dx,ipv4:()=>zx,integer:()=>Cx,idnEmail:()=>ND1,html5Email:()=>zD1,hostname:()=>wD1,hex:()=>PD1,guid:()=>qx,extendedDuration:()=>VD1,emoji:()=>Bx,email:()=>Ux,e164:()=>Mx,duration:()=>Vx,domain:()=>MD1,datetime:()=>Ax,date:()=>Px,cuid2:()=>Zx,cuid:()=>Wx,cidrv6:()=>Lx,cidrv4:()=>Ox,browserEmail:()=>OD1,boolean:()=>Ix,bigint:()=>jx,base64url:()=>uA,base64:()=>wx});function Bx(){return new RegExp(LD1,"u")}function d50(X){return typeof X.precision==="number"?X.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":X.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${X.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Tx(X){return new RegExp(`^${d50(X)}$`)}function Ax(X){let Y=d50({precision:X.precision}),Q=["Z"];if(X.local)Q.push("");if(X.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let J=`${Y}(?:${Q.join("|")})`;return new RegExp(`^${l50}T(?:${J})$`)}function jD(X,Y){return new RegExp(`^[A-Za-z0-9+/]{${X}}${Y}$`)}function CD(X){return new RegExp(`^[A-Za-z0-9_-]{${X}}$`)}var Wx,Zx,$x,Kx,Hx,Fx,Vx,VD1,qx,QH=(X)=>{if(!X)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${X}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qD1,UD1,BD1,Ux,zD1,DD1,m50,ND1,OD1,LD1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",zx,Dx,Nx=(X)=>{let Y=VJ(X??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},Ox,Lx,wx,uA,wD1,MD1,Mx,l50="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Px,Ex=(X)=>{let Y=X?`[\\s\\S]{${X?.minimum??0},${X?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},jx,Cx,ED,Ix,Rx,Sx,kx,vx,PD1,TD1,AD1,ED1,jD1,CD1,ID1,RD1,SD1,kD1,vD1,_D1,yD1,bD1,fD1,hD1;var mA=S(()=>{b1();Wx=/^[cC][^\s-]{8,}$/,Zx=/^[0-9a-z]+$/,$x=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Kx=/^[0-9a-vA-V]{20}$/,Hx=/^[A-Za-z0-9]{27}$/,Fx=/^[a-zA-Z0-9_-]{21}$/,Vx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,VD1=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,qx=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qD1=QH(4),UD1=QH(6),BD1=QH(7),Ux=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zD1=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,DD1=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,m50=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,ND1=m50,OD1=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;zx=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Dx=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ox=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Lx=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,uA=/^[A-Za-z0-9_-]*$/,wD1=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,MD1=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Mx=/^\+[1-9]\d{6,14}$/,Px=new RegExp(`^${l50}$`);jx=/^-?\d+n?$/,Cx=/^-?\d+$/,ED=/^-?\d+(?:\.\d+)?$/,Ix=/^(?:true|false)$/i,Rx=/^null$/i,Sx=/^undefined$/i,kx=/^[^A-Z]*$/,vx=/^[^a-z]*$/,PD1=/^[0-9a-fA-F]*$/;TD1=/^[0-9a-fA-F]{32}$/,AD1=jD(22,"=="),ED1=CD(22),jD1=/^[0-9a-fA-F]{40}$/,CD1=jD(27,"="),ID1=CD(27),RD1=/^[0-9a-fA-F]{64}$/,SD1=jD(43,"="),kD1=CD(43),vD1=/^[0-9a-fA-F]{96}$/,_D1=jD(64,""),yD1=CD(64),bD1=/^[0-9a-fA-F]{128}$/,fD1=jD(86,"=="),hD1=CD(86)});function p50(X,Y,Q){if(X.issues.length)Y.issues.push(...SQ(Q,X.issues))}var u4,c50,lA,dA,_x,yx,bx,fx,hx,xx,gx,ux,mx,SV,lx,dx,px,cx,nx,ix,ax,rx,ox;var pA=S(()=>{wV();mA();b1();u4=F0("$ZodCheck",(X,Y)=>{var Q;X._zod??(X._zod={}),X._zod.def=Y,(Q=X._zod).onattach??(Q.onattach=[])}),c50={number:"number",bigint:"bigint",object:"date"},lA=F0("$ZodCheckLessThan",(X,Y)=>{u4.init(X,Y);let Q=c50[typeof Y.value];X._zod.onattach.push((J)=>{let G=J._zod.bag,W=(Y.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Y.value<W)if(Y.inclusive)G.maximum=Y.value;else G.exclusiveMaximum=Y.value}),X._zod.check=(J)=>{if(Y.inclusive?J.value<=Y.value:J.value<Y.value)return;J.issues.push({origin:Q,code:"too_big",maximum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:J.value,inclusive:Y.inclusive,inst:X,continue:!Y.abort})}}),dA=F0("$ZodCheckGreaterThan",(X,Y)=>{u4.init(X,Y);let Q=c50[typeof Y.value];X._zod.onattach.push((J)=>{let G=J._zod.bag,W=(Y.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>W)if(Y.inclusive)G.minimum=Y.value;else G.exclusiveMinimum=Y.value}),X._zod.check=(J)=>{if(Y.inclusive?J.value>=Y.value:J.value>Y.value)return;J.issues.push({origin:Q,code:"too_small",minimum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:J.value,inclusive:Y.inclusive,inst:X,continue:!Y.abort})}}),_x=F0("$ZodCheckMultipleOf",(X,Y)=>{u4.init(X,Y),X._zod.onattach.push((Q)=>{var J;(J=Q._zod.bag).multipleOf??(J.multipleOf=Y.value)}),X._zod.check=(Q)=>{if(typeof Q.value!==typeof Y.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%Y.value===BigInt(0):oh(Q.value,Y.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:Y.value,input:Q.value,inst:X,continue:!Y.abort})}}),yx=F0("$ZodCheckNumberFormat",(X,Y)=>{u4.init(X,Y),Y.format=Y.format||"float64";let Q=Y.format?.includes("int"),J=Q?"int":"number",[G,W]=Yx[Y.format];X._zod.onattach.push((Z)=>{let $=Z._zod.bag;if($.format=Y.format,$.minimum=G,$.maximum=W,Q)$.pattern=Cx}),X._zod.check=(Z)=>{let $=Z.value;if(Q){if(!Number.isInteger($)){Z.issues.push({expected:J,format:Y.format,code:"invalid_type",continue:!1,input:$,inst:X});return}if(!Number.isSafeInteger($)){if($>0)Z.issues.push({input:$,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:X,origin:J,inclusive:!0,continue:!Y.abort});else Z.issues.push({input:$,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:X,origin:J,inclusive:!0,continue:!Y.abort});return}}if($<G)Z.issues.push({origin:"number",input:$,code:"too_small",minimum:G,inclusive:!0,inst:X,continue:!Y.abort});if($>W)Z.issues.push({origin:"number",input:$,code:"too_big",maximum:W,inclusive:!0,inst:X,continue:!Y.abort})}}),bx=F0("$ZodCheckBigIntFormat",(X,Y)=>{u4.init(X,Y);let[Q,J]=Qx[Y.format];X._zod.onattach.push((G)=>{let W=G._zod.bag;W.format=Y.format,W.minimum=Q,W.maximum=J}),X._zod.check=(G)=>{let W=G.value;if(W<Q)G.issues.push({origin:"bigint",input:W,code:"too_small",minimum:Q,inclusive:!0,inst:X,continue:!Y.abort});if(W>J)G.issues.push({origin:"bigint",input:W,code:"too_big",maximum:J,inclusive:!0,inst:X,continue:!Y.abort})}}),fx=F0("$ZodCheckMaxSize",(X,Y)=>{var Q;u4.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!yZ(G)&&G.size!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<G)J._zod.bag.maximum=Y.maximum}),X._zod.check=(J)=>{let G=J.value;if(G.size<=Y.maximum)return;J.issues.push({origin:PD(G),code:"too_big",maximum:Y.maximum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),hx=F0("$ZodCheckMinSize",(X,Y)=>{var Q;u4.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!yZ(G)&&G.size!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>G)J._zod.bag.minimum=Y.minimum}),X._zod.check=(J)=>{let G=J.value;if(G.size>=Y.minimum)return;J.issues.push({origin:PD(G),code:"too_small",minimum:Y.minimum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),xx=F0("$ZodCheckSizeEquals",(X,Y)=>{var Q;u4.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!yZ(G)&&G.size!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.minimum=Y.size,G.maximum=Y.size,G.size=Y.size}),X._zod.check=(J)=>{let G=J.value,W=G.size;if(W===Y.size)return;let Z=W>Y.size;J.issues.push({origin:PD(G),...Z?{code:"too_big",maximum:Y.size}:{code:"too_small",minimum:Y.size},inclusive:!0,exact:!0,input:J.value,inst:X,continue:!Y.abort})}}),gx=F0("$ZodCheckMaxLength",(X,Y)=>{var Q;u4.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!yZ(G)&&G.length!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<G)J._zod.bag.maximum=Y.maximum}),X._zod.check=(J)=>{let G=J.value;if(G.length<=Y.maximum)return;let Z=TD(G);J.issues.push({origin:Z,code:"too_big",maximum:Y.maximum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),ux=F0("$ZodCheckMinLength",(X,Y)=>{var Q;u4.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!yZ(G)&&G.length!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>G)J._zod.bag.minimum=Y.minimum}),X._zod.check=(J)=>{let G=J.value;if(G.length>=Y.minimum)return;let Z=TD(G);J.issues.push({origin:Z,code:"too_small",minimum:Y.minimum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),mx=F0("$ZodCheckLengthEquals",(X,Y)=>{var Q;u4.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!yZ(G)&&G.length!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.minimum=Y.length,G.maximum=Y.length,G.length=Y.length}),X._zod.check=(J)=>{let G=J.value,W=G.length;if(W===Y.length)return;let Z=TD(G),$=W>Y.length;J.issues.push({origin:Z,...$?{code:"too_big",maximum:Y.length}:{code:"too_small",minimum:Y.length},inclusive:!0,exact:!0,input:J.value,inst:X,continue:!Y.abort})}}),SV=F0("$ZodCheckStringFormat",(X,Y)=>{var Q,J;if(u4.init(X,Y),X._zod.onattach.push((G)=>{let W=G._zod.bag;if(W.format=Y.format,Y.pattern)W.patterns??(W.patterns=new Set),W.patterns.add(Y.pattern)}),Y.pattern)(Q=X._zod).check??(Q.check=(G)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:G.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:X,continue:!Y.abort})});else(J=X._zod).check??(J.check=()=>{})}),lx=F0("$ZodCheckRegex",(X,Y)=>{SV.init(X,Y),X._zod.check=(Q)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:Y.pattern.toString(),inst:X,continue:!Y.abort})}}),dx=F0("$ZodCheckLowerCase",(X,Y)=>{Y.pattern??(Y.pattern=kx),SV.init(X,Y)}),px=F0("$ZodCheckUpperCase",(X,Y)=>{Y.pattern??(Y.pattern=vx),SV.init(X,Y)}),cx=F0("$ZodCheckIncludes",(X,Y)=>{u4.init(X,Y);let Q=VJ(Y.includes),J=new RegExp(typeof Y.position==="number"?`^.{${Y.position}}${Q}`:Q);Y.pattern=J,X._zod.onattach.push((G)=>{let W=G._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),X._zod.check=(G)=>{if(G.value.includes(Y.includes,Y.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Y.includes,input:G.value,inst:X,continue:!Y.abort})}}),nx=F0("$ZodCheckStartsWith",(X,Y)=>{u4.init(X,Y);let Q=new RegExp(`^${VJ(Y.prefix)}.*`);Y.pattern??(Y.pattern=Q),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),X._zod.check=(J)=>{if(J.value.startsWith(Y.prefix))return;J.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Y.prefix,input:J.value,inst:X,continue:!Y.abort})}}),ix=F0("$ZodCheckEndsWith",(X,Y)=>{u4.init(X,Y);let Q=new RegExp(`.*${VJ(Y.suffix)}$`);Y.pattern??(Y.pattern=Q),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),X._zod.check=(J)=>{if(J.value.endsWith(Y.suffix))return;J.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Y.suffix,input:J.value,inst:X,continue:!Y.abort})}});ax=F0("$ZodCheckProperty",(X,Y)=>{u4.init(X,Y),X._zod.check=(Q)=>{let J=Y.schema._zod.run({value:Q.value[Y.property],issues:[]},{});if(J instanceof Promise)return J.then((G)=>p50(G,Q,Y.property));p50(J,Q,Y.property);return}}),rx=F0("$ZodCheckMimeType",(X,Y)=>{u4.init(X,Y);let Q=new Set(Y.mime);X._zod.onattach.push((J)=>{J._zod.bag.mime=Y.mime}),X._zod.check=(J)=>{if(Q.has(J.value.type))return;J.issues.push({code:"invalid_value",values:Y.mime,input:J.value.type,inst:X,continue:!Y.abort})}}),ox=F0("$ZodCheckOverwrite",(X,Y)=>{u4.init(X,Y),X._zod.check=(Q)=>{Q.value=Y.tx(Q.value)}})});class cA{constructor(X=[]){if(this.content=[],this.indent=0,this)this.args=X}indented(X){this.indent+=1,X(this),this.indent-=1}write(X){if(typeof X==="function"){X(this,{execution:"sync"}),X(this,{execution:"async"});return}let Q=X.split(`
5
5
  `).filter((W)=>W),J=Math.min(...Q.map((W)=>W.length-W.trimStart().length)),G=Q.map((W)=>W.slice(J)).map((W)=>" ".repeat(this.indent*2)+W);for(let W of G)this.content.push(W)}compile(){let X=Function,Y=this?.args,J=[...(this?.content??[""]).map((G)=>` ${G}`)];return new X(...Y,J.join(`
6
6
  `))}}var sx;var tx=S(()=>{sx={major:4,minor:3,patch:6}});function Gg(X){if(X==="")return!0;if(X.length%4!==0)return!1;try{return atob(X),!0}catch{return!1}}function GG0(X){if(!uA.test(X))return!1;let Y=X.replace(/[-_]/g,(J)=>J==="-"?"+":"/"),Q=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return Gg(Q)}function WG0(X,Y=null){try{let Q=X.split(".");if(Q.length!==3)return!1;let[J]=Q;if(!J)return!1;let G=JSON.parse(atob(J));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(Y&&(!("alg"in G)||G.alg!==Y))return!1;return!0}catch{return!1}}function i50(X,Y,Q){if(X.issues.length)Y.issues.push(...SQ(Q,X.issues));Y.value[Q]=X.value}function oA(X,Y,Q,J,G){if(X.issues.length){if(G&&!(Q in J))return;Y.issues.push(...SQ(Q,X.issues))}if(X.value===void 0){if(Q in J)Y.value[Q]=void 0}else Y.value[Q]=X.value}function ZG0(X){let Y=Object.keys(X.shape);for(let J of Y)if(!X.shape?.[J]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${J}": expected a Zod schema`);let Q=Xx(X.shape);return{...X,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(Q)}}function $G0(X,Y,Q,J,G,W){let Z=[],$=G.keySet,K=G.catchall._zod,H=K.def.type,F=K.optout==="optional";for(let V in Y){if($.has(V))continue;if(H==="never"){Z.push(V);continue}let q=K.run({value:Y[V],issues:[]},J);if(q instanceof Promise)X.push(q.then((B)=>oA(B,Q,V,Y,F)));else oA(q,Q,V,Y,F)}if(Z.length)Q.issues.push({code:"unrecognized_keys",keys:Z,input:Y,inst:W});if(!X.length)return Q;return Promise.all(X).then(()=>{return Q})}function a50(X,Y,Q,J){for(let W of X)if(W.issues.length===0)return Y.value=W.value,Y;let G=X.filter((W)=>!hZ(W));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:Q,errors:X.map((W)=>W.issues.map((Z)=>c9(Z,J,f8())))}),Y}function r50(X,Y,Q,J){let G=X.filter((W)=>W.issues.length===0);if(G.length===1)return Y.value=G[0].value,Y;if(G.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:Q,errors:X.map((W)=>W.issues.map((Z)=>c9(Z,J,f8())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:Q,errors:[],inclusive:!1});return Y}function ex(X,Y){if(X===Y)return{valid:!0,data:X};if(X instanceof Date&&Y instanceof Date&&+X===+Y)return{valid:!0,data:X};if(fZ(X)&&fZ(Y)){let Q=Object.keys(Y),J=Object.keys(X).filter((W)=>Q.indexOf(W)!==-1),G={...X,...Y};for(let W of J){let Z=ex(X[W],Y[W]);if(!Z.valid)return{valid:!1,mergeErrorPath:[W,...Z.mergeErrorPath]};G[W]=Z.data}return{valid:!0,data:G}}if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let J=0;J<X.length;J++){let G=X[J],W=Y[J],Z=ex(G,W);if(!Z.valid)return{valid:!1,mergeErrorPath:[J,...Z.mergeErrorPath]};Q.push(Z.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function o50(X,Y,Q){let J=new Map,G;for(let $ of Y.issues)if($.code==="unrecognized_keys"){G??(G=$);for(let K of $.keys){if(!J.has(K))J.set(K,{});J.get(K).l=!0}}else X.issues.push($);for(let $ of Q.issues)if($.code==="unrecognized_keys")for(let K of $.keys){if(!J.has(K))J.set(K,{});J.get(K).r=!0}else X.issues.push($);let W=[...J].filter(([,$])=>$.l&&$.r).map(([$])=>$);if(W.length&&G)X.issues.push({...G,keys:W});if(hZ(X))return X;let Z=ex(Y.value,Q.value);if(!Z.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Z.mergeErrorPath)}`);return X.value=Z.data,X}function nA(X,Y,Q){if(X.issues.length)Y.issues.push(...SQ(Q,X.issues));Y.value[Q]=X.value}function s50(X,Y,Q,J,G,W,Z){if(X.issues.length)if(MD.has(typeof J))Q.issues.push(...SQ(J,X.issues));else Q.issues.push({code:"invalid_key",origin:"map",input:G,inst:W,issues:X.issues.map(($)=>c9($,Z,f8()))});if(Y.issues.length)if(MD.has(typeof J))Q.issues.push(...SQ(J,Y.issues));else Q.issues.push({origin:"map",code:"invalid_element",input:G,inst:W,key:J,issues:Y.issues.map(($)=>c9($,Z,f8()))});Q.value.set(X.value,Y.value)}function t50(X,Y){if(X.issues.length)Y.issues.push(...X.issues);Y.value.add(X.value)}function e50(X,Y){if(X.issues.length&&Y===void 0)return{issues:[],value:void 0};return X}function XG0(X,Y){if(X.value===void 0)X.value=Y.defaultValue;return X}function YG0(X,Y){if(!X.issues.length&&X.value===void 0)X.issues.push({code:"invalid_type",expected:"nonoptional",input:X.value,inst:Y});return X}function iA(X,Y,Q){if(X.issues.length)return X.aborted=!0,X;return Y._zod.run({value:X.value,issues:X.issues},Q)}function aA(X,Y,Q){if(X.issues.length)return X.aborted=!0,X;if((Q.direction||"forward")==="forward"){let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then((W)=>rA(X,W,Y.out,Q));return rA(X,G,Y.out,Q)}else{let G=Y.reverseTransform(X.value,X);if(G instanceof Promise)return G.then((W)=>rA(X,W,Y.in,Q));return rA(X,G,Y.in,Q)}}function rA(X,Y,Q,J){if(X.issues.length)return X.aborted=!0,X;return Q._zod.run({value:Y,issues:X.issues},J)}function QG0(X){return X.value=Object.freeze(X.value),X}function JG0(X,Y,Q,J){if(!X){let G={code:"custom",input:Q,inst:J,path:[...J._zod.def.path??[]],continue:!J._zod.def.abort};if(J._zod.def.params)G.params=J._zod.def.params;Y.issues.push(TV(G))}}var W6,uZ,_4,sA,tA,eA,XE,YE,QE,JE,GE,WE,ZE,$E,Xg,Yg,Qg,Jg,KE,HE,FE,VE,qE,UE,BE,zE,DE,NE,ID,OE,kV,RD,LE,wE,ME,PE,TE,AE,EE,jE,CE,IE,RE,Wg,vV,SE,kE,vE,SD,_E,yE,bE,fE,hE,xE,gE,kD,uE,mE,lE,dE,pE,cE,nE,iE,aE,_V,rE,oE,sE,tE,eE,Xj;var Zg=S(()=>{pA();wV();Gx();mA();b1();tx();b1();W6=F0("$ZodType",(X,Y)=>{var Q;X??(X={}),X._zod.def=Y,X._zod.bag=X._zod.bag||{},X._zod.version=sx;let J=[...X._zod.def.checks??[]];if(X._zod.traits.has("$ZodCheck"))J.unshift(X);for(let G of J)for(let W of G._zod.onattach)W(X);if(J.length===0)(Q=X._zod).deferred??(Q.deferred=[]),X._zod.deferred?.push(()=>{X._zod.run=X._zod.parse});else{let G=(Z,$,K)=>{let H=hZ(Z),F;for(let V of $){if(V._zod.def.when){if(!V._zod.def.when(Z))continue}else if(H)continue;let q=Z.issues.length,B=V._zod.check(Z);if(B instanceof Promise&&K?.async===!1)throw new NG;if(F||B instanceof Promise)F=(F??Promise.resolve()).then(async()=>{if(await B,Z.issues.length===q)return;if(!H)H=hZ(Z,q)});else{if(Z.issues.length===q)continue;if(!H)H=hZ(Z,q)}}if(F)return F.then(()=>{return Z});return Z},W=(Z,$,K)=>{if(hZ(Z))return Z.aborted=!0,Z;let H=G($,J,K);if(H instanceof Promise){if(K.async===!1)throw new NG;return H.then((F)=>X._zod.parse(F,K))}return X._zod.parse(H,K)};X._zod.run=(Z,$)=>{if($.skipChecks)return X._zod.parse(Z,$);if($.direction==="backward"){let H=X._zod.parse({value:Z.value,issues:[]},{...$,skipChecks:!0});if(H instanceof Promise)return H.then((F)=>{return W(F,Z,$)});return W(H,Z,$)}let K=X._zod.parse(Z,$);if(K instanceof Promise){if($.async===!1)throw new NG;return K.then((H)=>G(H,J,$))}return G(K,J,$)}}D6(X,"~standard",()=>({validate:(G)=>{try{let W=xZ(X,G);return W.success?{value:W.data}:{issues:W.error?.issues}}catch(W){return gZ(X,G).then((Z)=>Z.success?{value:Z.data}:{issues:Z.error?.issues})}},vendor:"zod",version:1}))}),uZ=F0("$ZodString",(X,Y)=>{W6.init(X,Y),X._zod.pattern=[...X?._zod.bag?.patterns??[]].pop()??Ex(X._zod.bag),X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=String(Q.value)}catch(G){}if(typeof Q.value==="string")return Q;return Q.issues.push({expected:"string",code:"invalid_type",input:Q.value,inst:X}),Q}}),_4=F0("$ZodStringFormat",(X,Y)=>{SV.init(X,Y),uZ.init(X,Y)}),sA=F0("$ZodGUID",(X,Y)=>{Y.pattern??(Y.pattern=qx),_4.init(X,Y)}),tA=F0("$ZodUUID",(X,Y)=>{if(Y.version){let J={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[Y.version];if(J===void 0)throw Error(`Invalid UUID version: "${Y.version}"`);Y.pattern??(Y.pattern=QH(J))}else Y.pattern??(Y.pattern=QH());_4.init(X,Y)}),eA=F0("$ZodEmail",(X,Y)=>{Y.pattern??(Y.pattern=Ux),_4.init(X,Y)}),XE=F0("$ZodURL",(X,Y)=>{_4.init(X,Y),X._zod.check=(Q)=>{try{let J=Q.value.trim(),G=new URL(J);if(Y.hostname){if(Y.hostname.lastIndex=0,!Y.hostname.test(G.hostname))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y.hostname.source,input:Q.value,inst:X,continue:!Y.abort})}if(Y.protocol){if(Y.protocol.lastIndex=0,!Y.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Y.protocol.source,input:Q.value,inst:X,continue:!Y.abort})}if(Y.normalize)Q.value=G.href;else Q.value=J;return}catch(J){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:X,continue:!Y.abort})}}}),YE=F0("$ZodEmoji",(X,Y)=>{Y.pattern??(Y.pattern=Bx()),_4.init(X,Y)}),QE=F0("$ZodNanoID",(X,Y)=>{Y.pattern??(Y.pattern=Fx),_4.init(X,Y)}),JE=F0("$ZodCUID",(X,Y)=>{Y.pattern??(Y.pattern=Wx),_4.init(X,Y)}),GE=F0("$ZodCUID2",(X,Y)=>{Y.pattern??(Y.pattern=Zx),_4.init(X,Y)}),WE=F0("$ZodULID",(X,Y)=>{Y.pattern??(Y.pattern=$x),_4.init(X,Y)}),ZE=F0("$ZodXID",(X,Y)=>{Y.pattern??(Y.pattern=Kx),_4.init(X,Y)}),$E=F0("$ZodKSUID",(X,Y)=>{Y.pattern??(Y.pattern=Hx),_4.init(X,Y)}),Xg=F0("$ZodISODateTime",(X,Y)=>{Y.pattern??(Y.pattern=Ax(Y)),_4.init(X,Y)}),Yg=F0("$ZodISODate",(X,Y)=>{Y.pattern??(Y.pattern=Px),_4.init(X,Y)}),Qg=F0("$ZodISOTime",(X,Y)=>{Y.pattern??(Y.pattern=Tx(Y)),_4.init(X,Y)}),Jg=F0("$ZodISODuration",(X,Y)=>{Y.pattern??(Y.pattern=Vx),_4.init(X,Y)}),KE=F0("$ZodIPv4",(X,Y)=>{Y.pattern??(Y.pattern=zx),_4.init(X,Y),X._zod.bag.format="ipv4"}),HE=F0("$ZodIPv6",(X,Y)=>{Y.pattern??(Y.pattern=Dx),_4.init(X,Y),X._zod.bag.format="ipv6",X._zod.check=(Q)=>{try{new URL(`http://[${Q.value}]`)}catch{Q.issues.push({code:"invalid_format",format:"ipv6",input:Q.value,inst:X,continue:!Y.abort})}}}),FE=F0("$ZodMAC",(X,Y)=>{Y.pattern??(Y.pattern=Nx(Y.delimiter)),_4.init(X,Y),X._zod.bag.format="mac"}),VE=F0("$ZodCIDRv4",(X,Y)=>{Y.pattern??(Y.pattern=Ox),_4.init(X,Y)}),qE=F0("$ZodCIDRv6",(X,Y)=>{Y.pattern??(Y.pattern=Lx),_4.init(X,Y),X._zod.check=(Q)=>{let J=Q.value.split("/");try{if(J.length!==2)throw Error();let[G,W]=J;if(!W)throw Error();let Z=Number(W);if(`${Z}`!==W)throw Error();if(Z<0||Z>128)throw Error();new URL(`http://[${G}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:X,continue:!Y.abort})}}});UE=F0("$ZodBase64",(X,Y)=>{Y.pattern??(Y.pattern=wx),_4.init(X,Y),X._zod.bag.contentEncoding="base64",X._zod.check=(Q)=>{if(Gg(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:X,continue:!Y.abort})}});BE=F0("$ZodBase64URL",(X,Y)=>{Y.pattern??(Y.pattern=uA),_4.init(X,Y),X._zod.bag.contentEncoding="base64url",X._zod.check=(Q)=>{if(GG0(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:X,continue:!Y.abort})}}),zE=F0("$ZodE164",(X,Y)=>{Y.pattern??(Y.pattern=Mx),_4.init(X,Y)});DE=F0("$ZodJWT",(X,Y)=>{_4.init(X,Y),X._zod.check=(Q)=>{if(WG0(Q.value,Y.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:X,continue:!Y.abort})}}),NE=F0("$ZodCustomStringFormat",(X,Y)=>{_4.init(X,Y),X._zod.check=(Q)=>{if(Y.fn(Q.value))return;Q.issues.push({code:"invalid_format",format:Y.format,input:Q.value,inst:X,continue:!Y.abort})}}),ID=F0("$ZodNumber",(X,Y)=>{W6.init(X,Y),X._zod.pattern=X._zod.bag.pattern??ED,X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=Number(Q.value)}catch(Z){}let G=Q.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return Q;let W=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return Q.issues.push({expected:"number",code:"invalid_type",input:G,inst:X,...W?{received:W}:{}}),Q}}),OE=F0("$ZodNumberFormat",(X,Y)=>{yx.init(X,Y),ID.init(X,Y)}),kV=F0("$ZodBoolean",(X,Y)=>{W6.init(X,Y),X._zod.pattern=Ix,X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=Boolean(Q.value)}catch(W){}let G=Q.value;if(typeof G==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:X}),Q}}),RD=F0("$ZodBigInt",(X,Y)=>{W6.init(X,Y),X._zod.pattern=jx,X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=BigInt(Q.value)}catch(G){}if(typeof Q.value==="bigint")return Q;return Q.issues.push({expected:"bigint",code:"invalid_type",input:Q.value,inst:X}),Q}}),LE=F0("$ZodBigIntFormat",(X,Y)=>{bx.init(X,Y),RD.init(X,Y)}),wE=F0("$ZodSymbol",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q,J)=>{let G=Q.value;if(typeof G==="symbol")return Q;return Q.issues.push({expected:"symbol",code:"invalid_type",input:G,inst:X}),Q}}),ME=F0("$ZodUndefined",(X,Y)=>{W6.init(X,Y),X._zod.pattern=Sx,X._zod.values=new Set([void 0]),X._zod.optin="optional",X._zod.optout="optional",X._zod.parse=(Q,J)=>{let G=Q.value;if(typeof G>"u")return Q;return Q.issues.push({expected:"undefined",code:"invalid_type",input:G,inst:X}),Q}}),PE=F0("$ZodNull",(X,Y)=>{W6.init(X,Y),X._zod.pattern=Rx,X._zod.values=new Set([null]),X._zod.parse=(Q,J)=>{let G=Q.value;if(G===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:G,inst:X}),Q}}),TE=F0("$ZodAny",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q)=>Q}),AE=F0("$ZodUnknown",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q)=>Q}),EE=F0("$ZodNever",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q,J)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:X}),Q}}),jE=F0("$ZodVoid",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q,J)=>{let G=Q.value;if(typeof G>"u")return Q;return Q.issues.push({expected:"void",code:"invalid_type",input:G,inst:X}),Q}}),CE=F0("$ZodDate",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=new Date(Q.value)}catch($){}let G=Q.value,W=G instanceof Date;if(W&&!Number.isNaN(G.getTime()))return Q;return Q.issues.push({expected:"date",code:"invalid_type",input:G,...W?{received:"Invalid Date"}:{},inst:X}),Q}});IE=F0("$ZodArray",(X,Y)=>{W6.init(X,Y),X._zod.parse=(Q,J)=>{let G=Q.value;if(!Array.isArray(G))return Q.issues.push({expected:"array",code:"invalid_type",input:G,inst:X}),Q;Q.value=Array(G.length);let W=[];for(let Z=0;Z<G.length;Z++){let $=G[Z],K=Y.element._zod.run({value:$,issues:[]},J);if(K instanceof Promise)W.push(K.then((H)=>i50(H,Q,Z)));else i50(K,Q,Z)}if(W.length)return Promise.all(W).then(()=>Q);return Q}});RE=F0("$ZodObject",(X,Y)=>{if(W6.init(X,Y),!Object.getOwnPropertyDescriptor(Y,"shape")?.get){let $=Y.shape;Object.defineProperty(Y,"shape",{get:()=>{let K={...$};return Object.defineProperty(Y,"shape",{value:K}),K}})}let J=PV(()=>ZG0(Y));D6(X._zod,"propValues",()=>{let $=Y.shape,K={};for(let H in $){let F=$[H]._zod;if(F.values){K[H]??(K[H]=new Set);for(let V of F.values)K[H].add(V)}}return K});let G=eK,W=Y.catchall,Z;X._zod.parse=($,K)=>{Z??(Z=J.value);let H=$.value;if(!G(H))return $.issues.push({expected:"object",code:"invalid_type",input:H,inst:X}),$;$.value={};let F=[],V=Z.shape;for(let q of Z.keys){let B=V[q],D=B._zod.optout==="optional",N=B._zod.run({value:H[q],issues:[]},K);if(N instanceof Promise)F.push(N.then((L)=>oA(L,$,q,H,D)));else oA(N,$,q,H,D)}if(!W)return F.length?Promise.all(F).then(()=>$):$;return $G0(F,H,$,K,J.value,X)}}),Wg=F0("$ZodObjectJIT",(X,Y)=>{RE.init(X,Y);let Q=X._zod.parse,J=PV(()=>ZG0(Y)),G=(q)=>{let B=new cA(["shape","payload","ctx"]),D=J.value,N=(T)=>{let A=CA(T);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};B.write("const input = payload.value;");let L=Object.create(null),w=0;for(let T of D.keys)L[T]=`key_${w++}`;B.write("const newResult = {};");for(let T of D.keys){let A=L[T],P=CA(T),R=q[T]?._zod?.optout==="optional";if(B.write(`const ${A} = ${N(T)};`),R)B.write(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var VJ4=Object.create;var{getPrototypeOf:qJ4,defineProperty:T_,getOwnPropertyNames:UJ4}=Object;var zJ4=Object.prototype.hasOwnProperty;var U1=(X,Y,Q)=>{Q=X!=null?VJ4(qJ4(X)):{};let J=Y||!X||!X.__esModule?T_(Q,"default",{value:X,enumerable:!0}):Q;for(let G of UJ4(X))if(!zJ4.call(J,G))T_(J,G,{get:()=>X[G],enumerable:!0});return J};var j=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var h4=(X,Y)=>{for(var Q in Y)T_(X,Q,{get:Y[Q],enumerable:!0,configurable:!0,set:(J)=>Y[Q]=()=>J})};var g=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var U0=import.meta.require,A_=(X,Y,Q)=>{if(Y!=null){if(typeof Y!=="object"&&typeof Y!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let J;if(Q)J=Y[Symbol.asyncDispose];if(J===void 0)J=Y[Symbol.dispose];if(typeof J!=="function")throw TypeError("Object not disposable");X.push([Q,J,Y])}else if(Q)X.push([Q]);return Y},x10=(X,Y,Q)=>{let J=(Z)=>Y=Q?new SuppressedError(Z,Y,"An error was suppressed during disposal"):(Q=!0,Z),G=(Z)=>{while(Z=X.pop())try{var W=Z[1]&&Z[1].call(Z[2]);if(Z[0])return Promise.resolve(W).then(G,($)=>(J($),G()))}catch($){J($)}if(Q)throw Y};return G()};var KM="user-sandbox",g10="Create embeddable integration flows for platform end-users";import{sql as uU}from"kysely";var u10;var m10=g(()=>{u10={name:"001-user-sandbox",async up(X){await X.schema.createTable("user_sandbox").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Y)=>Y.notNull()).addColumn("description","text").addColumn("icon","text").addColumn("required_apps","text",(Y)=>Y.notNull()).addColumn("redirect_url","text").addColumn("webhook_url","text").addColumn("event_type","text",(Y)=>Y.notNull().defaultTo("integration.completed")).addColumn("agent_title_template","text",(Y)=>Y.notNull().defaultTo("Agent for {{externalUserId}}")).addColumn("agent_instructions","text").addColumn("tool_selection_mode","text",(Y)=>Y.notNull().defaultTo("inclusion")).addColumn("status","text",(Y)=>Y.notNull().defaultTo("active")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Y)=>Y.references("user.id").onDelete("set null")).execute(),await X.schema.createIndex("idx_user_sandbox_org").on("user_sandbox").column("organization_id").execute(),await X.schema.createTable("user_sandbox_sessions").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("template_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("status","text",(Y)=>Y.notNull().defaultTo("pending")).addColumn("app_statuses","text",(Y)=>Y.notNull().defaultTo("{}")).addColumn("created_agent_id","text",(Y)=>Y.references("connections.id").onDelete("set null")).addColumn("redirect_url","text").addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("expires_at","text",(Y)=>Y.notNull()).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_template").on("user_sandbox_sessions").column("template_id").execute(),await X.schema.createIndex("idx_user_sandbox_sessions_external_user").on("user_sandbox_sessions").columns(["template_id","external_user_id"]).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_org").on("user_sandbox_sessions").column("organization_id").execute(),await X.schema.createTable("user_sandbox_agents").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("user_sandbox_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("connection_id","text",(Y)=>Y.notNull().references("connections.id").onDelete("cascade")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).execute(),await X.schema.createIndex("idx_user_sandbox_agents_unique").on("user_sandbox_agents").columns(["user_sandbox_id","external_user_id"]).unique().execute(),await X.schema.createIndex("idx_user_sandbox_agents_connection").on("user_sandbox_agents").column("connection_id").execute()},async down(X){await X.schema.dropIndex("idx_user_sandbox_agents_connection").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_agents_unique").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_org").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_external_user").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_template").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_org").ifExists().execute(),await X.schema.dropTable("user_sandbox_agents").ifExists().execute(),await X.schema.dropTable("user_sandbox_sessions").ifExists().execute(),await X.schema.dropTable("user_sandbox").ifExists().execute()}}});var l10;var d10=g(()=>{m10();l10=[u10]});function HM(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}class mU{db;constructor(X){this.db=X}async create(X){let Y=HM("usb"),Q=new Date().toISOString(),J={id:Y,organization_id:X.organization_id,title:X.title,description:X.description??null,icon:X.icon??null,required_apps:JSON.stringify(X.required_apps),redirect_url:X.redirect_url??null,webhook_url:X.webhook_url??null,event_type:X.event_type??"integration.completed",agent_title_template:X.agent_title_template??"{{externalUserId}}'s Agent",agent_instructions:X.agent_instructions??null,tool_selection_mode:X.tool_selection_mode??"inclusion",status:"active",created_at:Q,updated_at:Q,created_by:X.created_by??null};await this.db.insertInto("user_sandbox").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create user sandbox with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async list(X){return(await this.db.selectFrom("user_sandbox").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.icon!==void 0)J.icon=Y.icon;if(Y.required_apps!==void 0)J.required_apps=JSON.stringify(Y.required_apps);if(Y.redirect_url!==void 0)J.redirect_url=Y.redirect_url;if(Y.webhook_url!==void 0)J.webhook_url=Y.webhook_url;if(Y.event_type!==void 0)J.event_type=Y.event_type;if(Y.agent_title_template!==void 0)J.agent_title_template=Y.agent_title_template;if(Y.agent_instructions!==void 0)J.agent_instructions=Y.agent_instructions;if(Y.tool_selection_mode!==void 0)J.tool_selection_mode=Y.tool_selection_mode;if(Y.status!==void 0)J.status=Y.status;await this.db.updateTable("user_sandbox").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Template not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox").where("id","=",X).execute()}deserialize(X){let Y=[];try{Y=JSON.parse(X.required_apps)}catch{Y=[]}return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,icon:X.icon,required_apps:Y,redirect_url:X.redirect_url,webhook_url:X.webhook_url,event_type:X.event_type,agent_title_template:X.agent_title_template,agent_instructions:X.agent_instructions,tool_selection_mode:X.tool_selection_mode,status:X.status,created_at:X.created_at,updated_at:X.updated_at,created_by:X.created_by}}}var E_=()=>{};class lU{db;constructor(X){this.db=X}async create(X){let Y=HM("uss"),Q=new Date().toISOString(),J={id:Y,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:"pending",app_statuses:"{}",created_agent_id:X.created_agent_id??null,redirect_url:X.redirect_url??null,created_at:Q,updated_at:Q,expires_at:X.expires_at};await this.db.insertInto("user_sandbox_sessions").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create session with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async findExisting(X,Y){let Q=new Date().toISOString(),J=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).where("external_user_id","=",Y).where("expires_at",">",Q).where("status","!=","completed").orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return this.deserialize(J)}async listByTemplate(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async listByOrganization(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.status!==void 0)J.status=Y.status;if(Y.app_statuses!==void 0)J.app_statuses=JSON.stringify(Y.app_statuses);if(Y.created_agent_id!==void 0)J.created_agent_id=Y.created_agent_id;await this.db.updateTable("user_sandbox_sessions").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Session not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox_sessions").where("id","=",X).execute()}async deleteExpired(){let X=new Date().toISOString(),Y=await this.db.deleteFrom("user_sandbox_sessions").where("expires_at","<",X).where("status","!=","completed").executeTakeFirst();return Number(Y.numDeletedRows??0)}deserialize(X){let Y={};try{Y=JSON.parse(X.app_statuses)}catch{Y={}}return{id:X.id,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:X.status,app_statuses:Y,created_agent_id:X.created_agent_id,redirect_url:X.redirect_url,created_at:X.created_at,updated_at:X.updated_at,expires_at:X.expires_at}}}var j_=()=>{};function dU(X){C_=X}function JY(){if(!C_)throw Error(`Plugin storage not initialized. Make sure the "${KM}" plugin is enabled.`);return C_}function I_(){return process.env.MESH_PUBLIC_URL||"http://localhost:3000"}var C_=null;var z5=()=>{};function p10(X){let Y=X.db,Q={templates:new mU(Y),sessions:new lU(Y)};return dU(Q),Q}var c10=g(()=>{E_();j_();z5()});function H0(X,Y,Q){function J($,K){if(!$._zod)Object.defineProperty($,"_zod",{value:{def:K,constr:W,traits:new Set},enumerable:!1});if($._zod.traits.has(X))return;$._zod.traits.add(X),Y($,K);let H=W.prototype,F=Object.keys(H);for(let V=0;V<F.length;V++){let q=F[V];if(!(q in $))$[q]=H[q].bind($)}}let G=Q?.Parent??Object;class Z extends G{}Object.defineProperty(Z,"name",{value:X});function W($){var K;let H=Q?.Parent?new Z:this;J(H,$),(K=H._zod).deferred??(K.deferred=[]);for(let F of H._zod.deferred)F();return H}return Object.defineProperty(W,"init",{value:J}),Object.defineProperty(W,Symbol.hasInstance,{value:($)=>{if(Q?.Parent&&$ instanceof Q.Parent)return!0;return $?._zod?.traits?.has(X)}}),Object.defineProperty(W,"name",{value:X}),W}function L8(X){if(X)Object.assign(pU,X);return pU}var qH,FM,B5,O$,pU;var UH=g(()=>{qH=Object.freeze({status:"aborted"});FM=Symbol("zod_brand");B5=class B5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};O$=class O$ extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}};pU={}});var p0={};h4(p0,{unwrapMessage:()=>cU,uint8ArrayToHex:()=>_J4,uint8ArrayToBase64url:()=>vJ4,uint8ArrayToBase64:()=>X80,stringifyPrimitive:()=>l0,slugify:()=>v_,shallowClone:()=>UM,safeExtend:()=>o10,required:()=>t10,randomString:()=>AJ4,propertyKeyTypes:()=>aU,promiseAllObject:()=>TJ4,primitiveTypes:()=>__,prefixIssues:()=>gY,pick:()=>i10,partial:()=>s10,parsedType:()=>n0,optionalKeys:()=>y_,omit:()=>a10,objectClone:()=>wJ4,numKeys:()=>EJ4,nullish:()=>FW,normalizeParams:()=>i0,mergeDefs:()=>bG,merge:()=>IJ4,jsonStringifyReplacer:()=>zH,joinValues:()=>M0,issue:()=>DH,isPlainObject:()=>qW,isObject:()=>L$,hexToUint8Array:()=>kJ4,getSizableOrigin:()=>rU,getParsedType:()=>jJ4,getLengthableOrigin:()=>oU,getEnumValues:()=>nU,getElementAtPath:()=>PJ4,floatSafeRemainder:()=>S_,finalizeIssue:()=>GY,extend:()=>r10,escapeRegex:()=>NQ,esc:()=>VM,defineLazy:()=>$6,createTransparentProxy:()=>CJ4,cloneDef:()=>MJ4,clone:()=>J9,cleanRegex:()=>iU,cleanEnum:()=>RJ4,captureStackTrace:()=>qM,cached:()=>BH,base64urlToUint8Array:()=>SJ4,base64ToUint8Array:()=>e10,assignProp:()=>VW,assertNotEqual:()=>DJ4,assertNever:()=>OJ4,assertIs:()=>NJ4,assertEqual:()=>BJ4,assert:()=>LJ4,allowsEval:()=>k_,aborted:()=>UW,NUMBER_FORMAT_RANGES:()=>f_,Class:()=>Y80,BIGINT_FORMAT_RANGES:()=>b_});function BJ4(X){return X}function DJ4(X){return X}function NJ4(X){}function OJ4(X){throw Error("Unexpected value in exhaustive check")}function LJ4(X){}function nU(X){let Y=Object.values(X).filter((J)=>typeof J==="number");return Object.entries(X).filter(([J,G])=>Y.indexOf(+J)===-1).map(([J,G])=>G)}function M0(X,Y="|"){return X.map((Q)=>l0(Q)).join(Y)}function zH(X,Y){if(typeof Y==="bigint")return Y.toString();return Y}function BH(X){return{get value(){{let Q=X();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function FW(X){return X===null||X===void 0}function iU(X){let Y=X.startsWith("^")?1:0,Q=X.endsWith("$")?X.length-1:X.length;return X.slice(Y,Q)}function S_(X,Y){let Q=(X.toString().split(".")[1]||"").length,J=Y.toString(),G=(J.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(J)){let K=J.match(/\d?e-(\d?)/);if(K?.[1])G=Number.parseInt(K[1])}let Z=Q>G?Q:G,W=Number.parseInt(X.toFixed(Z).replace(".","")),$=Number.parseInt(Y.toFixed(Z).replace(".",""));return W%$/10**Z}function $6(X,Y,Q){let J=void 0;Object.defineProperty(X,Y,{get(){if(J===n10)return;if(J===void 0)J=n10,J=Q();return J},set(G){Object.defineProperty(X,Y,{value:G})},configurable:!0})}function wJ4(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function VW(X,Y,Q){Object.defineProperty(X,Y,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function bG(...X){let Y={};for(let Q of X){let J=Object.getOwnPropertyDescriptors(Q);Object.assign(Y,J)}return Object.defineProperties({},Y)}function MJ4(X){return bG(X._zod.def)}function PJ4(X,Y){if(!Y)return X;return Y.reduce((Q,J)=>Q?.[J],X)}function TJ4(X){let Y=Object.keys(X),Q=Y.map((J)=>X[J]);return Promise.all(Q).then((J)=>{let G={};for(let Z=0;Z<Y.length;Z++)G[Y[Z]]=J[Z];return G})}function AJ4(X=10){let Q="";for(let J=0;J<X;J++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function VM(X){return JSON.stringify(X)}function v_(X){return X.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function L$(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function qW(X){if(L$(X)===!1)return!1;let Y=X.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let Q=Y.prototype;if(L$(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function UM(X){if(qW(X))return{...X};if(Array.isArray(X))return[...X];return X}function EJ4(X){let Y=0;for(let Q in X)if(Object.prototype.hasOwnProperty.call(X,Q))Y++;return Y}function NQ(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J9(X,Y,Q){let J=new X._zod.constr(Y??X._zod.def);if(!Y||Q?.parent)J._zod.parent=X;return J}function i0(X){let Y=X;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function CJ4(X){let Y;return new Proxy({},{get(Q,J,G){return Y??(Y=X()),Reflect.get(Y,J,G)},set(Q,J,G,Z){return Y??(Y=X()),Reflect.set(Y,J,G,Z)},has(Q,J){return Y??(Y=X()),Reflect.has(Y,J)},deleteProperty(Q,J){return Y??(Y=X()),Reflect.deleteProperty(Y,J)},ownKeys(Q){return Y??(Y=X()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(Q,J){return Y??(Y=X()),Reflect.getOwnPropertyDescriptor(Y,J)},defineProperty(Q,J,G){return Y??(Y=X()),Reflect.defineProperty(Y,J,G)}})}function l0(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function y_(X){return Object.keys(X).filter((Y)=>{return X[Y]._zod.optin==="optional"&&X[Y]._zod.optout==="optional"})}function i10(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let Z=bG(X._zod.def,{get shape(){let W={};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;W[$]=Q.shape[$]}return VW(this,"shape",W),W},checks:[]});return J9(X,Z)}function a10(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let Z=bG(X._zod.def,{get shape(){let W={...X._zod.def.shape};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete W[$]}return VW(this,"shape",W),W},checks:[]});return J9(X,Z)}function r10(X,Y){if(!qW(Y))throw Error("Invalid input to extend: expected a plain object");let Q=X._zod.def.checks;if(Q&&Q.length>0){let Z=X._zod.def.shape;for(let W in Y)if(Object.getOwnPropertyDescriptor(Z,W)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let G=bG(X._zod.def,{get shape(){let Z={...X._zod.def.shape,...Y};return VW(this,"shape",Z),Z}});return J9(X,G)}function o10(X,Y){if(!qW(Y))throw Error("Invalid input to safeExtend: expected a plain object");let Q=bG(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y};return VW(this,"shape",J),J}});return J9(X,Q)}function IJ4(X,Y){let Q=bG(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y._zod.def.shape};return VW(this,"shape",J),J},get catchall(){return Y._zod.def.catchall},checks:[]});return J9(X,Q)}function s10(X,Y,Q){let G=Y._zod.def.checks;if(G&&G.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let W=bG(Y._zod.def,{get shape(){let $=Y._zod.def.shape,K={...$};if(Q)for(let H in Q){if(!(H in $))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;K[H]=X?new X({type:"optional",innerType:$[H]}):$[H]}else for(let H in $)K[H]=X?new X({type:"optional",innerType:$[H]}):$[H];return VW(this,"shape",K),K},checks:[]});return J9(Y,W)}function t10(X,Y,Q){let J=bG(Y._zod.def,{get shape(){let G=Y._zod.def.shape,Z={...G};if(Q)for(let W in Q){if(!(W in Z))throw Error(`Unrecognized key: "${W}"`);if(!Q[W])continue;Z[W]=new X({type:"nonoptional",innerType:G[W]})}else for(let W in G)Z[W]=new X({type:"nonoptional",innerType:G[W]});return VW(this,"shape",Z),Z}});return J9(Y,J)}function UW(X,Y=0){if(X.aborted===!0)return!0;for(let Q=Y;Q<X.issues.length;Q++)if(X.issues[Q]?.continue!==!0)return!0;return!1}function gY(X,Y){return Y.map((Q)=>{var J;return(J=Q).path??(J.path=[]),Q.path.unshift(X),Q})}function cU(X){return typeof X==="string"?X:X?.message}function GY(X,Y,Q){let J={...X,path:X.path??[]};if(!X.message){let G=cU(X.inst?._zod.def?.error?.(X))??cU(Y?.error?.(X))??cU(Q.customError?.(X))??cU(Q.localeError?.(X))??"Invalid input";J.message=G}if(delete J.inst,delete J.continue,!Y?.reportInput)delete J.input;return J}function rU(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function oU(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function n0(X){let Y=typeof X;switch(Y){case"number":return Number.isNaN(X)?"nan":"number";case"object":{if(X===null)return"null";if(Array.isArray(X))return"array";let Q=X;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return Y}function DH(...X){let[Y,Q,J]=X;if(typeof Y==="string")return{message:Y,code:"custom",input:Q,inst:J};return{...Y}}function RJ4(X){return Object.entries(X).filter(([Y,Q])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function e10(X){let Y=atob(X),Q=new Uint8Array(Y.length);for(let J=0;J<Y.length;J++)Q[J]=Y.charCodeAt(J);return Q}function X80(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCharCode(X[Q]);return btoa(Y)}function SJ4(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-Y.length%4)%4);return e10(Y+Q)}function vJ4(X){return X80(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kJ4(X){let Y=X.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(Y.length/2);for(let J=0;J<Y.length;J+=2)Q[J/2]=Number.parseInt(Y.slice(J,J+2),16);return Q}function _J4(X){return Array.from(X).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class Y80{constructor(...X){}}var n10,qM,k_,jJ4=(X)=>{let Y=typeof X;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(X)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(X))return"array";if(X===null)return"null";if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return"promise";if(typeof Map<"u"&&X instanceof Map)return"map";if(typeof Set<"u"&&X instanceof Set)return"set";if(typeof Date<"u"&&X instanceof Date)return"date";if(typeof File<"u"&&X instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},aU,__,f_,b_;var C4=g(()=>{n10=Symbol("evaluating");qM="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};k_=BH(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});aU=new Set(["string","number","symbol"]),__=new Set(["string","number","bigint","boolean","symbol","undefined"]);f_={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},b_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function NH(X,Y=(Q)=>Q.message){let Q={},J=[];for(let G of X.issues)if(G.path.length>0)Q[G.path[0]]=Q[G.path[0]]||[],Q[G.path[0]].push(Y(G));else J.push(Y(G));return{formErrors:J,fieldErrors:Q}}function OH(X,Y=(Q)=>Q.message){let Q={_errors:[]},J=(G)=>{for(let Z of G.issues)if(Z.code==="invalid_union"&&Z.errors.length)Z.errors.map((W)=>J({issues:W}));else if(Z.code==="invalid_key")J({issues:Z.issues});else if(Z.code==="invalid_element")J({issues:Z.issues});else if(Z.path.length===0)Q._errors.push(Y(Z));else{let W=Q,$=0;while($<Z.path.length){let K=Z.path[$];if($!==Z.path.length-1)W[K]=W[K]||{_errors:[]};else W[K]=W[K]||{_errors:[]},W[K]._errors.push(Y(Z));W=W[K],$++}}};return J(X),Q}function zM(X,Y=(Q)=>Q.message){let Q={errors:[]},J=(G,Z=[])=>{var W,$;for(let K of G.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((H)=>J({issues:H},K.path));else if(K.code==="invalid_key")J({issues:K.issues},K.path);else if(K.code==="invalid_element")J({issues:K.issues},K.path);else{let H=[...Z,...K.path];if(H.length===0){Q.errors.push(Y(K));continue}let F=Q,V=0;while(V<H.length){let q=H[V],z=V===H.length-1;if(typeof q==="string")F.properties??(F.properties={}),(W=F.properties)[q]??(W[q]={errors:[]}),F=F.properties[q];else F.items??(F.items=[]),($=F.items)[q]??($[q]={errors:[]}),F=F.items[q];if(z)F.errors.push(Y(K));V++}}};return J(X),Q}function J80(X){let Y=[],Q=X.map((J)=>typeof J==="object"?J.key:J);for(let J of Q)if(typeof J==="number")Y.push(`[${J}]`);else if(typeof J==="symbol")Y.push(`[${JSON.stringify(String(J))}]`);else if(/[^\w$]/.test(J))Y.push(`[${JSON.stringify(J)}]`);else{if(Y.length)Y.push(".");Y.push(J)}return Y.join("")}function BM(X){let Y=[],Q=[...X.issues].sort((J,G)=>(J.path??[]).length-(G.path??[]).length);for(let J of Q)if(Y.push(`\u2716 ${J.message}`),J.path?.length)Y.push(` \u2192 at ${J80(J.path)}`);return Y.join(`
2
+ var VJ4=Object.create;var{getPrototypeOf:qJ4,defineProperty:T_,getOwnPropertyNames:UJ4}=Object;var zJ4=Object.prototype.hasOwnProperty;var U1=(X,Y,Q)=>{Q=X!=null?VJ4(qJ4(X)):{};let J=Y||!X||!X.__esModule?T_(Q,"default",{value:X,enumerable:!0}):Q;for(let G of UJ4(X))if(!zJ4.call(J,G))T_(J,G,{get:()=>X[G],enumerable:!0});return J};var j=(X,Y)=>()=>(Y||X((Y={exports:{}}).exports,Y),Y.exports);var h4=(X,Y)=>{for(var Q in Y)T_(X,Q,{get:Y[Q],enumerable:!0,configurable:!0,set:(J)=>Y[Q]=()=>J})};var g=(X,Y)=>()=>(X&&(Y=X(X=0)),Y);var U0=import.meta.require,A_=(X,Y,Q)=>{if(Y!=null){if(typeof Y!=="object"&&typeof Y!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let J;if(Q)J=Y[Symbol.asyncDispose];if(J===void 0)J=Y[Symbol.dispose];if(typeof J!=="function")throw TypeError("Object not disposable");X.push([Q,J,Y])}else if(Q)X.push([Q]);return Y},x10=(X,Y,Q)=>{let J=(Z)=>Y=Q?new SuppressedError(Z,Y,"An error was suppressed during disposal"):(Q=!0,Z),G=(Z)=>{while(Z=X.pop())try{var W=Z[1]&&Z[1].call(Z[2]);if(Z[0])return Promise.resolve(W).then(G,($)=>(J($),G()))}catch($){J($)}if(Q)throw Y};return G()};var KM="user-sandbox",g10="Create embeddable integration flows for platform end-users";import{sql as uU}from"kysely";var u10;var m10=g(()=>{u10={name:"001-user-sandbox",async up(X){await X.schema.createTable("user_sandbox").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Y)=>Y.notNull()).addColumn("description","text").addColumn("icon","text").addColumn("required_apps","text",(Y)=>Y.notNull()).addColumn("redirect_url","text").addColumn("webhook_url","text").addColumn("event_type","text",(Y)=>Y.notNull().defaultTo("integration.completed")).addColumn("agent_title_template","text",(Y)=>Y.notNull().defaultTo("Agent for {{externalUserId}}")).addColumn("agent_instructions","text").addColumn("tool_selection_mode","text",(Y)=>Y.notNull().defaultTo("inclusion")).addColumn("status","text",(Y)=>Y.notNull().defaultTo("active")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Y)=>Y.references("user.id").onDelete("set null")).execute(),await X.schema.createIndex("idx_user_sandbox_org").on("user_sandbox").column("organization_id").execute(),await X.schema.createTable("user_sandbox_sessions").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("template_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("status","text",(Y)=>Y.notNull().defaultTo("pending")).addColumn("app_statuses","text",(Y)=>Y.notNull().defaultTo("{}")).addColumn("created_agent_id","text",(Y)=>Y.references("connections.id").onDelete("set null")).addColumn("redirect_url","text").addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).addColumn("expires_at","text",(Y)=>Y.notNull()).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_template").on("user_sandbox_sessions").column("template_id").execute(),await X.schema.createIndex("idx_user_sandbox_sessions_external_user").on("user_sandbox_sessions").columns(["template_id","external_user_id"]).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_org").on("user_sandbox_sessions").column("organization_id").execute(),await X.schema.createTable("user_sandbox_agents").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("user_sandbox_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("connection_id","text",(Y)=>Y.notNull().references("connections.id").onDelete("cascade")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(uU`CURRENT_TIMESTAMP`)).execute(),await X.schema.createIndex("idx_user_sandbox_agents_unique").on("user_sandbox_agents").columns(["user_sandbox_id","external_user_id"]).unique().execute(),await X.schema.createIndex("idx_user_sandbox_agents_connection").on("user_sandbox_agents").column("connection_id").execute()},async down(X){await X.schema.dropIndex("idx_user_sandbox_agents_connection").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_agents_unique").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_org").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_external_user").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_template").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_org").ifExists().execute(),await X.schema.dropTable("user_sandbox_agents").ifExists().execute(),await X.schema.dropTable("user_sandbox_sessions").ifExists().execute(),await X.schema.dropTable("user_sandbox").ifExists().execute()}}});var l10;var d10=g(()=>{m10();l10=[u10]});function HM(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}class mU{db;constructor(X){this.db=X}async create(X){let Y=HM("usb"),Q=new Date().toISOString(),J={id:Y,organization_id:X.organization_id,title:X.title,description:X.description??null,icon:X.icon??null,required_apps:JSON.stringify(X.required_apps),redirect_url:X.redirect_url??null,webhook_url:X.webhook_url??null,event_type:X.event_type??"integration.completed",agent_title_template:X.agent_title_template??"{{externalUserId}}'s Agent",agent_instructions:X.agent_instructions??null,tool_selection_mode:X.tool_selection_mode??"inclusion",status:"active",created_at:Q,updated_at:Q,created_by:X.created_by??null};await this.db.insertInto("user_sandbox").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create user sandbox with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async list(X){return(await this.db.selectFrom("user_sandbox").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.icon!==void 0)J.icon=Y.icon;if(Y.required_apps!==void 0)J.required_apps=JSON.stringify(Y.required_apps);if(Y.redirect_url!==void 0)J.redirect_url=Y.redirect_url;if(Y.webhook_url!==void 0)J.webhook_url=Y.webhook_url;if(Y.event_type!==void 0)J.event_type=Y.event_type;if(Y.agent_title_template!==void 0)J.agent_title_template=Y.agent_title_template;if(Y.agent_instructions!==void 0)J.agent_instructions=Y.agent_instructions;if(Y.tool_selection_mode!==void 0)J.tool_selection_mode=Y.tool_selection_mode;if(Y.status!==void 0)J.status=Y.status;await this.db.updateTable("user_sandbox").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Template not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox").where("id","=",X).execute()}deserialize(X){let Y=[];try{Y=JSON.parse(X.required_apps)}catch{Y=[]}return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,icon:X.icon,required_apps:Y,redirect_url:X.redirect_url,webhook_url:X.webhook_url,event_type:X.event_type,agent_title_template:X.agent_title_template,agent_instructions:X.agent_instructions,tool_selection_mode:X.tool_selection_mode,status:X.status,created_at:X.created_at,updated_at:X.updated_at,created_by:X.created_by}}}var E_=()=>{};class lU{db;constructor(X){this.db=X}async create(X){let Y=HM("uss"),Q=new Date().toISOString(),J={id:Y,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:"pending",app_statuses:"{}",created_agent_id:X.created_agent_id??null,redirect_url:X.redirect_url??null,created_at:Q,updated_at:Q,expires_at:X.expires_at};await this.db.insertInto("user_sandbox_sessions").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create session with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async findExisting(X,Y){let Q=new Date().toISOString(),J=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).where("external_user_id","=",Y).where("expires_at",">",Q).where("status","!=","completed").orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return this.deserialize(J)}async listByTemplate(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async listByOrganization(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.status!==void 0)J.status=Y.status;if(Y.app_statuses!==void 0)J.app_statuses=JSON.stringify(Y.app_statuses);if(Y.created_agent_id!==void 0)J.created_agent_id=Y.created_agent_id;await this.db.updateTable("user_sandbox_sessions").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Session not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox_sessions").where("id","=",X).execute()}async deleteExpired(){let X=new Date().toISOString(),Y=await this.db.deleteFrom("user_sandbox_sessions").where("expires_at","<",X).where("status","!=","completed").executeTakeFirst();return Number(Y.numDeletedRows??0)}deserialize(X){let Y={};try{Y=JSON.parse(X.app_statuses)}catch{Y={}}return{id:X.id,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:X.status,app_statuses:Y,created_agent_id:X.created_agent_id,redirect_url:X.redirect_url,created_at:X.created_at,updated_at:X.updated_at,expires_at:X.expires_at}}}var j_=()=>{};function dU(X){C_=X}function JY(){if(!C_)throw Error(`Plugin storage not initialized. Make sure the "${KM}" plugin is enabled.`);return C_}function I_(){return process.env.BASE_URL||"http://localhost:3000"}var C_=null;var z5=()=>{};function p10(X){let Y=X.db,Q={templates:new mU(Y),sessions:new lU(Y)};return dU(Q),Q}var c10=g(()=>{E_();j_();z5()});function H0(X,Y,Q){function J($,K){if(!$._zod)Object.defineProperty($,"_zod",{value:{def:K,constr:W,traits:new Set},enumerable:!1});if($._zod.traits.has(X))return;$._zod.traits.add(X),Y($,K);let H=W.prototype,F=Object.keys(H);for(let V=0;V<F.length;V++){let q=F[V];if(!(q in $))$[q]=H[q].bind($)}}let G=Q?.Parent??Object;class Z extends G{}Object.defineProperty(Z,"name",{value:X});function W($){var K;let H=Q?.Parent?new Z:this;J(H,$),(K=H._zod).deferred??(K.deferred=[]);for(let F of H._zod.deferred)F();return H}return Object.defineProperty(W,"init",{value:J}),Object.defineProperty(W,Symbol.hasInstance,{value:($)=>{if(Q?.Parent&&$ instanceof Q.Parent)return!0;return $?._zod?.traits?.has(X)}}),Object.defineProperty(W,"name",{value:X}),W}function L8(X){if(X)Object.assign(pU,X);return pU}var qH,FM,B5,O$,pU;var UH=g(()=>{qH=Object.freeze({status:"aborted"});FM=Symbol("zod_brand");B5=class B5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};O$=class O$ extends Error{constructor(X){super(`Encountered unidirectional transform during encode: ${X}`);this.name="ZodEncodeError"}};pU={}});var p0={};h4(p0,{unwrapMessage:()=>cU,uint8ArrayToHex:()=>_J4,uint8ArrayToBase64url:()=>vJ4,uint8ArrayToBase64:()=>X80,stringifyPrimitive:()=>l0,slugify:()=>v_,shallowClone:()=>UM,safeExtend:()=>o10,required:()=>t10,randomString:()=>AJ4,propertyKeyTypes:()=>aU,promiseAllObject:()=>TJ4,primitiveTypes:()=>__,prefixIssues:()=>gY,pick:()=>i10,partial:()=>s10,parsedType:()=>n0,optionalKeys:()=>y_,omit:()=>a10,objectClone:()=>wJ4,numKeys:()=>EJ4,nullish:()=>FW,normalizeParams:()=>i0,mergeDefs:()=>bG,merge:()=>IJ4,jsonStringifyReplacer:()=>zH,joinValues:()=>M0,issue:()=>DH,isPlainObject:()=>qW,isObject:()=>L$,hexToUint8Array:()=>kJ4,getSizableOrigin:()=>rU,getParsedType:()=>jJ4,getLengthableOrigin:()=>oU,getEnumValues:()=>nU,getElementAtPath:()=>PJ4,floatSafeRemainder:()=>S_,finalizeIssue:()=>GY,extend:()=>r10,escapeRegex:()=>NQ,esc:()=>VM,defineLazy:()=>$6,createTransparentProxy:()=>CJ4,cloneDef:()=>MJ4,clone:()=>J9,cleanRegex:()=>iU,cleanEnum:()=>RJ4,captureStackTrace:()=>qM,cached:()=>BH,base64urlToUint8Array:()=>SJ4,base64ToUint8Array:()=>e10,assignProp:()=>VW,assertNotEqual:()=>DJ4,assertNever:()=>OJ4,assertIs:()=>NJ4,assertEqual:()=>BJ4,assert:()=>LJ4,allowsEval:()=>k_,aborted:()=>UW,NUMBER_FORMAT_RANGES:()=>f_,Class:()=>Y80,BIGINT_FORMAT_RANGES:()=>b_});function BJ4(X){return X}function DJ4(X){return X}function NJ4(X){}function OJ4(X){throw Error("Unexpected value in exhaustive check")}function LJ4(X){}function nU(X){let Y=Object.values(X).filter((J)=>typeof J==="number");return Object.entries(X).filter(([J,G])=>Y.indexOf(+J)===-1).map(([J,G])=>G)}function M0(X,Y="|"){return X.map((Q)=>l0(Q)).join(Y)}function zH(X,Y){if(typeof Y==="bigint")return Y.toString();return Y}function BH(X){return{get value(){{let Q=X();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function FW(X){return X===null||X===void 0}function iU(X){let Y=X.startsWith("^")?1:0,Q=X.endsWith("$")?X.length-1:X.length;return X.slice(Y,Q)}function S_(X,Y){let Q=(X.toString().split(".")[1]||"").length,J=Y.toString(),G=(J.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(J)){let K=J.match(/\d?e-(\d?)/);if(K?.[1])G=Number.parseInt(K[1])}let Z=Q>G?Q:G,W=Number.parseInt(X.toFixed(Z).replace(".","")),$=Number.parseInt(Y.toFixed(Z).replace(".",""));return W%$/10**Z}function $6(X,Y,Q){let J=void 0;Object.defineProperty(X,Y,{get(){if(J===n10)return;if(J===void 0)J=n10,J=Q();return J},set(G){Object.defineProperty(X,Y,{value:G})},configurable:!0})}function wJ4(X){return Object.create(Object.getPrototypeOf(X),Object.getOwnPropertyDescriptors(X))}function VW(X,Y,Q){Object.defineProperty(X,Y,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function bG(...X){let Y={};for(let Q of X){let J=Object.getOwnPropertyDescriptors(Q);Object.assign(Y,J)}return Object.defineProperties({},Y)}function MJ4(X){return bG(X._zod.def)}function PJ4(X,Y){if(!Y)return X;return Y.reduce((Q,J)=>Q?.[J],X)}function TJ4(X){let Y=Object.keys(X),Q=Y.map((J)=>X[J]);return Promise.all(Q).then((J)=>{let G={};for(let Z=0;Z<Y.length;Z++)G[Y[Z]]=J[Z];return G})}function AJ4(X=10){let Q="";for(let J=0;J<X;J++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function VM(X){return JSON.stringify(X)}function v_(X){return X.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function L$(X){return typeof X==="object"&&X!==null&&!Array.isArray(X)}function qW(X){if(L$(X)===!1)return!1;let Y=X.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let Q=Y.prototype;if(L$(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function UM(X){if(qW(X))return{...X};if(Array.isArray(X))return[...X];return X}function EJ4(X){let Y=0;for(let Q in X)if(Object.prototype.hasOwnProperty.call(X,Q))Y++;return Y}function NQ(X){return X.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function J9(X,Y,Q){let J=new X._zod.constr(Y??X._zod.def);if(!Y||Q?.parent)J._zod.parent=X;return J}function i0(X){let Y=X;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function CJ4(X){let Y;return new Proxy({},{get(Q,J,G){return Y??(Y=X()),Reflect.get(Y,J,G)},set(Q,J,G,Z){return Y??(Y=X()),Reflect.set(Y,J,G,Z)},has(Q,J){return Y??(Y=X()),Reflect.has(Y,J)},deleteProperty(Q,J){return Y??(Y=X()),Reflect.deleteProperty(Y,J)},ownKeys(Q){return Y??(Y=X()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(Q,J){return Y??(Y=X()),Reflect.getOwnPropertyDescriptor(Y,J)},defineProperty(Q,J,G){return Y??(Y=X()),Reflect.defineProperty(Y,J,G)}})}function l0(X){if(typeof X==="bigint")return X.toString()+"n";if(typeof X==="string")return`"${X}"`;return`${X}`}function y_(X){return Object.keys(X).filter((Y)=>{return X[Y]._zod.optin==="optional"&&X[Y]._zod.optout==="optional"})}function i10(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let Z=bG(X._zod.def,{get shape(){let W={};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;W[$]=Q.shape[$]}return VW(this,"shape",W),W},checks:[]});return J9(X,Z)}function a10(X,Y){let Q=X._zod.def,J=Q.checks;if(J&&J.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let Z=bG(X._zod.def,{get shape(){let W={...X._zod.def.shape};for(let $ in Y){if(!($ in Q.shape))throw Error(`Unrecognized key: "${$}"`);if(!Y[$])continue;delete W[$]}return VW(this,"shape",W),W},checks:[]});return J9(X,Z)}function r10(X,Y){if(!qW(Y))throw Error("Invalid input to extend: expected a plain object");let Q=X._zod.def.checks;if(Q&&Q.length>0){let Z=X._zod.def.shape;for(let W in Y)if(Object.getOwnPropertyDescriptor(Z,W)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let G=bG(X._zod.def,{get shape(){let Z={...X._zod.def.shape,...Y};return VW(this,"shape",Z),Z}});return J9(X,G)}function o10(X,Y){if(!qW(Y))throw Error("Invalid input to safeExtend: expected a plain object");let Q=bG(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y};return VW(this,"shape",J),J}});return J9(X,Q)}function IJ4(X,Y){let Q=bG(X._zod.def,{get shape(){let J={...X._zod.def.shape,...Y._zod.def.shape};return VW(this,"shape",J),J},get catchall(){return Y._zod.def.catchall},checks:[]});return J9(X,Q)}function s10(X,Y,Q){let G=Y._zod.def.checks;if(G&&G.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let W=bG(Y._zod.def,{get shape(){let $=Y._zod.def.shape,K={...$};if(Q)for(let H in Q){if(!(H in $))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;K[H]=X?new X({type:"optional",innerType:$[H]}):$[H]}else for(let H in $)K[H]=X?new X({type:"optional",innerType:$[H]}):$[H];return VW(this,"shape",K),K},checks:[]});return J9(Y,W)}function t10(X,Y,Q){let J=bG(Y._zod.def,{get shape(){let G=Y._zod.def.shape,Z={...G};if(Q)for(let W in Q){if(!(W in Z))throw Error(`Unrecognized key: "${W}"`);if(!Q[W])continue;Z[W]=new X({type:"nonoptional",innerType:G[W]})}else for(let W in G)Z[W]=new X({type:"nonoptional",innerType:G[W]});return VW(this,"shape",Z),Z}});return J9(Y,J)}function UW(X,Y=0){if(X.aborted===!0)return!0;for(let Q=Y;Q<X.issues.length;Q++)if(X.issues[Q]?.continue!==!0)return!0;return!1}function gY(X,Y){return Y.map((Q)=>{var J;return(J=Q).path??(J.path=[]),Q.path.unshift(X),Q})}function cU(X){return typeof X==="string"?X:X?.message}function GY(X,Y,Q){let J={...X,path:X.path??[]};if(!X.message){let G=cU(X.inst?._zod.def?.error?.(X))??cU(Y?.error?.(X))??cU(Q.customError?.(X))??cU(Q.localeError?.(X))??"Invalid input";J.message=G}if(delete J.inst,delete J.continue,!Y?.reportInput)delete J.input;return J}function rU(X){if(X instanceof Set)return"set";if(X instanceof Map)return"map";if(X instanceof File)return"file";return"unknown"}function oU(X){if(Array.isArray(X))return"array";if(typeof X==="string")return"string";return"unknown"}function n0(X){let Y=typeof X;switch(Y){case"number":return Number.isNaN(X)?"nan":"number";case"object":{if(X===null)return"null";if(Array.isArray(X))return"array";let Q=X;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return Y}function DH(...X){let[Y,Q,J]=X;if(typeof Y==="string")return{message:Y,code:"custom",input:Q,inst:J};return{...Y}}function RJ4(X){return Object.entries(X).filter(([Y,Q])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function e10(X){let Y=atob(X),Q=new Uint8Array(Y.length);for(let J=0;J<Y.length;J++)Q[J]=Y.charCodeAt(J);return Q}function X80(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCharCode(X[Q]);return btoa(Y)}function SJ4(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-Y.length%4)%4);return e10(Y+Q)}function vJ4(X){return X80(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function kJ4(X){let Y=X.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(Y.length/2);for(let J=0;J<Y.length;J+=2)Q[J/2]=Number.parseInt(Y.slice(J,J+2),16);return Q}function _J4(X){return Array.from(X).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class Y80{constructor(...X){}}var n10,qM,k_,jJ4=(X)=>{let Y=typeof X;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(X)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(X))return"array";if(X===null)return"null";if(X.then&&typeof X.then==="function"&&X.catch&&typeof X.catch==="function")return"promise";if(typeof Map<"u"&&X instanceof Map)return"map";if(typeof Set<"u"&&X instanceof Set)return"set";if(typeof Date<"u"&&X instanceof Date)return"date";if(typeof File<"u"&&X instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},aU,__,f_,b_;var C4=g(()=>{n10=Symbol("evaluating");qM="captureStackTrace"in Error?Error.captureStackTrace:(...X)=>{};k_=BH(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(X){return!1}});aU=new Set(["string","number","symbol"]),__=new Set(["string","number","bigint","boolean","symbol","undefined"]);f_={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},b_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function NH(X,Y=(Q)=>Q.message){let Q={},J=[];for(let G of X.issues)if(G.path.length>0)Q[G.path[0]]=Q[G.path[0]]||[],Q[G.path[0]].push(Y(G));else J.push(Y(G));return{formErrors:J,fieldErrors:Q}}function OH(X,Y=(Q)=>Q.message){let Q={_errors:[]},J=(G)=>{for(let Z of G.issues)if(Z.code==="invalid_union"&&Z.errors.length)Z.errors.map((W)=>J({issues:W}));else if(Z.code==="invalid_key")J({issues:Z.issues});else if(Z.code==="invalid_element")J({issues:Z.issues});else if(Z.path.length===0)Q._errors.push(Y(Z));else{let W=Q,$=0;while($<Z.path.length){let K=Z.path[$];if($!==Z.path.length-1)W[K]=W[K]||{_errors:[]};else W[K]=W[K]||{_errors:[]},W[K]._errors.push(Y(Z));W=W[K],$++}}};return J(X),Q}function zM(X,Y=(Q)=>Q.message){let Q={errors:[]},J=(G,Z=[])=>{var W,$;for(let K of G.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((H)=>J({issues:H},K.path));else if(K.code==="invalid_key")J({issues:K.issues},K.path);else if(K.code==="invalid_element")J({issues:K.issues},K.path);else{let H=[...Z,...K.path];if(H.length===0){Q.errors.push(Y(K));continue}let F=Q,V=0;while(V<H.length){let q=H[V],z=V===H.length-1;if(typeof q==="string")F.properties??(F.properties={}),(W=F.properties)[q]??(W[q]={errors:[]}),F=F.properties[q];else F.items??(F.items=[]),($=F.items)[q]??($[q]={errors:[]}),F=F.items[q];if(z)F.errors.push(Y(K));V++}}};return J(X),Q}function J80(X){let Y=[],Q=X.map((J)=>typeof J==="object"?J.key:J);for(let J of Q)if(typeof J==="number")Y.push(`[${J}]`);else if(typeof J==="symbol")Y.push(`[${JSON.stringify(String(J))}]`);else if(/[^\w$]/.test(J))Y.push(`[${JSON.stringify(J)}]`);else{if(Y.length)Y.push(".");Y.push(J)}return Y.join("")}function BM(X){let Y=[],Q=[...X.issues].sort((J,G)=>(J.path??[]).length-(G.path??[]).length);for(let J of Q)if(Y.push(`\u2716 ${J.message}`),J.path?.length)Y.push(` \u2192 at ${J80(J.path)}`);return Y.join(`
3
3
  `)}var Q80=(X,Y)=>{X.name="$ZodError",Object.defineProperty(X,"_zod",{value:X._zod,enumerable:!1}),Object.defineProperty(X,"issues",{value:Y,enumerable:!1}),X.message=JSON.stringify(Y,zH,2),Object.defineProperty(X,"toString",{value:()=>X.message,enumerable:!1})},sU,WY;var h_=g(()=>{UH();C4();sU=H0("$ZodError",Q80),WY=H0("$ZodError",Q80,{Parent:Error})});var LH=(X)=>(Y,Q,J,G)=>{let Z=J?Object.assign(J,{async:!1}):{async:!1},W=Y._zod.run({value:Q,issues:[]},Z);if(W instanceof Promise)throw new B5;if(W.issues.length){let $=new(G?.Err??X)(W.issues.map((K)=>GY(K,Z,L8())));throw qM($,G?.callee),$}return W.value},w$,wH=(X)=>async(Y,Q,J,G)=>{let Z=J?Object.assign(J,{async:!0}):{async:!0},W=Y._zod.run({value:Q,issues:[]},Z);if(W instanceof Promise)W=await W;if(W.issues.length){let $=new(G?.Err??X)(W.issues.map((K)=>GY(K,Z,L8())));throw qM($,G?.callee),$}return W.value},M$,MH=(X)=>(Y,Q,J)=>{let G=J?{...J,async:!1}:{async:!1},Z=Y._zod.run({value:Q,issues:[]},G);if(Z instanceof Promise)throw new B5;return Z.issues.length?{success:!1,error:new(X??sU)(Z.issues.map((W)=>GY(W,G,L8())))}:{success:!0,data:Z.value}},zW,PH=(X)=>async(Y,Q,J)=>{let G=J?Object.assign(J,{async:!0}):{async:!0},Z=Y._zod.run({value:Q,issues:[]},G);if(Z instanceof Promise)Z=await Z;return Z.issues.length?{success:!1,error:new X(Z.issues.map((W)=>GY(W,G,L8())))}:{success:!0,data:Z.value}},BW,DM=(X)=>(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return LH(X)(Y,Q,G)},G80,NM=(X)=>(Y,Q,J)=>{return LH(X)(Y,Q,J)},W80,OM=(X)=>async(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return wH(X)(Y,Q,G)},Z80,LM=(X)=>async(Y,Q,J)=>{return wH(X)(Y,Q,J)},$80,wM=(X)=>(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return MH(X)(Y,Q,G)},K80,MM=(X)=>(Y,Q,J)=>{return MH(X)(Y,Q,J)},H80,PM=(X)=>async(Y,Q,J)=>{let G=J?Object.assign(J,{direction:"backward"}):{direction:"backward"};return PH(X)(Y,Q,G)},F80,TM=(X)=>async(Y,Q,J)=>{return PH(X)(Y,Q,J)},V80;var x_=g(()=>{UH();h_();C4();w$=LH(WY),M$=wH(WY),zW=MH(WY),BW=PH(WY),G80=DM(WY),W80=NM(WY),Z80=OM(WY),$80=LM(WY),K80=wM(WY),H80=MM(WY),F80=PM(WY),V80=TM(WY)});var ZY={};h4(ZY,{xid:()=>l_,uuid7:()=>xJ4,uuid6:()=>hJ4,uuid4:()=>bJ4,uuid:()=>P$,uppercase:()=>qy,unicodeEmail:()=>q80,undefined:()=>Fy,ulid:()=>m_,time:()=>Jy,string:()=>Wy,sha512_hex:()=>W54,sha512_base64url:()=>$54,sha512_base64:()=>Z54,sha384_hex:()=>Q54,sha384_base64url:()=>G54,sha384_base64:()=>J54,sha256_hex:()=>eJ4,sha256_base64url:()=>Y54,sha256_base64:()=>X54,sha1_hex:()=>oJ4,sha1_base64url:()=>tJ4,sha1_base64:()=>sJ4,rfc5322Email:()=>uJ4,number:()=>tU,null:()=>Hy,nanoid:()=>p_,md5_hex:()=>iJ4,md5_base64url:()=>rJ4,md5_base64:()=>aJ4,mac:()=>s_,lowercase:()=>Vy,ksuid:()=>d_,ipv6:()=>o_,ipv4:()=>r_,integer:()=>$y,idnEmail:()=>mJ4,html5Email:()=>gJ4,hostname:()=>pJ4,hex:()=>nJ4,guid:()=>n_,extendedDuration:()=>fJ4,emoji:()=>a_,email:()=>i_,e164:()=>Yy,duration:()=>c_,domain:()=>cJ4,datetime:()=>Gy,date:()=>Qy,cuid2:()=>u_,cuid:()=>g_,cidrv6:()=>e_,cidrv4:()=>t_,browserEmail:()=>lJ4,boolean:()=>Ky,bigint:()=>Zy,base64url:()=>AM,base64:()=>Xy});function a_(){return new RegExp(dJ4,"u")}function z80(X){return typeof X.precision==="number"?X.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":X.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${X.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Jy(X){return new RegExp(`^${z80(X)}$`)}function Gy(X){let Y=z80({precision:X.precision}),Q=["Z"];if(X.local)Q.push("");if(X.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let J=`${Y}(?:${Q.join("|")})`;return new RegExp(`^${U80}T(?:${J})$`)}function eU(X,Y){return new RegExp(`^[A-Za-z0-9+/]{${X}}${Y}$`)}function Xz(X){return new RegExp(`^[A-Za-z0-9_-]{${X}}$`)}var g_,u_,m_,l_,d_,p_,c_,fJ4,n_,P$=(X)=>{if(!X)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${X}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},bJ4,hJ4,xJ4,i_,gJ4,uJ4,q80,mJ4,lJ4,dJ4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",r_,o_,s_=(X)=>{let Y=NQ(X??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},t_,e_,Xy,AM,pJ4,cJ4,Yy,U80="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Qy,Wy=(X)=>{let Y=X?`[\\s\\S]{${X?.minimum??0},${X?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},Zy,$y,tU,Ky,Hy,Fy,Vy,qy,nJ4,iJ4,aJ4,rJ4,oJ4,sJ4,tJ4,eJ4,X54,Y54,Q54,J54,G54,W54,Z54,$54;var EM=g(()=>{C4();g_=/^[cC][^\s-]{8,}$/,u_=/^[0-9a-z]+$/,m_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,l_=/^[0-9a-vA-V]{20}$/,d_=/^[A-Za-z0-9]{27}$/,p_=/^[a-zA-Z0-9_-]{21}$/,c_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fJ4=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,n_=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bJ4=P$(4),hJ4=P$(6),xJ4=P$(7),i_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,gJ4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,uJ4=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,q80=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,mJ4=q80,lJ4=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;r_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,o_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,t_=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,e_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,AM=/^[A-Za-z0-9_-]*$/,pJ4=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,cJ4=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Yy=/^\+[1-9]\d{6,14}$/,Qy=new RegExp(`^${U80}$`);Zy=/^-?\d+n?$/,$y=/^-?\d+$/,tU=/^-?\d+(?:\.\d+)?$/,Ky=/^(?:true|false)$/i,Hy=/^null$/i,Fy=/^undefined$/i,Vy=/^[^A-Z]*$/,qy=/^[^a-z]*$/,nJ4=/^[0-9a-fA-F]*$/;iJ4=/^[0-9a-fA-F]{32}$/,aJ4=eU(22,"=="),rJ4=Xz(22),oJ4=/^[0-9a-fA-F]{40}$/,sJ4=eU(27,"="),tJ4=Xz(27),eJ4=/^[0-9a-fA-F]{64}$/,X54=eU(43,"="),Y54=Xz(43),Q54=/^[0-9a-fA-F]{96}$/,J54=eU(64,""),G54=Xz(64),W54=/^[0-9a-fA-F]{128}$/,Z54=eU(86,"=="),$54=Xz(86)});function B80(X,Y,Q){if(X.issues.length)Y.issues.push(...gY(Q,X.issues))}var C1,D80,jM,CM,Uy,zy,By,Dy,Ny,Oy,Ly,wy,My,TH,Py,Ty,Ay,Ey,jy,Cy,Iy,Ry,Sy;var IM=g(()=>{UH();EM();C4();C1=H0("$ZodCheck",(X,Y)=>{var Q;X._zod??(X._zod={}),X._zod.def=Y,(Q=X._zod).onattach??(Q.onattach=[])}),D80={number:"number",bigint:"bigint",object:"date"},jM=H0("$ZodCheckLessThan",(X,Y)=>{C1.init(X,Y);let Q=D80[typeof Y.value];X._zod.onattach.push((J)=>{let G=J._zod.bag,Z=(Y.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Y.value<Z)if(Y.inclusive)G.maximum=Y.value;else G.exclusiveMaximum=Y.value}),X._zod.check=(J)=>{if(Y.inclusive?J.value<=Y.value:J.value<Y.value)return;J.issues.push({origin:Q,code:"too_big",maximum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:J.value,inclusive:Y.inclusive,inst:X,continue:!Y.abort})}}),CM=H0("$ZodCheckGreaterThan",(X,Y)=>{C1.init(X,Y);let Q=D80[typeof Y.value];X._zod.onattach.push((J)=>{let G=J._zod.bag,Z=(Y.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>Z)if(Y.inclusive)G.minimum=Y.value;else G.exclusiveMinimum=Y.value}),X._zod.check=(J)=>{if(Y.inclusive?J.value>=Y.value:J.value>Y.value)return;J.issues.push({origin:Q,code:"too_small",minimum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:J.value,inclusive:Y.inclusive,inst:X,continue:!Y.abort})}}),Uy=H0("$ZodCheckMultipleOf",(X,Y)=>{C1.init(X,Y),X._zod.onattach.push((Q)=>{var J;(J=Q._zod.bag).multipleOf??(J.multipleOf=Y.value)}),X._zod.check=(Q)=>{if(typeof Q.value!==typeof Y.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%Y.value===BigInt(0):S_(Q.value,Y.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:Y.value,input:Q.value,inst:X,continue:!Y.abort})}}),zy=H0("$ZodCheckNumberFormat",(X,Y)=>{C1.init(X,Y),Y.format=Y.format||"float64";let Q=Y.format?.includes("int"),J=Q?"int":"number",[G,Z]=f_[Y.format];X._zod.onattach.push((W)=>{let $=W._zod.bag;if($.format=Y.format,$.minimum=G,$.maximum=Z,Q)$.pattern=$y}),X._zod.check=(W)=>{let $=W.value;if(Q){if(!Number.isInteger($)){W.issues.push({expected:J,format:Y.format,code:"invalid_type",continue:!1,input:$,inst:X});return}if(!Number.isSafeInteger($)){if($>0)W.issues.push({input:$,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:X,origin:J,inclusive:!0,continue:!Y.abort});else W.issues.push({input:$,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:X,origin:J,inclusive:!0,continue:!Y.abort});return}}if($<G)W.issues.push({origin:"number",input:$,code:"too_small",minimum:G,inclusive:!0,inst:X,continue:!Y.abort});if($>Z)W.issues.push({origin:"number",input:$,code:"too_big",maximum:Z,inclusive:!0,inst:X,continue:!Y.abort})}}),By=H0("$ZodCheckBigIntFormat",(X,Y)=>{C1.init(X,Y);let[Q,J]=b_[Y.format];X._zod.onattach.push((G)=>{let Z=G._zod.bag;Z.format=Y.format,Z.minimum=Q,Z.maximum=J}),X._zod.check=(G)=>{let Z=G.value;if(Z<Q)G.issues.push({origin:"bigint",input:Z,code:"too_small",minimum:Q,inclusive:!0,inst:X,continue:!Y.abort});if(Z>J)G.issues.push({origin:"bigint",input:Z,code:"too_big",maximum:J,inclusive:!0,inst:X,continue:!Y.abort})}}),Dy=H0("$ZodCheckMaxSize",(X,Y)=>{var Q;C1.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!FW(G)&&G.size!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<G)J._zod.bag.maximum=Y.maximum}),X._zod.check=(J)=>{let G=J.value;if(G.size<=Y.maximum)return;J.issues.push({origin:rU(G),code:"too_big",maximum:Y.maximum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),Ny=H0("$ZodCheckMinSize",(X,Y)=>{var Q;C1.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!FW(G)&&G.size!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>G)J._zod.bag.minimum=Y.minimum}),X._zod.check=(J)=>{let G=J.value;if(G.size>=Y.minimum)return;J.issues.push({origin:rU(G),code:"too_small",minimum:Y.minimum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),Oy=H0("$ZodCheckSizeEquals",(X,Y)=>{var Q;C1.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!FW(G)&&G.size!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.minimum=Y.size,G.maximum=Y.size,G.size=Y.size}),X._zod.check=(J)=>{let G=J.value,Z=G.size;if(Z===Y.size)return;let W=Z>Y.size;J.issues.push({origin:rU(G),...W?{code:"too_big",maximum:Y.size}:{code:"too_small",minimum:Y.size},inclusive:!0,exact:!0,input:J.value,inst:X,continue:!Y.abort})}}),Ly=H0("$ZodCheckMaxLength",(X,Y)=>{var Q;C1.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!FW(G)&&G.length!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<G)J._zod.bag.maximum=Y.maximum}),X._zod.check=(J)=>{let G=J.value;if(G.length<=Y.maximum)return;let W=oU(G);J.issues.push({origin:W,code:"too_big",maximum:Y.maximum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),wy=H0("$ZodCheckMinLength",(X,Y)=>{var Q;C1.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!FW(G)&&G.length!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>G)J._zod.bag.minimum=Y.minimum}),X._zod.check=(J)=>{let G=J.value;if(G.length>=Y.minimum)return;let W=oU(G);J.issues.push({origin:W,code:"too_small",minimum:Y.minimum,inclusive:!0,input:G,inst:X,continue:!Y.abort})}}),My=H0("$ZodCheckLengthEquals",(X,Y)=>{var Q;C1.init(X,Y),(Q=X._zod.def).when??(Q.when=(J)=>{let G=J.value;return!FW(G)&&G.length!==void 0}),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.minimum=Y.length,G.maximum=Y.length,G.length=Y.length}),X._zod.check=(J)=>{let G=J.value,Z=G.length;if(Z===Y.length)return;let W=oU(G),$=Z>Y.length;J.issues.push({origin:W,...$?{code:"too_big",maximum:Y.length}:{code:"too_small",minimum:Y.length},inclusive:!0,exact:!0,input:J.value,inst:X,continue:!Y.abort})}}),TH=H0("$ZodCheckStringFormat",(X,Y)=>{var Q,J;if(C1.init(X,Y),X._zod.onattach.push((G)=>{let Z=G._zod.bag;if(Z.format=Y.format,Y.pattern)Z.patterns??(Z.patterns=new Set),Z.patterns.add(Y.pattern)}),Y.pattern)(Q=X._zod).check??(Q.check=(G)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:G.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:X,continue:!Y.abort})});else(J=X._zod).check??(J.check=()=>{})}),Py=H0("$ZodCheckRegex",(X,Y)=>{TH.init(X,Y),X._zod.check=(Q)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:Y.pattern.toString(),inst:X,continue:!Y.abort})}}),Ty=H0("$ZodCheckLowerCase",(X,Y)=>{Y.pattern??(Y.pattern=Vy),TH.init(X,Y)}),Ay=H0("$ZodCheckUpperCase",(X,Y)=>{Y.pattern??(Y.pattern=qy),TH.init(X,Y)}),Ey=H0("$ZodCheckIncludes",(X,Y)=>{C1.init(X,Y);let Q=NQ(Y.includes),J=new RegExp(typeof Y.position==="number"?`^.{${Y.position}}${Q}`:Q);Y.pattern=J,X._zod.onattach.push((G)=>{let Z=G._zod.bag;Z.patterns??(Z.patterns=new Set),Z.patterns.add(J)}),X._zod.check=(G)=>{if(G.value.includes(Y.includes,Y.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Y.includes,input:G.value,inst:X,continue:!Y.abort})}}),jy=H0("$ZodCheckStartsWith",(X,Y)=>{C1.init(X,Y);let Q=new RegExp(`^${NQ(Y.prefix)}.*`);Y.pattern??(Y.pattern=Q),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),X._zod.check=(J)=>{if(J.value.startsWith(Y.prefix))return;J.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Y.prefix,input:J.value,inst:X,continue:!Y.abort})}}),Cy=H0("$ZodCheckEndsWith",(X,Y)=>{C1.init(X,Y);let Q=new RegExp(`.*${NQ(Y.suffix)}$`);Y.pattern??(Y.pattern=Q),X._zod.onattach.push((J)=>{let G=J._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),X._zod.check=(J)=>{if(J.value.endsWith(Y.suffix))return;J.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Y.suffix,input:J.value,inst:X,continue:!Y.abort})}});Iy=H0("$ZodCheckProperty",(X,Y)=>{C1.init(X,Y),X._zod.check=(Q)=>{let J=Y.schema._zod.run({value:Q.value[Y.property],issues:[]},{});if(J instanceof Promise)return J.then((G)=>B80(G,Q,Y.property));B80(J,Q,Y.property);return}}),Ry=H0("$ZodCheckMimeType",(X,Y)=>{C1.init(X,Y);let Q=new Set(Y.mime);X._zod.onattach.push((J)=>{J._zod.bag.mime=Y.mime}),X._zod.check=(J)=>{if(Q.has(J.value.type))return;J.issues.push({code:"invalid_value",values:Y.mime,input:J.value.type,inst:X,continue:!Y.abort})}}),Sy=H0("$ZodCheckOverwrite",(X,Y)=>{C1.init(X,Y),X._zod.check=(Q)=>{Q.value=Y.tx(Q.value)}})});class RM{constructor(X=[]){if(this.content=[],this.indent=0,this)this.args=X}indented(X){this.indent+=1,X(this),this.indent-=1}write(X){if(typeof X==="function"){X(this,{execution:"sync"}),X(this,{execution:"async"});return}let Q=X.split(`
4
4
  `).filter((Z)=>Z),J=Math.min(...Q.map((Z)=>Z.length-Z.trimStart().length)),G=Q.map((Z)=>Z.slice(J)).map((Z)=>" ".repeat(this.indent*2)+Z);for(let Z of G)this.content.push(Z)}compile(){let X=Function,Y=this?.args,J=[...(this?.content??[""]).map((G)=>` ${G}`)];return new X(...Y,J.join(`
5
5
  `))}}var vy;var ky=g(()=>{vy={major:4,minor:3,patch:6}});function xy(X){if(X==="")return!0;if(X.length%4!==0)return!1;try{return atob(X),!0}catch{return!1}}function R80(X){if(!AM.test(X))return!1;let Y=X.replace(/[-_]/g,(J)=>J==="-"?"+":"/"),Q=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return xy(Q)}function S80(X,Y=null){try{let Q=X.split(".");if(Q.length!==3)return!1;let[J]=Q;if(!J)return!1;let G=JSON.parse(atob(J));if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(Y&&(!("alg"in G)||G.alg!==Y))return!1;return!0}catch{return!1}}function O80(X,Y,Q){if(X.issues.length)Y.issues.push(...gY(Q,X.issues));Y.value[Q]=X.value}function yM(X,Y,Q,J,G){if(X.issues.length){if(G&&!(Q in J))return;Y.issues.push(...gY(Q,X.issues))}if(X.value===void 0){if(Q in J)Y.value[Q]=void 0}else Y.value[Q]=X.value}function v80(X){let Y=Object.keys(X.shape);for(let J of Y)if(!X.shape?.[J]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${J}": expected a Zod schema`);let Q=y_(X.shape);return{...X,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(Q)}}function k80(X,Y,Q,J,G,Z){let W=[],$=G.keySet,K=G.catchall._zod,H=K.def.type,F=K.optout==="optional";for(let V in Y){if($.has(V))continue;if(H==="never"){W.push(V);continue}let q=K.run({value:Y[V],issues:[]},J);if(q instanceof Promise)X.push(q.then((z)=>yM(z,Q,V,Y,F)));else yM(q,Q,V,Y,F)}if(W.length)Q.issues.push({code:"unrecognized_keys",keys:W,input:Y,inst:Z});if(!X.length)return Q;return Promise.all(X).then(()=>{return Q})}function L80(X,Y,Q,J){for(let Z of X)if(Z.issues.length===0)return Y.value=Z.value,Y;let G=X.filter((Z)=>!UW(Z));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:Q,errors:X.map((Z)=>Z.issues.map((W)=>GY(W,J,L8())))}),Y}function w80(X,Y,Q,J){let G=X.filter((Z)=>Z.issues.length===0);if(G.length===1)return Y.value=G[0].value,Y;if(G.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:Q,errors:X.map((Z)=>Z.issues.map((W)=>GY(W,J,L8())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:Q,errors:[],inclusive:!1});return Y}function _y(X,Y){if(X===Y)return{valid:!0,data:X};if(X instanceof Date&&Y instanceof Date&&+X===+Y)return{valid:!0,data:X};if(qW(X)&&qW(Y)){let Q=Object.keys(Y),J=Object.keys(X).filter((Z)=>Q.indexOf(Z)!==-1),G={...X,...Y};for(let Z of J){let W=_y(X[Z],Y[Z]);if(!W.valid)return{valid:!1,mergeErrorPath:[Z,...W.mergeErrorPath]};G[Z]=W.data}return{valid:!0,data:G}}if(Array.isArray(X)&&Array.isArray(Y)){if(X.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let J=0;J<X.length;J++){let G=X[J],Z=Y[J],W=_y(G,Z);if(!W.valid)return{valid:!1,mergeErrorPath:[J,...W.mergeErrorPath]};Q.push(W.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function M80(X,Y,Q){let J=new Map,G;for(let $ of Y.issues)if($.code==="unrecognized_keys"){G??(G=$);for(let K of $.keys){if(!J.has(K))J.set(K,{});J.get(K).l=!0}}else X.issues.push($);for(let $ of Q.issues)if($.code==="unrecognized_keys")for(let K of $.keys){if(!J.has(K))J.set(K,{});J.get(K).r=!0}else X.issues.push($);let Z=[...J].filter(([,$])=>$.l&&$.r).map(([$])=>$);if(Z.length&&G)X.issues.push({...G,keys:Z});if(UW(X))return X;let W=_y(Y.value,Q.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return X.value=W.data,X}function SM(X,Y,Q){if(X.issues.length)Y.issues.push(...gY(Q,X.issues));Y.value[Q]=X.value}function P80(X,Y,Q,J,G,Z,W){if(X.issues.length)if(aU.has(typeof J))Q.issues.push(...gY(J,X.issues));else Q.issues.push({code:"invalid_key",origin:"map",input:G,inst:Z,issues:X.issues.map(($)=>GY($,W,L8()))});if(Y.issues.length)if(aU.has(typeof J))Q.issues.push(...gY(J,Y.issues));else Q.issues.push({origin:"map",code:"invalid_element",input:G,inst:Z,key:J,issues:Y.issues.map(($)=>GY($,W,L8()))});Q.value.set(X.value,Y.value)}function T80(X,Y){if(X.issues.length)Y.issues.push(...X.issues);Y.value.add(X.value)}function A80(X,Y){if(X.issues.length&&Y===void 0)return{issues:[],value:void 0};return X}function E80(X,Y){if(X.value===void 0)X.value=Y.defaultValue;return X}function j80(X,Y){if(!X.issues.length&&X.value===void 0)X.issues.push({code:"invalid_type",expected:"nonoptional",input:X.value,inst:Y});return X}function vM(X,Y,Q){if(X.issues.length)return X.aborted=!0,X;return Y._zod.run({value:X.value,issues:X.issues},Q)}function kM(X,Y,Q){if(X.issues.length)return X.aborted=!0,X;if((Q.direction||"forward")==="forward"){let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then((Z)=>_M(X,Z,Y.out,Q));return _M(X,G,Y.out,Q)}else{let G=Y.reverseTransform(X.value,X);if(G instanceof Promise)return G.then((Z)=>_M(X,Z,Y.in,Q));return _M(X,G,Y.in,Q)}}function _M(X,Y,Q,J){if(X.issues.length)return X.aborted=!0,X;return Q._zod.run({value:Y,issues:X.issues},J)}function C80(X){return X.value=Object.freeze(X.value),X}function I80(X,Y,Q,J){if(!X){let G={code:"custom",input:Q,inst:J,path:[...J._zod.def.path??[]],continue:!J._zod.def.abort};if(J._zod.def.params)G.params=J._zod.def.params;Y.issues.push(DH(G))}}var a4,DW,M1,fM,bM,hM,xM,gM,uM,mM,lM,dM,pM,cM,yy,fy,by,hy,nM,iM,aM,rM,oM,sM,tM,eM,XP,YP,Yz,QP,AH,Qz,JP,GP,WP,ZP,$P,KP,HP,FP,VP,qP,UP,gy,EH,zP,BP,DP,Jz,NP,OP,LP,wP,MP,PP,TP,Gz,AP,EP,jP,CP,IP,RP,SP,vP,kP,jH,_P,yP,fP,bP,hP,xP;var uy=g(()=>{IM();UH();x_();EM();C4();ky();C4();a4=H0("$ZodType",(X,Y)=>{var Q;X??(X={}),X._zod.def=Y,X._zod.bag=X._zod.bag||{},X._zod.version=vy;let J=[...X._zod.def.checks??[]];if(X._zod.traits.has("$ZodCheck"))J.unshift(X);for(let G of J)for(let Z of G._zod.onattach)Z(X);if(J.length===0)(Q=X._zod).deferred??(Q.deferred=[]),X._zod.deferred?.push(()=>{X._zod.run=X._zod.parse});else{let G=(W,$,K)=>{let H=UW(W),F;for(let V of $){if(V._zod.def.when){if(!V._zod.def.when(W))continue}else if(H)continue;let q=W.issues.length,z=V._zod.check(W);if(z instanceof Promise&&K?.async===!1)throw new B5;if(F||z instanceof Promise)F=(F??Promise.resolve()).then(async()=>{if(await z,W.issues.length===q)return;if(!H)H=UW(W,q)});else{if(W.issues.length===q)continue;if(!H)H=UW(W,q)}}if(F)return F.then(()=>{return W});return W},Z=(W,$,K)=>{if(UW(W))return W.aborted=!0,W;let H=G($,J,K);if(H instanceof Promise){if(K.async===!1)throw new B5;return H.then((F)=>X._zod.parse(F,K))}return X._zod.parse(H,K)};X._zod.run=(W,$)=>{if($.skipChecks)return X._zod.parse(W,$);if($.direction==="backward"){let H=X._zod.parse({value:W.value,issues:[]},{...$,skipChecks:!0});if(H instanceof Promise)return H.then((F)=>{return Z(F,W,$)});return Z(H,W,$)}let K=X._zod.parse(W,$);if(K instanceof Promise){if($.async===!1)throw new B5;return K.then((H)=>G(H,J,$))}return G(K,J,$)}}$6(X,"~standard",()=>({validate:(G)=>{try{let Z=zW(X,G);return Z.success?{value:Z.data}:{issues:Z.error?.issues}}catch(Z){return BW(X,G).then((W)=>W.success?{value:W.data}:{issues:W.error?.issues})}},vendor:"zod",version:1}))}),DW=H0("$ZodString",(X,Y)=>{a4.init(X,Y),X._zod.pattern=[...X?._zod.bag?.patterns??[]].pop()??Wy(X._zod.bag),X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=String(Q.value)}catch(G){}if(typeof Q.value==="string")return Q;return Q.issues.push({expected:"string",code:"invalid_type",input:Q.value,inst:X}),Q}}),M1=H0("$ZodStringFormat",(X,Y)=>{TH.init(X,Y),DW.init(X,Y)}),fM=H0("$ZodGUID",(X,Y)=>{Y.pattern??(Y.pattern=n_),M1.init(X,Y)}),bM=H0("$ZodUUID",(X,Y)=>{if(Y.version){let J={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[Y.version];if(J===void 0)throw Error(`Invalid UUID version: "${Y.version}"`);Y.pattern??(Y.pattern=P$(J))}else Y.pattern??(Y.pattern=P$());M1.init(X,Y)}),hM=H0("$ZodEmail",(X,Y)=>{Y.pattern??(Y.pattern=i_),M1.init(X,Y)}),xM=H0("$ZodURL",(X,Y)=>{M1.init(X,Y),X._zod.check=(Q)=>{try{let J=Q.value.trim(),G=new URL(J);if(Y.hostname){if(Y.hostname.lastIndex=0,!Y.hostname.test(G.hostname))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y.hostname.source,input:Q.value,inst:X,continue:!Y.abort})}if(Y.protocol){if(Y.protocol.lastIndex=0,!Y.protocol.test(G.protocol.endsWith(":")?G.protocol.slice(0,-1):G.protocol))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Y.protocol.source,input:Q.value,inst:X,continue:!Y.abort})}if(Y.normalize)Q.value=G.href;else Q.value=J;return}catch(J){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:X,continue:!Y.abort})}}}),gM=H0("$ZodEmoji",(X,Y)=>{Y.pattern??(Y.pattern=a_()),M1.init(X,Y)}),uM=H0("$ZodNanoID",(X,Y)=>{Y.pattern??(Y.pattern=p_),M1.init(X,Y)}),mM=H0("$ZodCUID",(X,Y)=>{Y.pattern??(Y.pattern=g_),M1.init(X,Y)}),lM=H0("$ZodCUID2",(X,Y)=>{Y.pattern??(Y.pattern=u_),M1.init(X,Y)}),dM=H0("$ZodULID",(X,Y)=>{Y.pattern??(Y.pattern=m_),M1.init(X,Y)}),pM=H0("$ZodXID",(X,Y)=>{Y.pattern??(Y.pattern=l_),M1.init(X,Y)}),cM=H0("$ZodKSUID",(X,Y)=>{Y.pattern??(Y.pattern=d_),M1.init(X,Y)}),yy=H0("$ZodISODateTime",(X,Y)=>{Y.pattern??(Y.pattern=Gy(Y)),M1.init(X,Y)}),fy=H0("$ZodISODate",(X,Y)=>{Y.pattern??(Y.pattern=Qy),M1.init(X,Y)}),by=H0("$ZodISOTime",(X,Y)=>{Y.pattern??(Y.pattern=Jy(Y)),M1.init(X,Y)}),hy=H0("$ZodISODuration",(X,Y)=>{Y.pattern??(Y.pattern=c_),M1.init(X,Y)}),nM=H0("$ZodIPv4",(X,Y)=>{Y.pattern??(Y.pattern=r_),M1.init(X,Y),X._zod.bag.format="ipv4"}),iM=H0("$ZodIPv6",(X,Y)=>{Y.pattern??(Y.pattern=o_),M1.init(X,Y),X._zod.bag.format="ipv6",X._zod.check=(Q)=>{try{new URL(`http://[${Q.value}]`)}catch{Q.issues.push({code:"invalid_format",format:"ipv6",input:Q.value,inst:X,continue:!Y.abort})}}}),aM=H0("$ZodMAC",(X,Y)=>{Y.pattern??(Y.pattern=s_(Y.delimiter)),M1.init(X,Y),X._zod.bag.format="mac"}),rM=H0("$ZodCIDRv4",(X,Y)=>{Y.pattern??(Y.pattern=t_),M1.init(X,Y)}),oM=H0("$ZodCIDRv6",(X,Y)=>{Y.pattern??(Y.pattern=e_),M1.init(X,Y),X._zod.check=(Q)=>{let J=Q.value.split("/");try{if(J.length!==2)throw Error();let[G,Z]=J;if(!Z)throw Error();let W=Number(Z);if(`${W}`!==Z)throw Error();if(W<0||W>128)throw Error();new URL(`http://[${G}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:X,continue:!Y.abort})}}});sM=H0("$ZodBase64",(X,Y)=>{Y.pattern??(Y.pattern=Xy),M1.init(X,Y),X._zod.bag.contentEncoding="base64",X._zod.check=(Q)=>{if(xy(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:X,continue:!Y.abort})}});tM=H0("$ZodBase64URL",(X,Y)=>{Y.pattern??(Y.pattern=AM),M1.init(X,Y),X._zod.bag.contentEncoding="base64url",X._zod.check=(Q)=>{if(R80(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:X,continue:!Y.abort})}}),eM=H0("$ZodE164",(X,Y)=>{Y.pattern??(Y.pattern=Yy),M1.init(X,Y)});XP=H0("$ZodJWT",(X,Y)=>{M1.init(X,Y),X._zod.check=(Q)=>{if(S80(Q.value,Y.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:X,continue:!Y.abort})}}),YP=H0("$ZodCustomStringFormat",(X,Y)=>{M1.init(X,Y),X._zod.check=(Q)=>{if(Y.fn(Q.value))return;Q.issues.push({code:"invalid_format",format:Y.format,input:Q.value,inst:X,continue:!Y.abort})}}),Yz=H0("$ZodNumber",(X,Y)=>{a4.init(X,Y),X._zod.pattern=X._zod.bag.pattern??tU,X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=Number(Q.value)}catch(W){}let G=Q.value;if(typeof G==="number"&&!Number.isNaN(G)&&Number.isFinite(G))return Q;let Z=typeof G==="number"?Number.isNaN(G)?"NaN":!Number.isFinite(G)?"Infinity":void 0:void 0;return Q.issues.push({expected:"number",code:"invalid_type",input:G,inst:X,...Z?{received:Z}:{}}),Q}}),QP=H0("$ZodNumberFormat",(X,Y)=>{zy.init(X,Y),Yz.init(X,Y)}),AH=H0("$ZodBoolean",(X,Y)=>{a4.init(X,Y),X._zod.pattern=Ky,X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=Boolean(Q.value)}catch(Z){}let G=Q.value;if(typeof G==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:G,inst:X}),Q}}),Qz=H0("$ZodBigInt",(X,Y)=>{a4.init(X,Y),X._zod.pattern=Zy,X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=BigInt(Q.value)}catch(G){}if(typeof Q.value==="bigint")return Q;return Q.issues.push({expected:"bigint",code:"invalid_type",input:Q.value,inst:X}),Q}}),JP=H0("$ZodBigIntFormat",(X,Y)=>{By.init(X,Y),Qz.init(X,Y)}),GP=H0("$ZodSymbol",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q,J)=>{let G=Q.value;if(typeof G==="symbol")return Q;return Q.issues.push({expected:"symbol",code:"invalid_type",input:G,inst:X}),Q}}),WP=H0("$ZodUndefined",(X,Y)=>{a4.init(X,Y),X._zod.pattern=Fy,X._zod.values=new Set([void 0]),X._zod.optin="optional",X._zod.optout="optional",X._zod.parse=(Q,J)=>{let G=Q.value;if(typeof G>"u")return Q;return Q.issues.push({expected:"undefined",code:"invalid_type",input:G,inst:X}),Q}}),ZP=H0("$ZodNull",(X,Y)=>{a4.init(X,Y),X._zod.pattern=Hy,X._zod.values=new Set([null]),X._zod.parse=(Q,J)=>{let G=Q.value;if(G===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:G,inst:X}),Q}}),$P=H0("$ZodAny",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q)=>Q}),KP=H0("$ZodUnknown",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q)=>Q}),HP=H0("$ZodNever",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q,J)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:X}),Q}}),FP=H0("$ZodVoid",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q,J)=>{let G=Q.value;if(typeof G>"u")return Q;return Q.issues.push({expected:"void",code:"invalid_type",input:G,inst:X}),Q}}),VP=H0("$ZodDate",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q,J)=>{if(Y.coerce)try{Q.value=new Date(Q.value)}catch($){}let G=Q.value,Z=G instanceof Date;if(Z&&!Number.isNaN(G.getTime()))return Q;return Q.issues.push({expected:"date",code:"invalid_type",input:G,...Z?{received:"Invalid Date"}:{},inst:X}),Q}});qP=H0("$ZodArray",(X,Y)=>{a4.init(X,Y),X._zod.parse=(Q,J)=>{let G=Q.value;if(!Array.isArray(G))return Q.issues.push({expected:"array",code:"invalid_type",input:G,inst:X}),Q;Q.value=Array(G.length);let Z=[];for(let W=0;W<G.length;W++){let $=G[W],K=Y.element._zod.run({value:$,issues:[]},J);if(K instanceof Promise)Z.push(K.then((H)=>O80(H,Q,W)));else O80(K,Q,W)}if(Z.length)return Promise.all(Z).then(()=>Q);return Q}});UP=H0("$ZodObject",(X,Y)=>{if(a4.init(X,Y),!Object.getOwnPropertyDescriptor(Y,"shape")?.get){let $=Y.shape;Object.defineProperty(Y,"shape",{get:()=>{let K={...$};return Object.defineProperty(Y,"shape",{value:K}),K}})}let J=BH(()=>v80(Y));$6(X._zod,"propValues",()=>{let $=Y.shape,K={};for(let H in $){let F=$[H]._zod;if(F.values){K[H]??(K[H]=new Set);for(let V of F.values)K[H].add(V)}}return K});let G=L$,Z=Y.catchall,W;X._zod.parse=($,K)=>{W??(W=J.value);let H=$.value;if(!G(H))return $.issues.push({expected:"object",code:"invalid_type",input:H,inst:X}),$;$.value={};let F=[],V=W.shape;for(let q of W.keys){let z=V[q],B=z._zod.optout==="optional",N=z._zod.run({value:H[q],issues:[]},K);if(N instanceof Promise)F.push(N.then((L)=>yM(L,$,q,H,B)));else yM(N,$,q,H,B)}if(!Z)return F.length?Promise.all(F).then(()=>$):$;return k80(F,H,$,K,J.value,X)}}),gy=H0("$ZodObjectJIT",(X,Y)=>{UP.init(X,Y);let Q=X._zod.parse,J=BH(()=>v80(Y)),G=(q)=>{let z=new RM(["shape","payload","ctx"]),B=J.value,N=(I)=>{let A=VM(I);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};z.write("const input = payload.value;");let L=Object.create(null),w=0;for(let I of B.keys)L[I]=`key_${w++}`;z.write("const newResult = {};");for(let I of B.keys){let A=L[I],T=VM(I),R=q[I]?._zod?.optout==="optional";if(z.write(`const ${A} = ${N(I)};`),R)z.write(`
@@ -257,7 +257,7 @@ data:
257
257
  `;if(J)G+=`id: ${J}
258
258
  `;return G+=`data: ${JSON.stringify(Q)}
259
259
 
260
- `,X.enqueue(Y.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(X,Y){try{let Q=X.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=X.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(X.headers.entries())},W;if(Y?.parsedBody!==void 0)W=Y.parsedBody;else try{W=await X.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let Z;try{if(Array.isArray(W))Z=W.map((L)=>TQ.parse(L));else Z=[TQ.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(Oa);if($){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(Z.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!$){let L=this.validateSession(X);if(L)return L;let w=this.validateProtocolVersion(X);if(w)return w}if(!Z.some(TG)){for(let L of Z)this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=Z.find((L)=>Oa(L)),V=F?F.params.protocolVersion:X.headers.get("mcp-protocol-version")??_h0;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let w of Z)if(TG(w))this._requestToStreamMapping.set(w.id,H);for(let w of Z)this.onmessage?.(w,{authInfo:Y?.authInfo,requestInfo:G})});let q=new TextEncoder,B,D=new ReadableStream({start:(L)=>{B=L},cancel:()=>{this._streamMapping.delete(H)}}),N={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)N["mcp-session-id"]=this.sessionId;for(let L of Z)if(TG(L))this._streamMapping.set(H,{controller:B,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{B.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(B,q,H,V);for(let L of Z){let w,C;if(TG(L)&&this._eventStore&&V>="2025-11-25")w=()=>{this.closeSSEStream(L.id)},C=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:C})}return new Response(D,{status:200,headers:N})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(X){let Y=this.validateSession(X);if(Y)return Y;let Q=this.validateProtocolVersion(X);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(X){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Y=X.headers.get("mcp-session-id");if(!Y)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Y!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(X){let Y=X.headers.get("mcp-protocol-version");if(Y!==null&&!sH.includes(Y))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Y} (supported versions: ${sH.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:X})=>{X()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(X){let Y=this._requestToStreamMapping.get(X);if(!Y)return;let Q=this._streamMapping.get(Y);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let X=this._streamMapping.get(this._standaloneSseStreamId);if(X)X.cleanup()}async send(X,Y){let Q=Y?.relatedRequestId;if(U5(X)||hq(X))Q=X.id;if(Q===void 0){if(U5(X)||hq(X))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let W;if(this._eventStore)W=await this._eventStore.storeEvent(this._standaloneSseStreamId,X);let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z===void 0)return;if(Z.controller&&Z.encoder)this.writeSSEEvent(Z.controller,Z.encoder,X,W);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let W;if(this._eventStore)W=await this._eventStore.storeEvent(J,X);this.writeSSEEvent(G.controller,G.encoder,X,W)}if(U5(X)||hq(X)){this._requestResponseMap.set(Q,X);let W=Array.from(this._requestToStreamMapping.entries()).filter(([$,K])=>K===J).map(([$])=>$);if(W.every(($)=>this._requestResponseMap.has($))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let $={"Content-Type":"application/json"};if(this.sessionId!==void 0)$["mcp-session-id"]=this.sessionId;let K=W.map((H)=>this._requestResponseMap.get(H));if(K.length===1)G.resolveJson(new Response(JSON.stringify(K[0]),{status:200,headers:$}));else G.resolveJson(new Response(JSON.stringify(K),{status:200,headers:$}))}else G.cleanup();for(let $ of W)this._requestResponseMap.delete($),this._requestToStreamMapping.delete($)}}}}var Nb=u(()=>{qX()});var RP=(...X)=>{return function(Q,J){let G=(W)=>{let Z=X[W];if(!Z)return J();return Z(Q,()=>G(W+1))};return G(0)}};class eQ1{config;tools=[];callToolMiddlewares=[];jsonSchemaCache=new Map;constructor(X){this.config={...X,capabilities:X.capabilities??{tools:{}}}}getCachedJsonSchema(X){let Y=this.jsonSchemaCache.get(X);if(!Y)Y=U.toJSONSchema(X),this.jsonSchemaCache.set(X,Y);return Y}withTool(X){return this.tools.push(X),this}withTools(X){return this.tools.push(...X),this}callToolMiddleware(...X){return this.callToolMiddlewares.push(...X),this}build(){let X=this.callToolMiddlewares.length>0?RP(...this.callToolMiddlewares):null,Y=()=>{let Q=new LF({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=X?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await X(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:U.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:U.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((Z)=>Z.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:this.getCachedJsonSchema(Q.inputSchema),outputSchema:Q.outputSchema?this.getCachedJsonSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new wF({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});await Y().connect(J);try{return await J.handleRequest(Q)}finally{try{await J.close?.()}catch{}}}}}}function XJ1(X){return new eQ1(X)}var YJ1=u(()=>{Db();Nb();c0()});var Ob="user-sandbox",QJ1="Create embeddable integration flows for platform end-users";import{sql as SP}from"kysely";var JJ1;var GJ1=u(()=>{JJ1={name:"001-user-sandbox",async up(X){await X.schema.createTable("user_sandbox").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Y)=>Y.notNull()).addColumn("description","text").addColumn("icon","text").addColumn("required_apps","text",(Y)=>Y.notNull()).addColumn("redirect_url","text").addColumn("webhook_url","text").addColumn("event_type","text",(Y)=>Y.notNull().defaultTo("integration.completed")).addColumn("agent_title_template","text",(Y)=>Y.notNull().defaultTo("Agent for {{externalUserId}}")).addColumn("agent_instructions","text").addColumn("tool_selection_mode","text",(Y)=>Y.notNull().defaultTo("inclusion")).addColumn("status","text",(Y)=>Y.notNull().defaultTo("active")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Y)=>Y.references("user.id").onDelete("set null")).execute(),await X.schema.createIndex("idx_user_sandbox_org").on("user_sandbox").column("organization_id").execute(),await X.schema.createTable("user_sandbox_sessions").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("template_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("status","text",(Y)=>Y.notNull().defaultTo("pending")).addColumn("app_statuses","text",(Y)=>Y.notNull().defaultTo("{}")).addColumn("created_agent_id","text",(Y)=>Y.references("connections.id").onDelete("set null")).addColumn("redirect_url","text").addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("expires_at","text",(Y)=>Y.notNull()).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_template").on("user_sandbox_sessions").column("template_id").execute(),await X.schema.createIndex("idx_user_sandbox_sessions_external_user").on("user_sandbox_sessions").columns(["template_id","external_user_id"]).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_org").on("user_sandbox_sessions").column("organization_id").execute(),await X.schema.createTable("user_sandbox_agents").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("user_sandbox_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("connection_id","text",(Y)=>Y.notNull().references("connections.id").onDelete("cascade")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).execute(),await X.schema.createIndex("idx_user_sandbox_agents_unique").on("user_sandbox_agents").columns(["user_sandbox_id","external_user_id"]).unique().execute(),await X.schema.createIndex("idx_user_sandbox_agents_connection").on("user_sandbox_agents").column("connection_id").execute()},async down(X){await X.schema.dropIndex("idx_user_sandbox_agents_connection").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_agents_unique").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_org").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_external_user").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_template").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_org").ifExists().execute(),await X.schema.dropTable("user_sandbox_agents").ifExists().execute(),await X.schema.dropTable("user_sandbox_sessions").ifExists().execute(),await X.schema.dropTable("user_sandbox").ifExists().execute()}}});var WJ1;var ZJ1=u(()=>{GJ1();WJ1=[JJ1]});function Lb(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}class kP{db;constructor(X){this.db=X}async create(X){let Y=Lb("usb"),Q=new Date().toISOString(),J={id:Y,organization_id:X.organization_id,title:X.title,description:X.description??null,icon:X.icon??null,required_apps:JSON.stringify(X.required_apps),redirect_url:X.redirect_url??null,webhook_url:X.webhook_url??null,event_type:X.event_type??"integration.completed",agent_title_template:X.agent_title_template??"{{externalUserId}}'s Agent",agent_instructions:X.agent_instructions??null,tool_selection_mode:X.tool_selection_mode??"inclusion",status:"active",created_at:Q,updated_at:Q,created_by:X.created_by??null};await this.db.insertInto("user_sandbox").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create user sandbox with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async list(X){return(await this.db.selectFrom("user_sandbox").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.icon!==void 0)J.icon=Y.icon;if(Y.required_apps!==void 0)J.required_apps=JSON.stringify(Y.required_apps);if(Y.redirect_url!==void 0)J.redirect_url=Y.redirect_url;if(Y.webhook_url!==void 0)J.webhook_url=Y.webhook_url;if(Y.event_type!==void 0)J.event_type=Y.event_type;if(Y.agent_title_template!==void 0)J.agent_title_template=Y.agent_title_template;if(Y.agent_instructions!==void 0)J.agent_instructions=Y.agent_instructions;if(Y.tool_selection_mode!==void 0)J.tool_selection_mode=Y.tool_selection_mode;if(Y.status!==void 0)J.status=Y.status;await this.db.updateTable("user_sandbox").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Template not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox").where("id","=",X).execute()}deserialize(X){let Y=[];try{Y=JSON.parse(X.required_apps)}catch{Y=[]}return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,icon:X.icon,required_apps:Y,redirect_url:X.redirect_url,webhook_url:X.webhook_url,event_type:X.event_type,agent_title_template:X.agent_title_template,agent_instructions:X.agent_instructions,tool_selection_mode:X.tool_selection_mode,status:X.status,created_at:X.created_at,updated_at:X.updated_at,created_by:X.created_by}}}var v80=()=>{};class vP{db;constructor(X){this.db=X}async create(X){let Y=Lb("uss"),Q=new Date().toISOString(),J={id:Y,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:"pending",app_statuses:"{}",created_agent_id:X.created_agent_id??null,redirect_url:X.redirect_url??null,created_at:Q,updated_at:Q,expires_at:X.expires_at};await this.db.insertInto("user_sandbox_sessions").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create session with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async findExisting(X,Y){let Q=new Date().toISOString(),J=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).where("external_user_id","=",Y).where("expires_at",">",Q).where("status","!=","completed").orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return this.deserialize(J)}async listByTemplate(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async listByOrganization(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.status!==void 0)J.status=Y.status;if(Y.app_statuses!==void 0)J.app_statuses=JSON.stringify(Y.app_statuses);if(Y.created_agent_id!==void 0)J.created_agent_id=Y.created_agent_id;await this.db.updateTable("user_sandbox_sessions").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Session not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox_sessions").where("id","=",X).execute()}async deleteExpired(){let X=new Date().toISOString(),Y=await this.db.deleteFrom("user_sandbox_sessions").where("expires_at","<",X).where("status","!=","completed").executeTakeFirst();return Number(Y.numDeletedRows??0)}deserialize(X){let Y={};try{Y=JSON.parse(X.app_statuses)}catch{Y={}}return{id:X.id,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:X.status,app_statuses:Y,created_agent_id:X.created_agent_id,redirect_url:X.redirect_url,created_at:X.created_at,updated_at:X.updated_at,expires_at:X.expires_at}}}var _80=()=>{};function _P(X){y80=X}function KQ(){if(!y80)throw Error(`Plugin storage not initialized. Make sure the "${Ob}" plugin is enabled.`);return y80}function b80(){return process.env.MESH_PUBLIC_URL||"http://localhost:3000"}var y80=null;var z7=()=>{};function $J1(X){let Y=X.db,Q={templates:new kP(Y),sessions:new vP(Y)};return _P(Q),Q}var KJ1=u(()=>{v80();_80();z7()});var Nb6,Ob6,Lb6,wb6,Mb6,UK,Pb6,HJ1,FJ1,VJ1,qJ1,UJ1,BJ1,zJ1,DJ1,NJ1,OJ1,LJ1,Tb6,wJ1;var aW=u(()=>{c0();Nb6=U.object({authorizationEndpoint:U.string().describe("OAuth authorization endpoint URL"),tokenEndpoint:U.string().describe("OAuth token endpoint URL"),clientId:U.string().describe("OAuth client ID"),scopes:U.array(U.string()).describe("OAuth scopes to request"),grantType:U.enum(["authorization_code","client_credentials"]).describe("OAuth grant type")}),Ob6=U.object({headers:U.record(U.string(),U.string()).optional().describe("HTTP headers")}),Lb6=U.object({command:U.string().describe("Command to run"),args:U.array(U.string()).optional().describe("Command arguments"),cwd:U.string().optional().describe("Working directory"),envVars:U.record(U.string(),U.string()).optional().describe("Environment variables")}),wb6=U.object({app_name:U.string().describe("App name from registry (e.g., '@deco/gmail')"),title:U.string().describe("Display title for the app"),description:U.string().nullable().optional().describe("App description"),icon:U.string().nullable().optional().describe("Icon URL"),connection_type:U.enum(["HTTP","SSE","Websocket","STDIO"]).describe("Connection type"),connection_url:U.string().nullable().optional().describe("MCP server URL"),connection_headers:U.union([Ob6,Lb6]).nullable().optional().describe("Connection parameters"),oauth_config:Nb6.nullable().optional().describe("OAuth configuration if required"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tools to expose (null = all)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resources to expose (null = all)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompts to expose (null = all)")}),Mb6=U.object({configured:U.boolean().describe("Whether the app has been configured"),connection_id:U.string().nullable().describe("Connection ID if created"),error:U.string().nullable().describe("Error message if configuration failed")}),UK=U.object({id:U.string(),organization_id:U.string(),title:U.string(),description:U.string().nullable(),icon:U.string().nullable(),required_apps:U.array(wb6),redirect_url:U.string().nullable(),webhook_url:U.string().nullable(),event_type:U.string(),agent_title_template:U.string(),agent_instructions:U.string().nullable(),tool_selection_mode:U.enum(["inclusion","exclusion"]),status:U.enum(["active","inactive"]),created_at:U.string(),updated_at:U.string(),created_by:U.string().nullable()}),Pb6=U.object({id:U.string(),template_id:U.string(),organization_id:U.string(),external_user_id:U.string(),status:U.enum(["pending","in_progress","completed"]),app_statuses:U.record(U.string(),Mb6),created_agent_id:U.string().nullable(),redirect_url:U.string().nullable(),created_at:U.string(),updated_at:U.string(),expires_at:U.string()}),HJ1=U.object({app_name:U.string().describe("App name from registry (e.g., '@deco/openrouter')"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tools to expose (null = all)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resources to expose (null = all)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompts to expose (null = all)")}),FJ1=U.object({title:U.string().describe("Title for the template"),description:U.string().optional().describe("Optional description"),icon:U.string().optional().describe("Optional icon URL"),registry_id:U.string().describe("Connection ID of the registry to look up apps from"),required_apps:U.array(HJ1).describe("Apps to include - only app_name required, details fetched from registry"),redirect_url:U.string().optional().describe("URL to redirect to after completion"),webhook_url:U.string().optional().describe("Webhook URL to call on completion"),event_type:U.string().optional().describe("Event type to emit (default: integration.completed)"),agent_title_template:U.string().optional().describe("Template for agent title (supports {{externalUserId}})"),agent_instructions:U.string().optional().describe("Instructions for the created agent"),tool_selection_mode:U.enum(["inclusion","exclusion"]).optional().describe("Tool selection mode for the agent")}),VJ1=U.object({id:U.string().describe("Template ID to update"),title:U.string().optional(),description:U.string().nullable().optional(),icon:U.string().nullable().optional(),registry_id:U.string().optional().describe("Connection ID of the registry (required if updating required_apps)"),required_apps:U.array(HJ1).optional().describe("Updated apps (details will be fetched from registry)"),redirect_url:U.string().nullable().optional(),webhook_url:U.string().nullable().optional(),event_type:U.string().optional(),agent_title_template:U.string().optional(),agent_instructions:U.string().nullable().optional(),tool_selection_mode:U.enum(["inclusion","exclusion"]).optional(),status:U.enum(["active","inactive"]).optional()}),qJ1=U.object({id:U.string().describe("Template ID")}),UJ1=U.object({}),BJ1=U.object({id:U.string().describe("Template ID to delete")}),zJ1=U.object({templateId:U.string().describe("Template ID"),externalUserId:U.string().describe("External user ID from your platform"),expiresInSeconds:U.number().optional().describe("Session expiration in seconds (default: 7 days)")}),DJ1=U.object({sessionId:U.string().describe("Session ID"),url:U.string().describe("URL for the connect flow"),expiresAt:U.string().describe("Session expiration time"),agentId:U.string().nullable().optional().describe("Virtual MCP ID for this user (unique per template + user)")}),NJ1=U.object({templateId:U.string().optional().describe("Filter by template ID")}),OJ1=U.object({sessions:U.array(Pb6)}),LJ1=U.object({externalUserId:U.string().describe("External user ID to find agents for")}),Tb6=U.object({id:U.string().describe("Agent (Virtual MCP) ID"),title:U.string(),external_user_id:U.string(),template_id:U.string().nullable(),created_at:U.string()}),wJ1=U.object({agents:U.array(Tb6)})});function Eb6(X){if(!X?.url)return null;try{let Y=new URL(X.url);if(Y.hostname==="github.com"){let Q=Y.pathname.split("/").filter(Boolean);if(Q.length>=1)return`https://github.com/${Q[0]}.png`}}catch{}return null}function jb6(X){return X.find((Q)=>Q.name.endsWith("_LIST"))?.name??null}function Cb6(X){if(!X)return[];if(Array.isArray(X))return X;if(typeof X==="object"&&X!==null){let Y=Object.keys(X).find((Q)=>Array.isArray(X[Q]));if(Y)return X[Y]}return[]}function Ib6(X,Y,Q,J){let G=X.server,W=X._meta?.["mcp.mesh"],Z=W?.friendlyName||W?.friendly_name||X.title||G?.title||G?.name||"Unnamed MCP Server",$=G?.description||null,K=G?.icons?.[0]?.src||Eb6(G?.repository)||null,H=W?.oauth_config,F=H&&typeof H.authorizationEndpoint==="string"&&typeof H.tokenEndpoint==="string"&&typeof H.clientId==="string"&&Array.isArray(H.scopes)&&(H.grantType==="authorization_code"||H.grantType==="client_credentials")?{authorizationEndpoint:H.authorizationEndpoint,tokenEndpoint:H.tokenEndpoint,clientId:H.clientId,scopes:H.scopes,grantType:H.grantType}:null,V=G?.packages??[],q=G?.remotes??[],B,D,N=null,L=q[0],w=V[0];if(L){if(B=Ab6[L.type??""]??L.type?.toUpperCase()??"HTTP",D=L.url??null,L.headers&&L.headers.length>0){let C={};for(let T of L.headers)if(T.name&&T.value)C[T.name]=T.value;if(Object.keys(C).length>0)N={headers:C}}}else if(w){B="STDIO",D=null;let C=w.identifier||w.name,T={};if(w.environmentVariables){for(let A of w.environmentVariables)if(A.name)T[A.name]=""}N={command:"npx",args:C?["-y",C]:[],...Object.keys(T).length>0&&{envVars:T}}}else B="HTTP",D=null;return{title:Z,description:$,icon:K,connection_type:B,connection_url:D,connection_headers:N,oauth_config:F,selected_tools:Y,selected_resources:Q,selected_prompts:J}}async function Rb6(X,Y,Q,J=null,G=null,W=null){let Z=await X.createMCPProxy(Y),$=await Z.client.listTools(),K=jb6($.tools);if(!K)throw Error(`Registry "${Y}" does not have a LIST tool`);let H=await Z.client.callTool({name:K,arguments:{where:{appName:Q}}}),F=H.structuredContent??H,q=Cb6(F)[0];if(!q)throw Error(`App "${Q}" not found in registry "${Y}"`);let B=Ib6(q,J,G,W);return{app_name:Q,...B}}async function wb(X,Y,Q){let J=[];for(let G of Q){let W=await Rb6(X,Y,G.app_name,G.selected_tools??null,G.selected_resources??null,G.selected_prompts??null);J.push(W)}return J}var Ab6;var f80=u(()=>{Ab6={"streamable-http":"HTTP",http:"HTTP",sse:"SSE",stdio:"STDIO",websocket:"Websocket"}});var MJ1;var PJ1=u(()=>{aW();z7();f80();MJ1={name:"USER_SANDBOX_CREATE",description:"Create a new user sandbox for platform integration flows. Specify apps by name and the system will automatically fetch connection details from the registry.",inputSchema:FJ1,outputSchema:UK,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=await wb(J,Q.registry_id,Q.required_apps.map(($)=>({app_name:$.app_name,selected_tools:$.selected_tools??null,selected_resources:$.selected_resources??null,selected_prompts:$.selected_prompts??null})));return await KQ().templates.create({organization_id:J.organization.id,title:Q.title,description:Q.description??null,icon:Q.icon??null,required_apps:G,redirect_url:Q.redirect_url??null,webhook_url:Q.webhook_url??null,event_type:Q.event_type,agent_title_template:Q.agent_title_template,agent_instructions:Q.agent_instructions??null,tool_selection_mode:Q.tool_selection_mode,created_by:J.auth.user?.id??null})}}});var TJ1;var AJ1=u(()=>{aW();z7();f80();TJ1={name:"USER_SANDBOX_UPDATE",description:"Update an existing user sandbox. If updating required_apps, provide registry_id to auto-fetch details.",inputSchema:VJ1,outputSchema:UK,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W=await G.templates.findById(Q.id);if(!W)throw Error(`Template not found: ${Q.id}`);if(W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");let Z=void 0;if(Q.required_apps&&Q.required_apps.length>0){if(!Q.registry_id)throw Error("registry_id is required when updating required_apps");Z=await wb(J,Q.registry_id,Q.required_apps.map((K)=>({app_name:K.app_name,selected_tools:K.selected_tools??null,selected_resources:K.selected_resources??null,selected_prompts:K.selected_prompts??null})))}return await G.templates.update(Q.id,{title:Q.title,description:Q.description,icon:Q.icon,required_apps:Z,redirect_url:Q.redirect_url,webhook_url:Q.webhook_url,event_type:Q.event_type,agent_title_template:Q.agent_title_template,agent_instructions:Q.agent_instructions,tool_selection_mode:Q.tool_selection_mode,status:Q.status})}}});var EJ1;var jJ1=u(()=>{c0();aW();z7();EJ1={name:"USER_SANDBOX_DELETE",description:"Delete a user sandbox",inputSchema:BJ1,outputSchema:U.object({success:U.boolean(),id:U.string()}),handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W=await G.templates.findById(Q.id);if(!W)throw Error(`Template not found: ${Q.id}`);if(W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");return await G.templates.delete(Q.id),{success:!0,id:Q.id}}}});var CJ1;var IJ1=u(()=>{c0();aW();z7();CJ1={name:"USER_SANDBOX_LIST",description:"List all user sandbox in the organization",inputSchema:UJ1,outputSchema:U.object({templates:U.array(UK)}),handler:async(X,Y)=>{let Q=Y;if(!Q.organization)throw Error("Organization context required");return await Q.access.check(),{templates:await KQ().templates.list(Q.organization.id)}}}});var RJ1;var SJ1=u(()=>{aW();z7();RJ1={name:"USER_SANDBOX_GET",description:"Get a user sandbox by ID",inputSchema:qJ1,outputSchema:UK.nullable(),handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let W=await KQ().templates.findById(Q.id);if(W&&W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");return W}}});async function kJ1(X,Y){let Q=await Y.sessions.findById(X);if(!Q)throw new rW("Session not found","SESSION_NOT_FOUND");if(new Date(Q.expires_at)<new Date)throw new rW("Session has expired","SESSION_EXPIRED");return Q}async function Sb6(X,Y){let Q=await kJ1(X,Y);if(Q.status==="completed")throw new rW("Session is already completed. Create a new session to reconfigure.","SESSION_COMPLETED");return Q}function kb6(X,Y){let Q=X.metadata;if(!Q)throw new rW("Connection has no metadata","CONNECTION_ACCESS_DENIED");let J=Q[BK.SESSION_ID]===Y.id,G=Q[BK.EXTERNAL_USER_ID]===Y.external_user_id&&Q[BK.TEMPLATE_ID]===Y.template_id;if(!J&&!G)throw new rW("Access denied: connection does not belong to this session","CONNECTION_ACCESS_DENIED")}function h80(X,Y,Q){return{[BK.SESSION_ID]:X,[BK.EXTERNAL_USER_ID]:Y,[BK.TEMPLATE_ID]:Q,source:"user-sandbox"}}function x80(X,Y){return{[BK.EXTERNAL_USER_ID]:X,[BK.TEMPLATE_ID]:Y,source:"user-sandbox"}}async function Jz(X,Y,Q){let J=Q?.allowCompleted?await kJ1(X,Y):await Sb6(X,Y);if(Q?.connection)kb6(Q.connection,J);return J}var BK,rW;var vJ1=u(()=>{BK={SESSION_ID:"user_sandbox_session_id",EXTERNAL_USER_ID:"user_sandbox_external_user_id",TEMPLATE_ID:"user_sandbox_id"};rW=class rW extends Error{code;constructor(X,Y){super(X);this.code=Y;this.name="SessionAccessError"}}});var g80=u(()=>{vJ1()});async function _b6(X,Y,Q,J,G,W,Z,$){let K=X,H=await K.selectFrom("user_sandbox_agents").select("connection_id").where("user_sandbox_id","=",J).where("external_user_id","=",G).executeTakeFirst();if(H)return H.connection_id;let F=new Date().toISOString(),V=`usa_${Date.now().toString(36)}${crypto.randomUUID().replace(/-/g,"").substring(0,8)}`,q=`vir_${Date.now().toString(36)}${crypto.randomUUID().replace(/-/g,"").substring(0,8)}`;try{return await K.transaction().execute(async(B)=>{await B.insertInto("connections").values({id:q,organization_id:Y,created_by:Q,title:W,description:Z,icon:null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${q}`,connection_token:null,connection_headers:JSON.stringify({tool_selection_mode:$}),oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:JSON.stringify(x80(G,J)),tools:null,bindings:null,status:"active",created_at:F,updated_at:F}).execute(),await B.insertInto("user_sandbox_agents").values({id:V,user_sandbox_id:J,external_user_id:G,connection_id:q,created_at:F}).execute()}),q}catch(B){let D=String(B);if(D.includes("UNIQUE constraint")||D.includes("duplicate key")){let N=await K.selectFrom("user_sandbox_agents").select("connection_id").where("user_sandbox_id","=",J).where("external_user_id","=",G).executeTakeFirst();if(N)return N.connection_id}throw B}}var vb6=604800,_J1;var yJ1=u(()=>{aW();z7();g80();_J1={name:"USER_SANDBOX_CREATE_SESSION",description:"Create a connect session URL for an external user. Returns a URL that the user can visit to configure their integrations. Also creates a unique Virtual MCP (agent) for this user if one doesn't exist.",inputSchema:zJ1,outputSchema:DJ1,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W=await G.templates.findById(Q.templateId);if(!W)throw Error(`Template not found: ${Q.templateId}`);if(W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");if(W.status!=="active")throw Error("Template is not active");let Z=await G.sessions.findExisting(Q.templateId,Q.externalUserId);if(Z){let D=b80();return{sessionId:Z.id,url:`${D}/connect/${Z.id}`,expiresAt:Z.expires_at,agentId:Z.created_agent_id}}let $=W.agent_title_template.replace("{{externalUserId}}",Q.externalUserId),K=W.created_by??J.auth.user?.id??"system",H=await _b6(J.db,J.organization.id,K,W.id,Q.externalUserId,$,W.agent_instructions,W.tool_selection_mode),F=Q.expiresInSeconds??vb6,V=new Date(Date.now()+F*1000).toISOString(),q=await G.sessions.create({template_id:Q.templateId,organization_id:J.organization.id,external_user_id:Q.externalUserId,redirect_url:W.redirect_url,expires_at:V,created_agent_id:H}),B=b80();return{sessionId:q.id,url:`${B}/connect/${q.id}`,expiresAt:q.expires_at,agentId:H}}}});var bJ1;var fJ1=u(()=>{aW();z7();bJ1={name:"USER_SANDBOX_LIST_SESSIONS",description:"List connect sessions for monitoring and management",inputSchema:NJ1,outputSchema:OJ1,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W;if(Q.templateId){let Z=await G.templates.findById(Q.templateId);if(!Z)throw Error(`Template not found: ${Q.templateId}`);if(Z.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");W=await G.sessions.listByTemplate(Q.templateId)}else W=await G.sessions.listByOrganization(J.organization.id);return{sessions:W}}}});var yb6="user_sandbox_external_user_id",bb6="user_sandbox_id",hJ1;var xJ1=u(()=>{aW();hJ1={name:"USER_SANDBOX_LIST_USER_AGENTS",description:"List all agents (Virtual MCPs) created for an external user. Use this to find agents created via user sandbox for a specific user in your platform.",inputSchema:LJ1,outputSchema:wJ1,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");return await J.access.check(),{agents:(await J.storage.connections.list(J.organization.id)).filter((Z)=>{if(Z.connection_type!=="VIRTUAL")return!1;let $=Z.metadata;if(!$)return!1;return $[yb6]===Q.externalUserId}).map((Z)=>{let $=Z.metadata;return{id:Z.id,title:Z.title,external_user_id:Q.externalUserId,template_id:$[bb6]??null,created_at:Z.created_at}})}}}});var gJ1;var uJ1=u(()=>{PJ1();AJ1();jJ1();IJ1();SJ1();yJ1();fJ1();xJ1();z7();gJ1=[MJ1,TJ1,EJ1,CJ1,RJ1,_J1,bJ1,hJ1]});function fb6(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}async function u80(X,Y,Q,J){let G={success:!1,agentId:X.created_agent_id,connectionIds:[],redirectUrl:null,eventEmitted:!1,webhookCalled:!1};try{let W=J.db,Z=new Date().toISOString(),$=X.created_agent_id;if(!$)throw Error("Session has no agent - this should not happen");let K=[],H=[];for(let[q,B]of Object.entries(X.app_statuses))if(B.configured&&B.connection_id){K.push(B.connection_id);let D=Y.required_apps.find((N)=>N.app_name===q);H.push({appName:q,connectionId:B.connection_id,selectedTools:D?.selected_tools??null,selectedResources:D?.selected_resources??null,selectedPrompts:D?.selected_prompts??null})}if(G.connectionIds=K,await W.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).execute(),H.length>0)await W.insertInto("connection_aggregations").values(H.map((q)=>({id:fb6("agg"),parent_connection_id:$,child_connection_id:q.connectionId,selected_tools:q.selectedTools?JSON.stringify(q.selectedTools):null,selected_resources:q.selectedResources?JSON.stringify(q.selectedResources):null,selected_prompts:q.selectedPrompts?JSON.stringify(q.selectedPrompts):null,created_at:Z}))).execute();await Q.sessions.update(X.id,{status:"completed"});let F={type:Y.event_type,data:{externalUserId:X.external_user_id,agentId:$,templateId:Y.id,sessionId:X.id,connections:K.map((q)=>{let B=Object.entries(X.app_statuses).find(([D,N])=>N.connection_id===q)?.[0];return{id:q,appName:B??"unknown"}})}};if(J.eventBus)try{await J.eventBus.publish(J.organizationId,"user-sandbox",F),G.eventEmitted=!0}catch(q){console.error("[UserSandbox] Failed to emit completion event:",q)}if(Y.webhook_url)try{let q=await fetch(Y.webhook_url,{method:"POST",headers:{"Content-Type":"application/json","X-User-Sandbox-Event":Y.event_type},body:JSON.stringify(F.data)});if(!q.ok)console.error("[UserSandbox] Webhook returned error:",q.status);else G.webhookCalled=!0}catch(q){console.error("[UserSandbox] Failed to call webhook:",q)}let V=X.redirect_url??Y.redirect_url;if(V){let q=new URL(V);q.searchParams.set("sessionId",X.id),q.searchParams.set("externalUserId",X.external_user_id),q.searchParams.set("agentId",$),G.redirectUrl=q.toString()}return G.success=!0,G}catch(W){throw console.error("[UserSandbox] Completion failed:",W),W}}var mJ1=()=>{};function hb6(){let X=Date.now().toString(36),Y=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`conn_${X}${Y}`}async function xb6(X,Y,Q,J,G,W,Z){let $=hb6(),K=new Date().toISOString();if(!Z.title)throw Error(`App "${Z.app_name}" is missing required field: title`);if(!Z.connection_type)throw Error(`App "${Z.app_name}" is missing required field: connection_type`);if(!Z.connection_url&&Z.connection_type!=="STDIO")throw Error(`App "${Z.app_name}" is missing required field: connection_url`);let H={id:$,organization_id:Y,created_by:Q,title:Z.title,description:Z.description??null,icon:Z.icon??null,app_name:Z.app_name,app_id:null,connection_type:Z.connection_type,connection_url:Z.connection_url??"",connection_token:null,connection_headers:Z.connection_headers?JSON.stringify(Z.connection_headers):null,oauth_config:Z.oauth_config?JSON.stringify(Z.oauth_config):null,configuration_state:null,configuration_scopes:null,metadata:JSON.stringify(h80(J,G,W)),tools:null,bindings:null,status:"active",created_at:K,updated_at:K};return await X.insertInto("connections").values(H).execute(),$}function Mb(X,Y){if(Y instanceof rW){let Q={SESSION_NOT_FOUND:404,SESSION_EXPIRED:410,SESSION_COMPLETED:409,ACCESS_DENIED:403,CONNECTION_ACCESS_DENIED:403};return X.json({error:Y.message,code:Y.code},Q[Y.code]??400)}return console.error("[UserSandbox] Connect API error:",Y),X.json({error:Y instanceof Error?Y.message:"Internal error"},500)}function m80(X,Y){let Q=Y.db,J=new kP(Q),G=new vP(Q),W={templates:J,sessions:G};X.get("/api/user-sandbox/sessions/:sessionId",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Jz($,W,{allowCompleted:!0}),H=await J.findById(K.template_id);if(!H)return Z.json({error:"Template not found"},404);return Z.json({session:{id:K.id,status:K.status,external_user_id:K.external_user_id,expires_at:K.expires_at,redirect_url:K.redirect_url,created_agent_id:K.created_agent_id},template:{id:H.id,title:H.title,description:H.description,icon:H.icon},apps:H.required_apps.map((F)=>({app_name:F.app_name,title:F.title,description:F.description,icon:F.icon,connection_type:F.connection_type,requires_oauth:!!F.oauth_config,selected_tools:F.selected_tools,selected_resources:F.selected_resources,selected_prompts:F.selected_prompts,status:K.app_statuses[F.app_name]??{configured:!1,connection_id:null,error:null}}))})}catch($){return Mb(Z,$)}}),X.post("/api/user-sandbox/sessions/:sessionId/provision",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Z.req.json();if(!K.app_name)return Z.json({error:"app_name is required"},400);let H=await Jz($,W),F=await J.findById(H.template_id);if(!F)return Z.json({error:"Template not found"},404);let V=F.required_apps.find((N)=>N.app_name===K.app_name);if(!V)return Z.json({error:`App "${K.app_name}" is not required by this template`},400);let q=H.app_statuses[K.app_name];if(q?.connection_id)return Z.json({success:!0,connection_id:q.connection_id,already_provisioned:!0,requires_oauth:!!V.oauth_config});if(!F.created_by)return Z.json({error:"Template is missing created_by - cannot create connections"},500);let B=await xb6(Q,H.organization_id,F.created_by,$,H.external_user_id,H.template_id,V),D={...H.app_statuses,[K.app_name]:{configured:!1,connection_id:B,error:null}};return await G.update($,{status:"in_progress",app_statuses:D}),Z.json({success:!0,connection_id:B,already_provisioned:!1,requires_oauth:!!V.oauth_config})}catch($){return Mb(Z,$)}}),X.post("/api/user-sandbox/sessions/:sessionId/configure",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Z.req.json();if(!K.app_name)return Z.json({error:"app_name is required"},400);let H=await Jz($,W),F=await J.findById(H.template_id);if(!F)return Z.json({error:"Template not found"},404);if(!F.required_apps.find((L)=>L.app_name===K.app_name))return Z.json({error:`App "${K.app_name}" is not required by this template`},400);let q=H.app_statuses[K.app_name],D={configured:!0,connection_id:K.connection_id??q?.connection_id??null,error:null},N={...H.app_statuses,[K.app_name]:D};return await G.update($,{status:"in_progress",app_statuses:N}),Z.json({success:!0,app_name:K.app_name,status:D})}catch($){return Mb(Z,$)}}),X.post("/api/user-sandbox/sessions/:sessionId/complete",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Jz($,W),H=await J.findById(K.template_id);if(!H)return Z.json({error:"Template not found"},404);let F=H.required_apps.filter((q)=>{return!K.app_statuses[q.app_name]?.configured});if(F.length>0)return Z.json({error:"Not all required apps are configured",unconfigured:F.map((q)=>q.app_name)},400);let V=await u80(K,H,W,{organizationId:K.organization_id,db:Q});return Z.json({success:V.success,completed:!0,agentId:V.agentId,redirectUrl:V.redirectUrl,eventEmitted:V.eventEmitted,webhookCalled:V.webhookCalled})}catch($){return Mb(Z,$)}})}var lJ1=u(()=>{v80();_80();g80();mJ1()});var dJ1=u(()=>{lJ1()});var pJ1;var cJ1=u(()=>{ZJ1();KJ1();uJ1();dJ1();pJ1={id:Ob,description:QJ1,tools:gJ1,publicRoutes:(X,Y)=>{m80(X,Y)},migrations:WJ1,createStorage:(X)=>{let Y=$J1(X);return _P(Y),Y}}});var Pb;var nJ1=u(()=>{cJ1();Pb=[pJ1]});function gb6(X,Y){return iJ1.set(Y.name,X),{...Y,handler:async(Q,J)=>{let G=J.organization;if(!G)throw Error(`Organization context required for plugin tool "${Y.name}"`);if(!(await J.storage.organizationSettings.get(G.id))?.enabled_plugins?.includes(X))throw Error(`Plugin "${X}" is not enabled for this organization. Enable it in Settings > Plugins.`);return Y.handler(Q,J)},execute:async(Q,J)=>{let G=J.organization;if(!G)throw Error(`Organization context required for plugin tool "${Y.name}"`);if(!(await J.storage.organizationSettings.get(G.id))?.enabled_plugins?.includes(X))throw Error(`Plugin "${X}" is not enabled for this organization. Enable it in Settings > Plugins.`);return Y.execute(Q,J)}}}function aJ1(X,Y){return X.filter((Q)=>{let J=iJ1.get(Q.name);if(!J)return!0;return Y?.includes(J)??!1})}function rJ1(){let X=[];for(let Y of Pb){if(!Y.tools)continue;for(let Q of Y.tools){let J={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,handler:Q.handler,execute:Q.handler},G=gb6(Y.id,J);X.push(G)}}return X}function oJ1(X,Y){for(let Q of Pb){if(Q.routes){let J=new X.constructor;Q.routes(J,Y),X.route(`/api/plugins/${Q.id}`,J)}if(Q.publicRoutes)Q.publicRoutes(X,Y)}}function sJ1(X,Y){let Q={db:X,vault:{encrypt:(J)=>Y.encrypt(J),decrypt:(J)=>Y.decrypt(J)}};for(let J of Pb)if(J.createStorage){let G=J.createStorage(Q);ub6.set(J.id,G)}}var iJ1,ub6;var l80=u(()=>{nJ1();iJ1=new Map;ub6=new Map});function t0(X){return{...X,execute:async(Y,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${X.name}`,async()=>Q.tracer.startActiveSpan(`tool.${X.name}`,{attributes:{"tool.name":X.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=X.name,Q.access.setToolName?.(X.name);let W=await X.handler(Y,Q),Z=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(Z,{"tool.name":X.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":X.name,status:"success"}),G.setStatus({code:d80.SpanStatusCode.OK}),W}catch(W){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":X.name,"error.type":W.constructor.name}),G.setStatus({code:d80.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}}))}}}var d80;var Z6=u(()=>{d80=E6(K1(),1)});function _1(X){if(!X.organization)throw Error("This operation requires organization scope");return X.organization}function f8(X){return X.auth.user?.id??X.auth.apiKey?.userId}function mb6(X){return!!(X.auth.user||X.auth.apiKey)}function U1(X){if(!mb6(X))throw Error("Authentication required")}var Tb,tJ1,eJ1,X51,Y51,Q51,J51,G51,W51,Z51;var Gz=u(()=>{c0();Tb=U.record(U.string(),U.array(U.string())),tJ1=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),userId:U.string().describe("ID of the user who owns this API key"),permissions:Tb.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),eJ1=U.object({name:U.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Tb.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:U.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:U.record(U.string(),U.unknown()).optional().describe("Additional metadata to store with the API key")}),X51=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),key:U.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Tb.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),Y51=U.object({}),Q51=U.object({items:U.array(tJ1).describe("List of API keys (without key values)")}),J51=U.object({keyId:U.string().describe("ID of the API key to update"),name:U.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Tb.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:U.record(U.string(),U.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),G51=U.object({item:tJ1.describe("The updated API key (without key value)")}),W51=U.object({keyId:U.string().describe("ID of the API key to delete")}),Z51=U.object({success:U.boolean().describe("Whether the deletion was successful"),keyId:U.string().describe("ID of the deleted API key")})});var p80;var $51=u(()=>{Z6();Gz();p80=t0({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:eJ1,outputSchema:X51,handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.create({name:X.name,permissions:X.permissions,expiresIn:X.expiresIn,metadata:{...X.metadata,organization:Y.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??X.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var c80;var K51=u(()=>{Z6();Gz();c80=t0({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:W51,outputSchema:Z51,handler:async(X,Y)=>{if(U1(Y),await Y.access.check(),!f8(Y))throw Error("User ID required to delete API key");let G=(await Y.boundAuth.apiKey.list())?.find((K)=>K.id===X.keyId);if(!G)throw Error("API key not found");let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot delete API key from another organization");return await Y.boundAuth.apiKey.delete(X.keyId),{success:!0,keyId:X.keyId}}})});var n80;var H51=u(()=>{Z6();Gz();n80=t0({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:Y51,outputSchema:Q51,handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.list(),J=Y.organization?.id;return{items:(Q??[]).filter((W)=>{return W.metadata?.organization?.id===J}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt?W.expiresAt instanceof Date?W.expiresAt.toISOString():W.expiresAt:null,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var i80;var F51=u(()=>{Z6();Gz();i80=t0({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:J51,outputSchema:G51,handler:async(X,Y)=>{if(U1(Y),await Y.access.check(),!f8(Y))throw Error("User ID required to update API key");let G=(await Y.boundAuth.apiKey.list())?.find((H)=>H.id===X.keyId);if(!G)throw Error(`API key not found: ${X.keyId}`);let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot update API key from another organization");let K=await Y.boundAuth.apiKey.update({keyId:X.keyId,name:X.name,permissions:X.permissions,metadata:{...X.metadata,organization:Y.organization}});if(!K)throw Error(`Failed to update API key: ${X.keyId}`);return{item:{id:K.id,name:K.name??X.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var V51=u(()=>{$51();K51();H51();F51();Gz()});var q51,U51,B51,z51,D51,N51;var yP=u(()=>{c0();q51=U.object({query:U.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:U.number().default(10).describe("Maximum results to return (default: 10)")}),U51=U.object({query:U.string(),results:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string()})),totalAvailable:U.number()}),B51=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),z51=U.object({tools:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string(),inputSchema:U.unknown(),outputSchema:U.unknown().optional()})),notFound:U.array(U.string())}),D51=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),N51=U.object({returnValue:U.unknown().optional(),error:U.string().optional(),consoleLogs:U.array(U.object({type:U.enum(["log","warn","error"]),content:U.string()}))})});class Wz{proxies=new Map;constructor(){}static async create(X,Y){let Q=new Wz,J=await Promise.allSettled(X.map(async({connection:G,selectedTools:W,selectedResources:Z,selectedPrompts:$})=>{try{let K=await Y.createMCPProxy(G);return{connection:G,proxy:K,selectedTools:W,selectedResources:Z,selectedPrompts:$}}catch(K){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,K),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(X){return this.proxies.get(X)}entries(){return this.proxies.entries()}forEach(X){this.proxies.forEach((Y,Q)=>X(Y,Q))}async mapAsync(X){let Y=[];for(let[Q,J]of this.proxies.entries())Y.push(X(J,Q));return await Promise.all(Y)}async mapSettled(X){return Promise.allSettled(Array.from(this.proxies.entries()).map(([Y,Q])=>X(Q,Y)))}get size(){return this.proxies.size}}function O51(X){let Y=[],Q=[],J=(K)=>{let H=X.newFunction(K,(...F)=>{try{let V=F.map((q)=>X.dump(q));Y.push({type:K??"log",content:V.map(String).join(" ")})}finally{F.forEach((V)=>V.dispose())}return X.undefined});return Q.push(H),H},G=X.newObject();Q.push(G);let W=J("log"),Z=J("warn"),$=J("error");return X.setProp(G,"log",W),X.setProp(G,"warn",Z),X.setProp(G,"error",$),X.setProp(X.global,"console",G),{logs:Y,[Symbol.dispose](){Q.forEach((K)=>K.dispose())}}}var MF,a80,Ab,PF,bP;var Eb=u(()=>{MF={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},a80={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},Ab={Pending:0,Fulfilled:1,Rejected:2},PF={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},bP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function Zz(...X){XX0&&console.log("quickjs-emscripten:",...X)}function*k51(X){return yield X}function cb6(X){return k51(QX0(X))}function L51(X,Y){return(...Q)=>{let J=Y.call(X,YX0,...Q);return QX0(J)}}function nb6(X,Y){let Q=Y.call(X,YX0);return QX0(Q)}function QX0(X){function Y(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>Y(X.next(J)),(J)=>Y(X.throw(J))):Y(X.next(Q.value))}return Y(X.next())}function r80(X,Y){let Q;try{X.dispose()}catch(J){Q=J}if(Y&&Q)throw Object.assign(Y,{message:`${Y.message}
260
+ `,X.enqueue(Y.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(X,Y){try{let Q=X.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=X.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(X.headers.entries())},W;if(Y?.parsedBody!==void 0)W=Y.parsedBody;else try{W=await X.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let Z;try{if(Array.isArray(W))Z=W.map((L)=>TQ.parse(L));else Z=[TQ.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(Oa);if($){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(Z.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!$){let L=this.validateSession(X);if(L)return L;let w=this.validateProtocolVersion(X);if(w)return w}if(!Z.some(TG)){for(let L of Z)this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=Z.find((L)=>Oa(L)),V=F?F.params.protocolVersion:X.headers.get("mcp-protocol-version")??_h0;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let w of Z)if(TG(w))this._requestToStreamMapping.set(w.id,H);for(let w of Z)this.onmessage?.(w,{authInfo:Y?.authInfo,requestInfo:G})});let q=new TextEncoder,B,D=new ReadableStream({start:(L)=>{B=L},cancel:()=>{this._streamMapping.delete(H)}}),N={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)N["mcp-session-id"]=this.sessionId;for(let L of Z)if(TG(L))this._streamMapping.set(H,{controller:B,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{B.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(B,q,H,V);for(let L of Z){let w,C;if(TG(L)&&this._eventStore&&V>="2025-11-25")w=()=>{this.closeSSEStream(L.id)},C=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:C})}return new Response(D,{status:200,headers:N})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(X){let Y=this.validateSession(X);if(Y)return Y;let Q=this.validateProtocolVersion(X);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(X){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Y=X.headers.get("mcp-session-id");if(!Y)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Y!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(X){let Y=X.headers.get("mcp-protocol-version");if(Y!==null&&!sH.includes(Y))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Y} (supported versions: ${sH.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:X})=>{X()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(X){let Y=this._requestToStreamMapping.get(X);if(!Y)return;let Q=this._streamMapping.get(Y);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let X=this._streamMapping.get(this._standaloneSseStreamId);if(X)X.cleanup()}async send(X,Y){let Q=Y?.relatedRequestId;if(U5(X)||hq(X))Q=X.id;if(Q===void 0){if(U5(X)||hq(X))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let W;if(this._eventStore)W=await this._eventStore.storeEvent(this._standaloneSseStreamId,X);let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z===void 0)return;if(Z.controller&&Z.encoder)this.writeSSEEvent(Z.controller,Z.encoder,X,W);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let W;if(this._eventStore)W=await this._eventStore.storeEvent(J,X);this.writeSSEEvent(G.controller,G.encoder,X,W)}if(U5(X)||hq(X)){this._requestResponseMap.set(Q,X);let W=Array.from(this._requestToStreamMapping.entries()).filter(([$,K])=>K===J).map(([$])=>$);if(W.every(($)=>this._requestResponseMap.has($))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let $={"Content-Type":"application/json"};if(this.sessionId!==void 0)$["mcp-session-id"]=this.sessionId;let K=W.map((H)=>this._requestResponseMap.get(H));if(K.length===1)G.resolveJson(new Response(JSON.stringify(K[0]),{status:200,headers:$}));else G.resolveJson(new Response(JSON.stringify(K),{status:200,headers:$}))}else G.cleanup();for(let $ of W)this._requestResponseMap.delete($),this._requestToStreamMapping.delete($)}}}}var Nb=u(()=>{qX()});var RP=(...X)=>{return function(Q,J){let G=(W)=>{let Z=X[W];if(!Z)return J();return Z(Q,()=>G(W+1))};return G(0)}};class eQ1{config;tools=[];callToolMiddlewares=[];jsonSchemaCache=new Map;constructor(X){this.config={...X,capabilities:X.capabilities??{tools:{}}}}getCachedJsonSchema(X){let Y=this.jsonSchemaCache.get(X);if(!Y)Y=U.toJSONSchema(X),this.jsonSchemaCache.set(X,Y);return Y}withTool(X){return this.tools.push(X),this}withTools(X){return this.tools.push(...X),this}callToolMiddleware(...X){return this.callToolMiddlewares.push(...X),this}build(){let X=this.callToolMiddlewares.length>0?RP(...this.callToolMiddlewares):null,Y=()=>{let Q=new LF({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=X?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await X(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:U.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:U.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((Z)=>Z.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:this.getCachedJsonSchema(Q.inputSchema),outputSchema:Q.outputSchema?this.getCachedJsonSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new wF({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});await Y().connect(J);try{return await J.handleRequest(Q)}finally{try{await J.close?.()}catch{}}}}}}function XJ1(X){return new eQ1(X)}var YJ1=u(()=>{Db();Nb();c0()});var Ob="user-sandbox",QJ1="Create embeddable integration flows for platform end-users";import{sql as SP}from"kysely";var JJ1;var GJ1=u(()=>{JJ1={name:"001-user-sandbox",async up(X){await X.schema.createTable("user_sandbox").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Y)=>Y.notNull()).addColumn("description","text").addColumn("icon","text").addColumn("required_apps","text",(Y)=>Y.notNull()).addColumn("redirect_url","text").addColumn("webhook_url","text").addColumn("event_type","text",(Y)=>Y.notNull().defaultTo("integration.completed")).addColumn("agent_title_template","text",(Y)=>Y.notNull().defaultTo("Agent for {{externalUserId}}")).addColumn("agent_instructions","text").addColumn("tool_selection_mode","text",(Y)=>Y.notNull().defaultTo("inclusion")).addColumn("status","text",(Y)=>Y.notNull().defaultTo("active")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Y)=>Y.references("user.id").onDelete("set null")).execute(),await X.schema.createIndex("idx_user_sandbox_org").on("user_sandbox").column("organization_id").execute(),await X.schema.createTable("user_sandbox_sessions").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("template_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("organization_id","text",(Y)=>Y.notNull().references("organization.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("status","text",(Y)=>Y.notNull().defaultTo("pending")).addColumn("app_statuses","text",(Y)=>Y.notNull().defaultTo("{}")).addColumn("created_agent_id","text",(Y)=>Y.references("connections.id").onDelete("set null")).addColumn("redirect_url","text").addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).addColumn("expires_at","text",(Y)=>Y.notNull()).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_template").on("user_sandbox_sessions").column("template_id").execute(),await X.schema.createIndex("idx_user_sandbox_sessions_external_user").on("user_sandbox_sessions").columns(["template_id","external_user_id"]).execute(),await X.schema.createIndex("idx_user_sandbox_sessions_org").on("user_sandbox_sessions").column("organization_id").execute(),await X.schema.createTable("user_sandbox_agents").addColumn("id","text",(Y)=>Y.primaryKey()).addColumn("user_sandbox_id","text",(Y)=>Y.notNull().references("user_sandbox.id").onDelete("cascade")).addColumn("external_user_id","text",(Y)=>Y.notNull()).addColumn("connection_id","text",(Y)=>Y.notNull().references("connections.id").onDelete("cascade")).addColumn("created_at","text",(Y)=>Y.notNull().defaultTo(SP`CURRENT_TIMESTAMP`)).execute(),await X.schema.createIndex("idx_user_sandbox_agents_unique").on("user_sandbox_agents").columns(["user_sandbox_id","external_user_id"]).unique().execute(),await X.schema.createIndex("idx_user_sandbox_agents_connection").on("user_sandbox_agents").column("connection_id").execute()},async down(X){await X.schema.dropIndex("idx_user_sandbox_agents_connection").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_agents_unique").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_org").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_external_user").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_sessions_template").ifExists().execute(),await X.schema.dropIndex("idx_user_sandbox_org").ifExists().execute(),await X.schema.dropTable("user_sandbox_agents").ifExists().execute(),await X.schema.dropTable("user_sandbox_sessions").ifExists().execute(),await X.schema.dropTable("user_sandbox").ifExists().execute()}}});var WJ1;var ZJ1=u(()=>{GJ1();WJ1=[JJ1]});function Lb(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}class kP{db;constructor(X){this.db=X}async create(X){let Y=Lb("usb"),Q=new Date().toISOString(),J={id:Y,organization_id:X.organization_id,title:X.title,description:X.description??null,icon:X.icon??null,required_apps:JSON.stringify(X.required_apps),redirect_url:X.redirect_url??null,webhook_url:X.webhook_url??null,event_type:X.event_type??"integration.completed",agent_title_template:X.agent_title_template??"{{externalUserId}}'s Agent",agent_instructions:X.agent_instructions??null,tool_selection_mode:X.tool_selection_mode??"inclusion",status:"active",created_at:Q,updated_at:Q,created_by:X.created_by??null};await this.db.insertInto("user_sandbox").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create user sandbox with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async list(X){return(await this.db.selectFrom("user_sandbox").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.icon!==void 0)J.icon=Y.icon;if(Y.required_apps!==void 0)J.required_apps=JSON.stringify(Y.required_apps);if(Y.redirect_url!==void 0)J.redirect_url=Y.redirect_url;if(Y.webhook_url!==void 0)J.webhook_url=Y.webhook_url;if(Y.event_type!==void 0)J.event_type=Y.event_type;if(Y.agent_title_template!==void 0)J.agent_title_template=Y.agent_title_template;if(Y.agent_instructions!==void 0)J.agent_instructions=Y.agent_instructions;if(Y.tool_selection_mode!==void 0)J.tool_selection_mode=Y.tool_selection_mode;if(Y.status!==void 0)J.status=Y.status;await this.db.updateTable("user_sandbox").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Template not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox").where("id","=",X).execute()}deserialize(X){let Y=[];try{Y=JSON.parse(X.required_apps)}catch{Y=[]}return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,icon:X.icon,required_apps:Y,redirect_url:X.redirect_url,webhook_url:X.webhook_url,event_type:X.event_type,agent_title_template:X.agent_title_template,agent_instructions:X.agent_instructions,tool_selection_mode:X.tool_selection_mode,status:X.status,created_at:X.created_at,updated_at:X.updated_at,created_by:X.created_by}}}var v80=()=>{};class vP{db;constructor(X){this.db=X}async create(X){let Y=Lb("uss"),Q=new Date().toISOString(),J={id:Y,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:"pending",app_statuses:"{}",created_agent_id:X.created_agent_id??null,redirect_url:X.redirect_url??null,created_at:Q,updated_at:Q,expires_at:X.expires_at};await this.db.insertInto("user_sandbox_sessions").values(J).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create session with id: ${Y}`);return G}async findById(X){let Y=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("id","=",X).executeTakeFirst();if(!Y)return null;return this.deserialize(Y)}async findExisting(X,Y){let Q=new Date().toISOString(),J=await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).where("external_user_id","=",Y).where("expires_at",">",Q).where("status","!=","completed").orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return this.deserialize(J)}async listByTemplate(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("template_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async listByOrganization(X){return(await this.db.selectFrom("user_sandbox_sessions").selectAll().where("organization_id","=",X).orderBy("created_at","desc").execute()).map((Q)=>this.deserialize(Q))}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.status!==void 0)J.status=Y.status;if(Y.app_statuses!==void 0)J.app_statuses=JSON.stringify(Y.app_statuses);if(Y.created_agent_id!==void 0)J.created_agent_id=Y.created_agent_id;await this.db.updateTable("user_sandbox_sessions").set(J).where("id","=",X).execute();let G=await this.findById(X);if(!G)throw Error(`Session not found after update: ${X}`);return G}async delete(X){await this.db.deleteFrom("user_sandbox_sessions").where("id","=",X).execute()}async deleteExpired(){let X=new Date().toISOString(),Y=await this.db.deleteFrom("user_sandbox_sessions").where("expires_at","<",X).where("status","!=","completed").executeTakeFirst();return Number(Y.numDeletedRows??0)}deserialize(X){let Y={};try{Y=JSON.parse(X.app_statuses)}catch{Y={}}return{id:X.id,template_id:X.template_id,organization_id:X.organization_id,external_user_id:X.external_user_id,status:X.status,app_statuses:Y,created_agent_id:X.created_agent_id,redirect_url:X.redirect_url,created_at:X.created_at,updated_at:X.updated_at,expires_at:X.expires_at}}}var _80=()=>{};function _P(X){y80=X}function KQ(){if(!y80)throw Error(`Plugin storage not initialized. Make sure the "${Ob}" plugin is enabled.`);return y80}function b80(){return process.env.BASE_URL||"http://localhost:3000"}var y80=null;var z7=()=>{};function $J1(X){let Y=X.db,Q={templates:new kP(Y),sessions:new vP(Y)};return _P(Q),Q}var KJ1=u(()=>{v80();_80();z7()});var Nb6,Ob6,Lb6,wb6,Mb6,UK,Pb6,HJ1,FJ1,VJ1,qJ1,UJ1,BJ1,zJ1,DJ1,NJ1,OJ1,LJ1,Tb6,wJ1;var aW=u(()=>{c0();Nb6=U.object({authorizationEndpoint:U.string().describe("OAuth authorization endpoint URL"),tokenEndpoint:U.string().describe("OAuth token endpoint URL"),clientId:U.string().describe("OAuth client ID"),scopes:U.array(U.string()).describe("OAuth scopes to request"),grantType:U.enum(["authorization_code","client_credentials"]).describe("OAuth grant type")}),Ob6=U.object({headers:U.record(U.string(),U.string()).optional().describe("HTTP headers")}),Lb6=U.object({command:U.string().describe("Command to run"),args:U.array(U.string()).optional().describe("Command arguments"),cwd:U.string().optional().describe("Working directory"),envVars:U.record(U.string(),U.string()).optional().describe("Environment variables")}),wb6=U.object({app_name:U.string().describe("App name from registry (e.g., '@deco/gmail')"),title:U.string().describe("Display title for the app"),description:U.string().nullable().optional().describe("App description"),icon:U.string().nullable().optional().describe("Icon URL"),connection_type:U.enum(["HTTP","SSE","Websocket","STDIO"]).describe("Connection type"),connection_url:U.string().nullable().optional().describe("MCP server URL"),connection_headers:U.union([Ob6,Lb6]).nullable().optional().describe("Connection parameters"),oauth_config:Nb6.nullable().optional().describe("OAuth configuration if required"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tools to expose (null = all)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resources to expose (null = all)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompts to expose (null = all)")}),Mb6=U.object({configured:U.boolean().describe("Whether the app has been configured"),connection_id:U.string().nullable().describe("Connection ID if created"),error:U.string().nullable().describe("Error message if configuration failed")}),UK=U.object({id:U.string(),organization_id:U.string(),title:U.string(),description:U.string().nullable(),icon:U.string().nullable(),required_apps:U.array(wb6),redirect_url:U.string().nullable(),webhook_url:U.string().nullable(),event_type:U.string(),agent_title_template:U.string(),agent_instructions:U.string().nullable(),tool_selection_mode:U.enum(["inclusion","exclusion"]),status:U.enum(["active","inactive"]),created_at:U.string(),updated_at:U.string(),created_by:U.string().nullable()}),Pb6=U.object({id:U.string(),template_id:U.string(),organization_id:U.string(),external_user_id:U.string(),status:U.enum(["pending","in_progress","completed"]),app_statuses:U.record(U.string(),Mb6),created_agent_id:U.string().nullable(),redirect_url:U.string().nullable(),created_at:U.string(),updated_at:U.string(),expires_at:U.string()}),HJ1=U.object({app_name:U.string().describe("App name from registry (e.g., '@deco/openrouter')"),selected_tools:U.array(U.string()).nullable().optional().describe("Selected tools to expose (null = all)"),selected_resources:U.array(U.string()).nullable().optional().describe("Selected resources to expose (null = all)"),selected_prompts:U.array(U.string()).nullable().optional().describe("Selected prompts to expose (null = all)")}),FJ1=U.object({title:U.string().describe("Title for the template"),description:U.string().optional().describe("Optional description"),icon:U.string().optional().describe("Optional icon URL"),registry_id:U.string().describe("Connection ID of the registry to look up apps from"),required_apps:U.array(HJ1).describe("Apps to include - only app_name required, details fetched from registry"),redirect_url:U.string().optional().describe("URL to redirect to after completion"),webhook_url:U.string().optional().describe("Webhook URL to call on completion"),event_type:U.string().optional().describe("Event type to emit (default: integration.completed)"),agent_title_template:U.string().optional().describe("Template for agent title (supports {{externalUserId}})"),agent_instructions:U.string().optional().describe("Instructions for the created agent"),tool_selection_mode:U.enum(["inclusion","exclusion"]).optional().describe("Tool selection mode for the agent")}),VJ1=U.object({id:U.string().describe("Template ID to update"),title:U.string().optional(),description:U.string().nullable().optional(),icon:U.string().nullable().optional(),registry_id:U.string().optional().describe("Connection ID of the registry (required if updating required_apps)"),required_apps:U.array(HJ1).optional().describe("Updated apps (details will be fetched from registry)"),redirect_url:U.string().nullable().optional(),webhook_url:U.string().nullable().optional(),event_type:U.string().optional(),agent_title_template:U.string().optional(),agent_instructions:U.string().nullable().optional(),tool_selection_mode:U.enum(["inclusion","exclusion"]).optional(),status:U.enum(["active","inactive"]).optional()}),qJ1=U.object({id:U.string().describe("Template ID")}),UJ1=U.object({}),BJ1=U.object({id:U.string().describe("Template ID to delete")}),zJ1=U.object({templateId:U.string().describe("Template ID"),externalUserId:U.string().describe("External user ID from your platform"),expiresInSeconds:U.number().optional().describe("Session expiration in seconds (default: 7 days)")}),DJ1=U.object({sessionId:U.string().describe("Session ID"),url:U.string().describe("URL for the connect flow"),expiresAt:U.string().describe("Session expiration time"),agentId:U.string().nullable().optional().describe("Virtual MCP ID for this user (unique per template + user)")}),NJ1=U.object({templateId:U.string().optional().describe("Filter by template ID")}),OJ1=U.object({sessions:U.array(Pb6)}),LJ1=U.object({externalUserId:U.string().describe("External user ID to find agents for")}),Tb6=U.object({id:U.string().describe("Agent (Virtual MCP) ID"),title:U.string(),external_user_id:U.string(),template_id:U.string().nullable(),created_at:U.string()}),wJ1=U.object({agents:U.array(Tb6)})});function Eb6(X){if(!X?.url)return null;try{let Y=new URL(X.url);if(Y.hostname==="github.com"){let Q=Y.pathname.split("/").filter(Boolean);if(Q.length>=1)return`https://github.com/${Q[0]}.png`}}catch{}return null}function jb6(X){return X.find((Q)=>Q.name.endsWith("_LIST"))?.name??null}function Cb6(X){if(!X)return[];if(Array.isArray(X))return X;if(typeof X==="object"&&X!==null){let Y=Object.keys(X).find((Q)=>Array.isArray(X[Q]));if(Y)return X[Y]}return[]}function Ib6(X,Y,Q,J){let G=X.server,W=X._meta?.["mcp.mesh"],Z=W?.friendlyName||W?.friendly_name||X.title||G?.title||G?.name||"Unnamed MCP Server",$=G?.description||null,K=G?.icons?.[0]?.src||Eb6(G?.repository)||null,H=W?.oauth_config,F=H&&typeof H.authorizationEndpoint==="string"&&typeof H.tokenEndpoint==="string"&&typeof H.clientId==="string"&&Array.isArray(H.scopes)&&(H.grantType==="authorization_code"||H.grantType==="client_credentials")?{authorizationEndpoint:H.authorizationEndpoint,tokenEndpoint:H.tokenEndpoint,clientId:H.clientId,scopes:H.scopes,grantType:H.grantType}:null,V=G?.packages??[],q=G?.remotes??[],B,D,N=null,L=q[0],w=V[0];if(L){if(B=Ab6[L.type??""]??L.type?.toUpperCase()??"HTTP",D=L.url??null,L.headers&&L.headers.length>0){let C={};for(let T of L.headers)if(T.name&&T.value)C[T.name]=T.value;if(Object.keys(C).length>0)N={headers:C}}}else if(w){B="STDIO",D=null;let C=w.identifier||w.name,T={};if(w.environmentVariables){for(let A of w.environmentVariables)if(A.name)T[A.name]=""}N={command:"npx",args:C?["-y",C]:[],...Object.keys(T).length>0&&{envVars:T}}}else B="HTTP",D=null;return{title:Z,description:$,icon:K,connection_type:B,connection_url:D,connection_headers:N,oauth_config:F,selected_tools:Y,selected_resources:Q,selected_prompts:J}}async function Rb6(X,Y,Q,J=null,G=null,W=null){let Z=await X.createMCPProxy(Y),$=await Z.client.listTools(),K=jb6($.tools);if(!K)throw Error(`Registry "${Y}" does not have a LIST tool`);let H=await Z.client.callTool({name:K,arguments:{where:{appName:Q}}}),F=H.structuredContent??H,q=Cb6(F)[0];if(!q)throw Error(`App "${Q}" not found in registry "${Y}"`);let B=Ib6(q,J,G,W);return{app_name:Q,...B}}async function wb(X,Y,Q){let J=[];for(let G of Q){let W=await Rb6(X,Y,G.app_name,G.selected_tools??null,G.selected_resources??null,G.selected_prompts??null);J.push(W)}return J}var Ab6;var f80=u(()=>{Ab6={"streamable-http":"HTTP",http:"HTTP",sse:"SSE",stdio:"STDIO",websocket:"Websocket"}});var MJ1;var PJ1=u(()=>{aW();z7();f80();MJ1={name:"USER_SANDBOX_CREATE",description:"Create a new user sandbox for platform integration flows. Specify apps by name and the system will automatically fetch connection details from the registry.",inputSchema:FJ1,outputSchema:UK,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=await wb(J,Q.registry_id,Q.required_apps.map(($)=>({app_name:$.app_name,selected_tools:$.selected_tools??null,selected_resources:$.selected_resources??null,selected_prompts:$.selected_prompts??null})));return await KQ().templates.create({organization_id:J.organization.id,title:Q.title,description:Q.description??null,icon:Q.icon??null,required_apps:G,redirect_url:Q.redirect_url??null,webhook_url:Q.webhook_url??null,event_type:Q.event_type,agent_title_template:Q.agent_title_template,agent_instructions:Q.agent_instructions??null,tool_selection_mode:Q.tool_selection_mode,created_by:J.auth.user?.id??null})}}});var TJ1;var AJ1=u(()=>{aW();z7();f80();TJ1={name:"USER_SANDBOX_UPDATE",description:"Update an existing user sandbox. If updating required_apps, provide registry_id to auto-fetch details.",inputSchema:VJ1,outputSchema:UK,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W=await G.templates.findById(Q.id);if(!W)throw Error(`Template not found: ${Q.id}`);if(W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");let Z=void 0;if(Q.required_apps&&Q.required_apps.length>0){if(!Q.registry_id)throw Error("registry_id is required when updating required_apps");Z=await wb(J,Q.registry_id,Q.required_apps.map((K)=>({app_name:K.app_name,selected_tools:K.selected_tools??null,selected_resources:K.selected_resources??null,selected_prompts:K.selected_prompts??null})))}return await G.templates.update(Q.id,{title:Q.title,description:Q.description,icon:Q.icon,required_apps:Z,redirect_url:Q.redirect_url,webhook_url:Q.webhook_url,event_type:Q.event_type,agent_title_template:Q.agent_title_template,agent_instructions:Q.agent_instructions,tool_selection_mode:Q.tool_selection_mode,status:Q.status})}}});var EJ1;var jJ1=u(()=>{c0();aW();z7();EJ1={name:"USER_SANDBOX_DELETE",description:"Delete a user sandbox",inputSchema:BJ1,outputSchema:U.object({success:U.boolean(),id:U.string()}),handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W=await G.templates.findById(Q.id);if(!W)throw Error(`Template not found: ${Q.id}`);if(W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");return await G.templates.delete(Q.id),{success:!0,id:Q.id}}}});var CJ1;var IJ1=u(()=>{c0();aW();z7();CJ1={name:"USER_SANDBOX_LIST",description:"List all user sandbox in the organization",inputSchema:UJ1,outputSchema:U.object({templates:U.array(UK)}),handler:async(X,Y)=>{let Q=Y;if(!Q.organization)throw Error("Organization context required");return await Q.access.check(),{templates:await KQ().templates.list(Q.organization.id)}}}});var RJ1;var SJ1=u(()=>{aW();z7();RJ1={name:"USER_SANDBOX_GET",description:"Get a user sandbox by ID",inputSchema:qJ1,outputSchema:UK.nullable(),handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let W=await KQ().templates.findById(Q.id);if(W&&W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");return W}}});async function kJ1(X,Y){let Q=await Y.sessions.findById(X);if(!Q)throw new rW("Session not found","SESSION_NOT_FOUND");if(new Date(Q.expires_at)<new Date)throw new rW("Session has expired","SESSION_EXPIRED");return Q}async function Sb6(X,Y){let Q=await kJ1(X,Y);if(Q.status==="completed")throw new rW("Session is already completed. Create a new session to reconfigure.","SESSION_COMPLETED");return Q}function kb6(X,Y){let Q=X.metadata;if(!Q)throw new rW("Connection has no metadata","CONNECTION_ACCESS_DENIED");let J=Q[BK.SESSION_ID]===Y.id,G=Q[BK.EXTERNAL_USER_ID]===Y.external_user_id&&Q[BK.TEMPLATE_ID]===Y.template_id;if(!J&&!G)throw new rW("Access denied: connection does not belong to this session","CONNECTION_ACCESS_DENIED")}function h80(X,Y,Q){return{[BK.SESSION_ID]:X,[BK.EXTERNAL_USER_ID]:Y,[BK.TEMPLATE_ID]:Q,source:"user-sandbox"}}function x80(X,Y){return{[BK.EXTERNAL_USER_ID]:X,[BK.TEMPLATE_ID]:Y,source:"user-sandbox"}}async function Jz(X,Y,Q){let J=Q?.allowCompleted?await kJ1(X,Y):await Sb6(X,Y);if(Q?.connection)kb6(Q.connection,J);return J}var BK,rW;var vJ1=u(()=>{BK={SESSION_ID:"user_sandbox_session_id",EXTERNAL_USER_ID:"user_sandbox_external_user_id",TEMPLATE_ID:"user_sandbox_id"};rW=class rW extends Error{code;constructor(X,Y){super(X);this.code=Y;this.name="SessionAccessError"}}});var g80=u(()=>{vJ1()});async function _b6(X,Y,Q,J,G,W,Z,$){let K=X,H=await K.selectFrom("user_sandbox_agents").select("connection_id").where("user_sandbox_id","=",J).where("external_user_id","=",G).executeTakeFirst();if(H)return H.connection_id;let F=new Date().toISOString(),V=`usa_${Date.now().toString(36)}${crypto.randomUUID().replace(/-/g,"").substring(0,8)}`,q=`vir_${Date.now().toString(36)}${crypto.randomUUID().replace(/-/g,"").substring(0,8)}`;try{return await K.transaction().execute(async(B)=>{await B.insertInto("connections").values({id:q,organization_id:Y,created_by:Q,title:W,description:Z,icon:null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${q}`,connection_token:null,connection_headers:JSON.stringify({tool_selection_mode:$}),oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:JSON.stringify(x80(G,J)),tools:null,bindings:null,status:"active",created_at:F,updated_at:F}).execute(),await B.insertInto("user_sandbox_agents").values({id:V,user_sandbox_id:J,external_user_id:G,connection_id:q,created_at:F}).execute()}),q}catch(B){let D=String(B);if(D.includes("UNIQUE constraint")||D.includes("duplicate key")){let N=await K.selectFrom("user_sandbox_agents").select("connection_id").where("user_sandbox_id","=",J).where("external_user_id","=",G).executeTakeFirst();if(N)return N.connection_id}throw B}}var vb6=604800,_J1;var yJ1=u(()=>{aW();z7();g80();_J1={name:"USER_SANDBOX_CREATE_SESSION",description:"Create a connect session URL for an external user. Returns a URL that the user can visit to configure their integrations. Also creates a unique Virtual MCP (agent) for this user if one doesn't exist.",inputSchema:zJ1,outputSchema:DJ1,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W=await G.templates.findById(Q.templateId);if(!W)throw Error(`Template not found: ${Q.templateId}`);if(W.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");if(W.status!=="active")throw Error("Template is not active");let Z=await G.sessions.findExisting(Q.templateId,Q.externalUserId);if(Z){let D=b80();return{sessionId:Z.id,url:`${D}/connect/${Z.id}`,expiresAt:Z.expires_at,agentId:Z.created_agent_id}}let $=W.agent_title_template.replace("{{externalUserId}}",Q.externalUserId),K=W.created_by??J.auth.user?.id??"system",H=await _b6(J.db,J.organization.id,K,W.id,Q.externalUserId,$,W.agent_instructions,W.tool_selection_mode),F=Q.expiresInSeconds??vb6,V=new Date(Date.now()+F*1000).toISOString(),q=await G.sessions.create({template_id:Q.templateId,organization_id:J.organization.id,external_user_id:Q.externalUserId,redirect_url:W.redirect_url,expires_at:V,created_agent_id:H}),B=b80();return{sessionId:q.id,url:`${B}/connect/${q.id}`,expiresAt:q.expires_at,agentId:H}}}});var bJ1;var fJ1=u(()=>{aW();z7();bJ1={name:"USER_SANDBOX_LIST_SESSIONS",description:"List connect sessions for monitoring and management",inputSchema:NJ1,outputSchema:OJ1,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");await J.access.check();let G=KQ(),W;if(Q.templateId){let Z=await G.templates.findById(Q.templateId);if(!Z)throw Error(`Template not found: ${Q.templateId}`);if(Z.organization_id!==J.organization.id)throw Error("Access denied: template belongs to another organization");W=await G.sessions.listByTemplate(Q.templateId)}else W=await G.sessions.listByOrganization(J.organization.id);return{sessions:W}}}});var yb6="user_sandbox_external_user_id",bb6="user_sandbox_id",hJ1;var xJ1=u(()=>{aW();hJ1={name:"USER_SANDBOX_LIST_USER_AGENTS",description:"List all agents (Virtual MCPs) created for an external user. Use this to find agents created via user sandbox for a specific user in your platform.",inputSchema:LJ1,outputSchema:wJ1,handler:async(X,Y)=>{let Q=X,J=Y;if(!J.organization)throw Error("Organization context required");return await J.access.check(),{agents:(await J.storage.connections.list(J.organization.id)).filter((Z)=>{if(Z.connection_type!=="VIRTUAL")return!1;let $=Z.metadata;if(!$)return!1;return $[yb6]===Q.externalUserId}).map((Z)=>{let $=Z.metadata;return{id:Z.id,title:Z.title,external_user_id:Q.externalUserId,template_id:$[bb6]??null,created_at:Z.created_at}})}}}});var gJ1;var uJ1=u(()=>{PJ1();AJ1();jJ1();IJ1();SJ1();yJ1();fJ1();xJ1();z7();gJ1=[MJ1,TJ1,EJ1,CJ1,RJ1,_J1,bJ1,hJ1]});function fb6(X){let Y=Date.now().toString(36),Q=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`${X}_${Y}${Q}`}async function u80(X,Y,Q,J){let G={success:!1,agentId:X.created_agent_id,connectionIds:[],redirectUrl:null,eventEmitted:!1,webhookCalled:!1};try{let W=J.db,Z=new Date().toISOString(),$=X.created_agent_id;if(!$)throw Error("Session has no agent - this should not happen");let K=[],H=[];for(let[q,B]of Object.entries(X.app_statuses))if(B.configured&&B.connection_id){K.push(B.connection_id);let D=Y.required_apps.find((N)=>N.app_name===q);H.push({appName:q,connectionId:B.connection_id,selectedTools:D?.selected_tools??null,selectedResources:D?.selected_resources??null,selectedPrompts:D?.selected_prompts??null})}if(G.connectionIds=K,await W.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).execute(),H.length>0)await W.insertInto("connection_aggregations").values(H.map((q)=>({id:fb6("agg"),parent_connection_id:$,child_connection_id:q.connectionId,selected_tools:q.selectedTools?JSON.stringify(q.selectedTools):null,selected_resources:q.selectedResources?JSON.stringify(q.selectedResources):null,selected_prompts:q.selectedPrompts?JSON.stringify(q.selectedPrompts):null,created_at:Z}))).execute();await Q.sessions.update(X.id,{status:"completed"});let F={type:Y.event_type,data:{externalUserId:X.external_user_id,agentId:$,templateId:Y.id,sessionId:X.id,connections:K.map((q)=>{let B=Object.entries(X.app_statuses).find(([D,N])=>N.connection_id===q)?.[0];return{id:q,appName:B??"unknown"}})}};if(J.eventBus)try{await J.eventBus.publish(J.organizationId,"user-sandbox",F),G.eventEmitted=!0}catch(q){console.error("[UserSandbox] Failed to emit completion event:",q)}if(Y.webhook_url)try{let q=await fetch(Y.webhook_url,{method:"POST",headers:{"Content-Type":"application/json","X-User-Sandbox-Event":Y.event_type},body:JSON.stringify(F.data)});if(!q.ok)console.error("[UserSandbox] Webhook returned error:",q.status);else G.webhookCalled=!0}catch(q){console.error("[UserSandbox] Failed to call webhook:",q)}let V=X.redirect_url??Y.redirect_url;if(V){let q=new URL(V);q.searchParams.set("sessionId",X.id),q.searchParams.set("externalUserId",X.external_user_id),q.searchParams.set("agentId",$),G.redirectUrl=q.toString()}return G.success=!0,G}catch(W){throw console.error("[UserSandbox] Completion failed:",W),W}}var mJ1=()=>{};function hb6(){let X=Date.now().toString(36),Y=crypto.randomUUID().replace(/-/g,"").substring(0,8);return`conn_${X}${Y}`}async function xb6(X,Y,Q,J,G,W,Z){let $=hb6(),K=new Date().toISOString();if(!Z.title)throw Error(`App "${Z.app_name}" is missing required field: title`);if(!Z.connection_type)throw Error(`App "${Z.app_name}" is missing required field: connection_type`);if(!Z.connection_url&&Z.connection_type!=="STDIO")throw Error(`App "${Z.app_name}" is missing required field: connection_url`);let H={id:$,organization_id:Y,created_by:Q,title:Z.title,description:Z.description??null,icon:Z.icon??null,app_name:Z.app_name,app_id:null,connection_type:Z.connection_type,connection_url:Z.connection_url??"",connection_token:null,connection_headers:Z.connection_headers?JSON.stringify(Z.connection_headers):null,oauth_config:Z.oauth_config?JSON.stringify(Z.oauth_config):null,configuration_state:null,configuration_scopes:null,metadata:JSON.stringify(h80(J,G,W)),tools:null,bindings:null,status:"active",created_at:K,updated_at:K};return await X.insertInto("connections").values(H).execute(),$}function Mb(X,Y){if(Y instanceof rW){let Q={SESSION_NOT_FOUND:404,SESSION_EXPIRED:410,SESSION_COMPLETED:409,ACCESS_DENIED:403,CONNECTION_ACCESS_DENIED:403};return X.json({error:Y.message,code:Y.code},Q[Y.code]??400)}return console.error("[UserSandbox] Connect API error:",Y),X.json({error:Y instanceof Error?Y.message:"Internal error"},500)}function m80(X,Y){let Q=Y.db,J=new kP(Q),G=new vP(Q),W={templates:J,sessions:G};X.get("/api/user-sandbox/sessions/:sessionId",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Jz($,W,{allowCompleted:!0}),H=await J.findById(K.template_id);if(!H)return Z.json({error:"Template not found"},404);return Z.json({session:{id:K.id,status:K.status,external_user_id:K.external_user_id,expires_at:K.expires_at,redirect_url:K.redirect_url,created_agent_id:K.created_agent_id},template:{id:H.id,title:H.title,description:H.description,icon:H.icon},apps:H.required_apps.map((F)=>({app_name:F.app_name,title:F.title,description:F.description,icon:F.icon,connection_type:F.connection_type,requires_oauth:!!F.oauth_config,selected_tools:F.selected_tools,selected_resources:F.selected_resources,selected_prompts:F.selected_prompts,status:K.app_statuses[F.app_name]??{configured:!1,connection_id:null,error:null}}))})}catch($){return Mb(Z,$)}}),X.post("/api/user-sandbox/sessions/:sessionId/provision",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Z.req.json();if(!K.app_name)return Z.json({error:"app_name is required"},400);let H=await Jz($,W),F=await J.findById(H.template_id);if(!F)return Z.json({error:"Template not found"},404);let V=F.required_apps.find((N)=>N.app_name===K.app_name);if(!V)return Z.json({error:`App "${K.app_name}" is not required by this template`},400);let q=H.app_statuses[K.app_name];if(q?.connection_id)return Z.json({success:!0,connection_id:q.connection_id,already_provisioned:!0,requires_oauth:!!V.oauth_config});if(!F.created_by)return Z.json({error:"Template is missing created_by - cannot create connections"},500);let B=await xb6(Q,H.organization_id,F.created_by,$,H.external_user_id,H.template_id,V),D={...H.app_statuses,[K.app_name]:{configured:!1,connection_id:B,error:null}};return await G.update($,{status:"in_progress",app_statuses:D}),Z.json({success:!0,connection_id:B,already_provisioned:!1,requires_oauth:!!V.oauth_config})}catch($){return Mb(Z,$)}}),X.post("/api/user-sandbox/sessions/:sessionId/configure",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Z.req.json();if(!K.app_name)return Z.json({error:"app_name is required"},400);let H=await Jz($,W),F=await J.findById(H.template_id);if(!F)return Z.json({error:"Template not found"},404);if(!F.required_apps.find((L)=>L.app_name===K.app_name))return Z.json({error:`App "${K.app_name}" is not required by this template`},400);let q=H.app_statuses[K.app_name],D={configured:!0,connection_id:K.connection_id??q?.connection_id??null,error:null},N={...H.app_statuses,[K.app_name]:D};return await G.update($,{status:"in_progress",app_statuses:N}),Z.json({success:!0,app_name:K.app_name,status:D})}catch($){return Mb(Z,$)}}),X.post("/api/user-sandbox/sessions/:sessionId/complete",async(Z)=>{try{let $=Z.req.param("sessionId"),K=await Jz($,W),H=await J.findById(K.template_id);if(!H)return Z.json({error:"Template not found"},404);let F=H.required_apps.filter((q)=>{return!K.app_statuses[q.app_name]?.configured});if(F.length>0)return Z.json({error:"Not all required apps are configured",unconfigured:F.map((q)=>q.app_name)},400);let V=await u80(K,H,W,{organizationId:K.organization_id,db:Q});return Z.json({success:V.success,completed:!0,agentId:V.agentId,redirectUrl:V.redirectUrl,eventEmitted:V.eventEmitted,webhookCalled:V.webhookCalled})}catch($){return Mb(Z,$)}})}var lJ1=u(()=>{v80();_80();g80();mJ1()});var dJ1=u(()=>{lJ1()});var pJ1;var cJ1=u(()=>{ZJ1();KJ1();uJ1();dJ1();pJ1={id:Ob,description:QJ1,tools:gJ1,publicRoutes:(X,Y)=>{m80(X,Y)},migrations:WJ1,createStorage:(X)=>{let Y=$J1(X);return _P(Y),Y}}});var Pb;var nJ1=u(()=>{cJ1();Pb=[pJ1]});function gb6(X,Y){return iJ1.set(Y.name,X),{...Y,handler:async(Q,J)=>{let G=J.organization;if(!G)throw Error(`Organization context required for plugin tool "${Y.name}"`);if(!(await J.storage.organizationSettings.get(G.id))?.enabled_plugins?.includes(X))throw Error(`Plugin "${X}" is not enabled for this organization. Enable it in Settings > Plugins.`);return Y.handler(Q,J)},execute:async(Q,J)=>{let G=J.organization;if(!G)throw Error(`Organization context required for plugin tool "${Y.name}"`);if(!(await J.storage.organizationSettings.get(G.id))?.enabled_plugins?.includes(X))throw Error(`Plugin "${X}" is not enabled for this organization. Enable it in Settings > Plugins.`);return Y.execute(Q,J)}}}function aJ1(X,Y){return X.filter((Q)=>{let J=iJ1.get(Q.name);if(!J)return!0;return Y?.includes(J)??!1})}function rJ1(){let X=[];for(let Y of Pb){if(!Y.tools)continue;for(let Q of Y.tools){let J={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,handler:Q.handler,execute:Q.handler},G=gb6(Y.id,J);X.push(G)}}return X}function oJ1(X,Y){for(let Q of Pb){if(Q.routes){let J=new X.constructor;Q.routes(J,Y),X.route(`/api/plugins/${Q.id}`,J)}if(Q.publicRoutes)Q.publicRoutes(X,Y)}}function sJ1(X,Y){let Q={db:X,vault:{encrypt:(J)=>Y.encrypt(J),decrypt:(J)=>Y.decrypt(J)}};for(let J of Pb)if(J.createStorage){let G=J.createStorage(Q);ub6.set(J.id,G)}}var iJ1,ub6;var l80=u(()=>{nJ1();iJ1=new Map;ub6=new Map});function t0(X){return{...X,execute:async(Y,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${X.name}`,async()=>Q.tracer.startActiveSpan(`tool.${X.name}`,{attributes:{"tool.name":X.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=X.name,Q.access.setToolName?.(X.name);let W=await X.handler(Y,Q),Z=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(Z,{"tool.name":X.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":X.name,status:"success"}),G.setStatus({code:d80.SpanStatusCode.OK}),W}catch(W){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":X.name,"error.type":W.constructor.name}),G.setStatus({code:d80.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}}))}}}var d80;var Z6=u(()=>{d80=E6(K1(),1)});function _1(X){if(!X.organization)throw Error("This operation requires organization scope");return X.organization}function f8(X){return X.auth.user?.id??X.auth.apiKey?.userId}function mb6(X){return!!(X.auth.user||X.auth.apiKey)}function U1(X){if(!mb6(X))throw Error("Authentication required")}var Tb,tJ1,eJ1,X51,Y51,Q51,J51,G51,W51,Z51;var Gz=u(()=>{c0();Tb=U.record(U.string(),U.array(U.string())),tJ1=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),userId:U.string().describe("ID of the user who owns this API key"),permissions:Tb.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),eJ1=U.object({name:U.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:Tb.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:U.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:U.record(U.string(),U.unknown()).optional().describe("Additional metadata to store with the API key")}),X51=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),key:U.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:Tb.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),Y51=U.object({}),Q51=U.object({items:U.array(tJ1).describe("List of API keys (without key values)")}),J51=U.object({keyId:U.string().describe("ID of the API key to update"),name:U.string().min(1).max(64).optional().describe("New name for the API key"),permissions:Tb.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:U.record(U.string(),U.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),G51=U.object({item:tJ1.describe("The updated API key (without key value)")}),W51=U.object({keyId:U.string().describe("ID of the API key to delete")}),Z51=U.object({success:U.boolean().describe("Whether the deletion was successful"),keyId:U.string().describe("ID of the deleted API key")})});var p80;var $51=u(()=>{Z6();Gz();p80=t0({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:eJ1,outputSchema:X51,handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.create({name:X.name,permissions:X.permissions,expiresIn:X.expiresIn,metadata:{...X.metadata,organization:Y.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??X.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var c80;var K51=u(()=>{Z6();Gz();c80=t0({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:W51,outputSchema:Z51,handler:async(X,Y)=>{if(U1(Y),await Y.access.check(),!f8(Y))throw Error("User ID required to delete API key");let G=(await Y.boundAuth.apiKey.list())?.find((K)=>K.id===X.keyId);if(!G)throw Error("API key not found");let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot delete API key from another organization");return await Y.boundAuth.apiKey.delete(X.keyId),{success:!0,keyId:X.keyId}}})});var n80;var H51=u(()=>{Z6();Gz();n80=t0({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:Y51,outputSchema:Q51,handler:async(X,Y)=>{U1(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.list(),J=Y.organization?.id;return{items:(Q??[]).filter((W)=>{return W.metadata?.organization?.id===J}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt?W.expiresAt instanceof Date?W.expiresAt.toISOString():W.expiresAt:null,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var i80;var F51=u(()=>{Z6();Gz();i80=t0({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:J51,outputSchema:G51,handler:async(X,Y)=>{if(U1(Y),await Y.access.check(),!f8(Y))throw Error("User ID required to update API key");let G=(await Y.boundAuth.apiKey.list())?.find((H)=>H.id===X.keyId);if(!G)throw Error(`API key not found: ${X.keyId}`);let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot update API key from another organization");let K=await Y.boundAuth.apiKey.update({keyId:X.keyId,name:X.name,permissions:X.permissions,metadata:{...X.metadata,organization:Y.organization}});if(!K)throw Error(`Failed to update API key: ${X.keyId}`);return{item:{id:K.id,name:K.name??X.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var V51=u(()=>{$51();K51();H51();F51();Gz()});var q51,U51,B51,z51,D51,N51;var yP=u(()=>{c0();q51=U.object({query:U.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:U.number().default(10).describe("Maximum results to return (default: 10)")}),U51=U.object({query:U.string(),results:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string()})),totalAvailable:U.number()}),B51=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),z51=U.object({tools:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string(),inputSchema:U.unknown(),outputSchema:U.unknown().optional()})),notFound:U.array(U.string())}),D51=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),N51=U.object({returnValue:U.unknown().optional(),error:U.string().optional(),consoleLogs:U.array(U.object({type:U.enum(["log","warn","error"]),content:U.string()}))})});class Wz{proxies=new Map;constructor(){}static async create(X,Y){let Q=new Wz,J=await Promise.allSettled(X.map(async({connection:G,selectedTools:W,selectedResources:Z,selectedPrompts:$})=>{try{let K=await Y.createMCPProxy(G);return{connection:G,proxy:K,selectedTools:W,selectedResources:Z,selectedPrompts:$}}catch(K){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,K),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(X){return this.proxies.get(X)}entries(){return this.proxies.entries()}forEach(X){this.proxies.forEach((Y,Q)=>X(Y,Q))}async mapAsync(X){let Y=[];for(let[Q,J]of this.proxies.entries())Y.push(X(J,Q));return await Promise.all(Y)}async mapSettled(X){return Promise.allSettled(Array.from(this.proxies.entries()).map(([Y,Q])=>X(Q,Y)))}get size(){return this.proxies.size}}function O51(X){let Y=[],Q=[],J=(K)=>{let H=X.newFunction(K,(...F)=>{try{let V=F.map((q)=>X.dump(q));Y.push({type:K??"log",content:V.map(String).join(" ")})}finally{F.forEach((V)=>V.dispose())}return X.undefined});return Q.push(H),H},G=X.newObject();Q.push(G);let W=J("log"),Z=J("warn"),$=J("error");return X.setProp(G,"log",W),X.setProp(G,"warn",Z),X.setProp(G,"error",$),X.setProp(X.global,"console",G),{logs:Y,[Symbol.dispose](){Q.forEach((K)=>K.dispose())}}}var MF,a80,Ab,PF,bP;var Eb=u(()=>{MF={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},a80={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},Ab={Pending:0,Fulfilled:1,Rejected:2},PF={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},bP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function Zz(...X){XX0&&console.log("quickjs-emscripten:",...X)}function*k51(X){return yield X}function cb6(X){return k51(QX0(X))}function L51(X,Y){return(...Q)=>{let J=Y.call(X,YX0,...Q);return QX0(J)}}function nb6(X,Y){let Q=Y.call(X,YX0);return QX0(Q)}function QX0(X){function Y(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>Y(X.next(J)),(J)=>Y(X.throw(J))):Y(X.next(Q.value))}return Y(X.next())}function r80(X,Y){let Q;try{X.dispose()}catch(J){Q=J}if(Y&&Q)throw Object.assign(Y,{message:`${Y.message}
261
261
  Then, failed to dispose scope: ${Q.message}`,disposeError:Q}),Y;if(Y||Q)throw Y||Q}function v51(X){let Y=X?Array.from(X):[];function Q(){return Y.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return Y.some((G)=>G.alive)}return Object.defineProperty(Y,t80,{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(Y,"dispose",{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(Y,"alive",{configurable:!0,enumerable:!1,get:J}),Y}function jb(X){return!!(X&&(typeof X=="object"||typeof X=="function")&&("alive"in X)&&typeof X.alive=="boolean"&&("dispose"in X)&&typeof X.dispose=="function")}function ib6(X){if(!X)return 0;let Y=0;for(let[Q,J]of Object.entries(X)){if(!(Q in a80))throw new I51(Q);J&&(Y|=a80[Q])}return Y}function ab6(X){if(typeof X=="number")return X;if(X===void 0)return 0;let{type:Y,strict:Q,strip:J,compileOnly:G,backtraceBarrier:W}=X,Z=0;return Y==="global"&&(Z|=MF.JS_EVAL_TYPE_GLOBAL),Y==="module"&&(Z|=MF.JS_EVAL_TYPE_MODULE),Q&&(Z|=MF.JS_EVAL_FLAG_STRICT),J&&(Z|=MF.JS_EVAL_FLAG_STRIP),G&&(Z|=MF.JS_EVAL_FLAG_COMPILE_ONLY),W&&(Z|=MF.JS_EVAL_FLAG_BACKTRACE_BARRIER),Z}function rb6(X){if(typeof X=="number")return X;if(X===void 0)return 0;let{strings:Y,symbols:Q,quickjsPrivate:J,onlyEnumerable:G,numbers:W,numbersAsStrings:Z}=X,$=0;return Y&&($|=PF.JS_GPN_STRING_MASK),Q&&($|=PF.JS_GPN_SYMBOL_MASK),J&&($|=PF.JS_GPN_PRIVATE_MASK),G&&($|=PF.JS_GPN_ENUM_ONLY),W&&($|=PF.QTS_GPN_NUMBER_MASK),Z&&($|=PF.QTS_STANDARD_COMPLIANT_NUMBER),$}function ob6(...X){let Y=[];for(let Q of X)Q!==void 0&&(Y=Y.concat(Q));return Y}function ZX0(X,Y){Y.interruptHandler&&X.setInterruptHandler(Y.interruptHandler),Y.maxStackSizeBytes!==void 0&&X.setMaxStackSize(Y.maxStackSizeBytes),Y.memoryLimitBytes!==void 0&&X.setMemoryLimit(Y.memoryLimitBytes)}function $X0(X,Y){Y.moduleLoader&&X.setModuleLoader(Y.moduleLoader),Y.shouldInterrupt&&X.setInterruptHandler(Y.shouldInterrupt),Y.memoryLimitBytes!==void 0&&X.setMemoryLimit(Y.memoryLimitBytes),Y.maxStackSizeBytes!==void 0&&X.setMaxStackSize(Y.maxStackSizeBytes)}var db6,pb6=(X,Y)=>{for(var Q in Y)db6(X,Q,{get:Y[Q],enumerable:!0})},XX0=!1,M51,o80,P51,s80,T51,A51,E51,j51,C51,I51,R51,S51,YX0,oW,t80,w51,dY,zK,e80,x5,JX0,_51,y51,TF,b51,f51=class{constructor(X){this.module=X}toPointerArray(X){let Y=new Int32Array(X.map((G)=>G.value)),Q=Y.length*Y.BYTES_PER_ELEMENT,J=this.module._malloc(Q);return new Uint8Array(this.module.HEAPU8.buffer,J,Q).set(new Uint8Array(Y.buffer)),new dY(J,void 0,(G)=>this.module._free(G))}newTypedArray(X,Y){let Q=new X(Array(Y).fill(0)),J=Q.length*Q.BYTES_PER_ELEMENT,G=this.module._malloc(J),W=new X(this.module.HEAPU8.buffer,G,Y);return W.set(Q),new dY({typedArray:W,ptr:G},void 0,(Z)=>this.module._free(Z.ptr))}newMutablePointerArray(X){return this.newTypedArray(Int32Array,X)}newHeapCharPointer(X){let Y=this.module.lengthBytesUTF8(X),Q=Y+1,J=this.module._malloc(Q);return this.module.stringToUTF8(X,J,Q),new dY({ptr:J,strlen:Y},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(X){let Y=X.byteLength,Q=this.module._malloc(Y);return this.module.HEAPU8.set(X,Q),new dY({pointer:Q,numBytes:Y},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(X){let Y=this.module.UTF8ToString(X);return this.module._free(X),Y}},Bd4,GX0,sb6,tb6,h51,x51,eb6=class{constructor(X){this.callFunction=X.callFunction,this.shouldInterrupt=X.shouldInterrupt,this.loadModuleSource=X.loadModuleSource,this.normalizeModule=X.normalizeModule}},WX0=class{constructor(X){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new eb6({callFunction:(Y,Q,J,G,W,Z)=>this.handleAsyncify(Y,()=>{try{let $=this.contextCallbacks.get(Q);if(!$)throw Error(`QuickJSContext(ctx = ${Q}) not found for C function call "${Z}"`);return $.callFunction(Q,J,G,W,Z)}catch($){return console.error("[C to host error: returning null]",$),0}}),shouldInterrupt:(Y,Q)=>this.handleAsyncify(Y,()=>{try{let J=this.runtimeCallbacks.get(Q);if(!J)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C interrupt`);return J.shouldInterrupt(Q)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(Y,Q,J,G)=>this.handleAsyncify(Y,()=>{try{let W=this.runtimeCallbacks.get(Q);if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let Z=W.loadModuleSource;if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return Z(Q,J,G)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}}),normalizeModule:(Y,Q,J,G,W)=>this.handleAsyncify(Y,()=>{try{let Z=this.runtimeCallbacks.get(Q);if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let $=Z.normalizeModule;if(!$)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return $(Q,J,G,W)}catch(Z){return console.error("[C to host module loader error: returning null]",Z),0}})}),this.module=X,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(X,Y){this.runtimeCallbacks.set(X,Y)}deleteRuntime(X){this.runtimeCallbacks.delete(X)}setContextCallbacks(X,Y){this.contextCallbacks.set(X,Y)}deleteContext(X){this.contextCallbacks.delete(X)}handleAsyncify(X,Y){if(X)return X.handleSleep((J)=>{try{let G=Y();if(!(G instanceof Promise)){Zz("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new A51(`Already suspended at: ${this.suspended.stack}
262
262
  Attempted to suspend at:`);this.suspended=new E51(`(${this.suspendedCount++})`),Zz("asyncify.handleSleep: suspending:",this.suspended),G.then((W)=>{this.suspended=void 0,Zz("asyncify.handleSleep: resolved:",W),J(W)},(W)=>{Zz("asyncify.handleSleep: rejected:",W),console.error("QuickJS: cannot handle error in suspended function",W),this.suspended=void 0})}catch(G){throw Zz("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Q=Y();if(Q instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Q}},KX0=class{constructor(X,Y){this.module=X,this.ffi=Y,this.callbacks=new WX0(X)}newRuntime(X={}){let Y=new dY(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Q=new x51({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:Y});return ZX0(Q,X),X.moduleLoader&&Q.setModuleLoader(X.moduleLoader),Q}newContext(X={}){let Y=this.newRuntime(),Q=Y.newContext({...X,ownedLifetimes:ob6(Y,X.ownedLifetimes)});return Y.context=Q,Q}evalCode(X,Y={}){return x5.withScope((Q)=>{let J=Q.manage(this.newContext());$X0(J.runtime,Y);let G=J.evalCode(X,"eval.js");if(Y.memoryLimitBytes!==void 0&&J.runtime.setMemoryLimit(-1),G.error)throw J.dump(Q.manage(G.error));return J.dump(Q.manage(G.value))})}getWasmMemory(){let X=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!X)throw Error("Variant does not support getting WebAssembly.Memory");return X}getFFI(){return this.ffi}};var HX0=u(()=>{Eb();Eb();db6=Object.defineProperty;M51={};pb6(M51,{QuickJSAsyncifyError:()=>A51,QuickJSAsyncifySuspended:()=>E51,QuickJSEmptyGetOwnPropertyNames:()=>S51,QuickJSEmscriptenModuleError:()=>C51,QuickJSMemoryLeakDetected:()=>j51,QuickJSNotImplemented:()=>T51,QuickJSPromisePending:()=>R51,QuickJSUnknownIntrinsic:()=>I51,QuickJSUnwrapError:()=>o80,QuickJSUseAfterFree:()=>s80,QuickJSWrongOwner:()=>P51});o80=class extends Error{constructor(X,Y){let Q=typeof X=="object"&&X&&"message"in X?String(X.message):String(X);super(Q);this.cause=X,this.context=Y,this.name="QuickJSUnwrapError"}},P51=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},s80=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},T51=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},A51=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},E51=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},j51=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},C51=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},I51=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},R51=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},S51=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};YX0=k51;YX0.of=cb6;oW=class{[Symbol.dispose](){return this.dispose()}},t80=Symbol.dispose??Symbol.for("Symbol.dispose"),w51=oW.prototype;w51[t80]||(w51[t80]=function(){return this.dispose()});dY=class X extends oW{constructor(Y,Q,J,G){super();this._value=Y,this.copier=Q,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=XX0?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new X(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(Y){this.assertAlive();let Q=Y(this);return this.dispose(),Q}map(Y){return this.assertAlive(),Y(this)}tap(Y){return Y(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new s80(`Lifetime not alive
263
263
  ${this._constructorStack}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/mesh",
3
- "version": "2.39.0",
3
+ "version": "2.39.1",
4
4
  "description": "MCP Mesh - Self-hostable MCP Gateway for managing AI connections and tools",
5
5
  "author": "Deco team",
6
6
  "license": "MIT",