@decocms/mesh 2.123.0 → 2.123.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1042,7 +1042,7 @@ At the end, provide a concise summary of:
1042
1042
  - What failed
1043
1043
  - What could not be tested and why
1044
1044
  - If some tool needs user-specific context (email/account/tenant), explicitly output a "CONTEXT_REQUIRED" note with what is needed.
1045
- `.trim()});import{sql as eI0}from"kysely";var Yj0;var Qj0=k(()=>{Yj0={name:"001-private-registry",async up(Y){await Y.schema.createTable("private_registry_item").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Q)=>Q.notNull()).addColumn("description","text").addColumn("server_json","text",(Q)=>Q.notNull()).addColumn("meta_json","text").addColumn("tags","text").addColumn("categories","text").addColumn("is_public","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(eI0`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Q)=>Q.notNull().defaultTo(eI0`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Q)=>Q.references("user.id").onDelete("set null")).execute(),await Y.schema.createIndex("idx_private_registry_item_org").on("private_registry_item").column("organization_id").execute(),await Y.schema.createIndex("idx_private_registry_item_org_public").on("private_registry_item").columns(["organization_id","is_public"]).execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_item_org_public").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_item_org").ifExists().execute(),await Y.schema.dropTable("private_registry_item").ifExists().execute()}}});import{sql as Xj0}from"kysely";var Jj0;var Gj0=k(()=>{Jj0={name:"002-publish-requests",async up(Y){await Y.schema.createTable("private_registry_publish_request").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("status","text",(Q)=>Q.notNull().defaultTo("pending")).addColumn("title","text",(Q)=>Q.notNull()).addColumn("description","text").addColumn("server_json","text",(Q)=>Q.notNull()).addColumn("meta_json","text").addColumn("requester_name","text").addColumn("requester_email","text").addColumn("reviewer_notes","text").addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(Xj0`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Q)=>Q.notNull().defaultTo(Xj0`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_publish_request_org_status").on("private_registry_publish_request").columns(["organization_id","status"]).execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_publish_request_org_status").ifExists().execute(),await Y.schema.dropTable("private_registry_publish_request").ifExists().execute()}}});import{sql as iA6}from"kysely";var Wj0;var Zj0=k(()=>{Wj0={name:"003-publish-api-keys",async up(Y){await Y.schema.createTable("private_registry_publish_api_key").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("name","text",(Q)=>Q.notNull()).addColumn("key_hash","text",(Q)=>Q.notNull()).addColumn("prefix","text",(Q)=>Q.notNull()).addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(iA6`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_publish_api_key_org").on("private_registry_publish_api_key").columns(["organization_id"]).execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_publish_api_key_org").ifExists().execute(),await Y.schema.dropTable("private_registry_publish_api_key").ifExists().execute()}}});var Kj0;var Hj0=k(()=>{Kj0={name:"004-publish-request-requested-id",async up(Y){await Y.schema.alterTable("private_registry_publish_request").addColumn("requested_id","text").execute()},async down(Y){await Y.schema.alterTable("private_registry_publish_request").dropColumn("requested_id").execute()}}});import{sql as kn}from"kysely";var $j0;var Fj0=k(()=>{$j0={name:"005-monitor-runs",async up(Y){await Y.schema.createTable("private_registry_monitor_run").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("status","text",(Q)=>Q.notNull().defaultTo("pending")).addColumn("config_snapshot","text").addColumn("total_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("tested_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("passed_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("failed_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("skipped_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("current_item_id","text").addColumn("started_at","text").addColumn("finished_at","text").addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_monitor_run_org_created").on("private_registry_monitor_run").columns(["organization_id","created_at"]).execute(),await Y.schema.createTable("private_registry_monitor_result").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("run_id","text",(Q)=>Q.notNull().references("private_registry_monitor_run.id").onDelete("cascade")).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("item_id","text",(Q)=>Q.notNull()).addColumn("item_title","text",(Q)=>Q.notNull()).addColumn("status","text",(Q)=>Q.notNull()).addColumn("error_message","text").addColumn("connection_ok","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("tools_listed","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("tool_results","text").addColumn("agent_summary","text").addColumn("duration_ms","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("action_taken","text",(Q)=>Q.notNull().defaultTo("none")).addColumn("tested_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_monitor_result_run").on("private_registry_monitor_result").columns(["run_id","tested_at"]).execute(),await Y.schema.createIndex("idx_private_registry_monitor_result_run_status").on("private_registry_monitor_result").columns(["run_id","status"]).execute(),await Y.schema.createTable("private_registry_monitor_connection").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("item_id","text",(Q)=>Q.notNull()).addColumn("connection_id","text",(Q)=>Q.notNull().references("connections.id").onDelete("cascade")).addColumn("auth_status","text",(Q)=>Q.notNull().defaultTo("none")).addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_monitor_connection_org_item").on("private_registry_monitor_connection").columns(["organization_id","item_id"]).unique().execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_monitor_connection_org_item").ifExists().execute(),await Y.schema.dropTable("private_registry_monitor_connection").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_monitor_result_run_status").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_monitor_result_run").ifExists().execute(),await Y.schema.dropTable("private_registry_monitor_result").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_monitor_run_org_created").ifExists().execute(),await Y.schema.dropTable("private_registry_monitor_run").ifExists().execute()}}});var Vj0;var qj0=k(()=>{Vj0={name:"006-unlisted",async up(Y){await Y.schema.alterTable("private_registry_item").addColumn("is_unlisted","integer",(Q)=>Q.notNull().defaultTo(0)).execute()},async down(Y){await Y.schema.alterTable("private_registry_item").dropColumn("is_unlisted").execute()}}});var Bj0;var Uj0=k(()=>{Qj0();Gj0();Zj0();Hj0();Fj0();qj0();Bj0=[Yj0,Jj0,Wj0,Kj0,$j0,Vj0]});function aA6(Y){let Q=Y;if(!Q||typeof Q!=="object"||!("method"in Q))return null;switch(Q.method){case"initialize":{let X=Q?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Q.jsonrpc??"2.0",id:Q.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var vn;var yV1=k(()=>{AR();vn=class vn extends bV{constructor(Y,Q){super(Y,Q)}send(Y,Q){let X=aA6(Y);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send(Y,Q)}}});function AS(Y,Q){if(Y===Q)return!0;if(Y==null||Q==null)return Y===Q;if(typeof Y!==typeof Q)return!1;if(Array.isArray(Y)&&Array.isArray(Q)){if(Y.length!==Q.length)return!1;return Y.every((X,J)=>AS(X,Q[J]))}if(typeof Y==="object"&&typeof Q==="object"){let X=Object.keys(Y),J=Object.keys(Q);if(X.length!==J.length)return!1;return X.every((G)=>J.includes(G)&&AS(Y[G],Q[G]))}return!1}function OP6(){return(Y)=>{if(!Array.isArray(Y))return!0;let Q=[];return Y.every((X)=>{if(Q.some((G)=>AS(X,G)))return!1;return Q.push(X),!0})}}function _n(Y,Q){return Y.safeParse(Q).success}function rX(Y){if(typeof Y==="boolean")return Y?B.any():B.never();let Q={};for(let G of kP6)G.apply(Q,Y);let X=[];if(Q.string!==!1)X.push(Q.string||B.string());if(Q.number!==!1)X.push(Q.number||B.number());if(Q.boolean!==!1)X.push(Q.boolean||B.boolean());if(Q.null!==!1)X.push(Q.null||B.null());if(Q.array!==!1)X.push(Q.array||B.array(B.any()));if(Q.tuple!==!1&&Q.tuple!==void 0)X.push(Q.tuple);if(Q.object!==!1)if(Q.object)X.push(Q.object);else{let G=B.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");X.push(G)}if(Q.file!==!1&&Q.file!==void 0)X.push(Q.file);let J;if(X.length===0)J=B.never();else if(X.length===1)J=X[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=B.any();else J=B.union(X);for(let G of vP6)J=G.apply(J,Y);return J}var rA6=class{apply(Y,Q){if(!Q.type)return;let X=Array.isArray(Q.type)?Q.type:[Q.type],J=new Set(X);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||B.number();if(G instanceof B.ZodNumber)Y.number=G.int()}}},oA6=class{apply(Y,Q){if(Q.const===void 0)return;let X=Q.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof X==="string")Y.string=B.literal(X);else if(typeof X==="number")Y.number=B.literal(X);else if(typeof X==="boolean")Y.boolean=B.literal(X);else if(X===null)Y.null=B.null();else if(Array.isArray(X))Y.array=void 0;else if(typeof X==="object")Y.object=void 0}},sA6=class{apply(Y,Q){if(!Q.enum)return;if(Q.enum.length===0){if(!Q.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let X={string:Q.enum.filter((J)=>typeof J==="string"),number:Q.enum.filter((J)=>typeof J==="number"),boolean:Q.enum.filter((J)=>typeof J==="boolean"),null:Q.enum.filter((J)=>J===null),array:Q.enum.filter((J)=>Array.isArray(J)),object:Q.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(X.string,"string"),Y.number=this.createTypeSchema(X.number,"number"),Y.boolean=this.createTypeSchema(X.boolean,"boolean"),Y.null=X.null.length>0?B.null():!1,Y.array=X.array.length>0?void 0:!1,Y.object=X.object.length>0?void 0:!1}createTypeSchema(Y,Q){if(Y.length===0)return!1;if(Y.length===1)return B.literal(Y[0]);if(Q==="string")return B.enum(Y);if(Q==="number"){let[X,J,...G]=Y;return B.union([B.literal(X),B.literal(J),...G.map((K)=>B.literal(K))])}if(Q==="boolean")return B.union([B.literal(!0),B.literal(!1)]);return!1}},tA6=class{apply(Y,Q){let X=Q;if(X.type==="string"&&X.format==="binary"&&X.contentEncoding==="binary"){let J=B.file();if(X.minLength!==void 0)J=J.min(X.minLength);if(X.maxLength!==void 0)J=J.max(X.maxLength);if(X.contentMediaType!==void 0)J=J.mime(X.contentMediaType);Y.file=J,Y.string=!1}}},eA6=class{apply(Y,Q){let X=Q;if(Q.type===void 0&&(X.minLength!==void 0||X.maxLength!==void 0||X.pattern!==void 0)){if(Y.string===void 0)Y.string=B.string()}}},YP6=class{apply(Y,Q){let X=Q;if(X.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||B.string();if(J instanceof B.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=X.minLength},{message:`String must be at least ${X.minLength} characters long`})}}},QP6=class{apply(Y,Q){let X=Q;if(X.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||B.string();if(J instanceof B.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=X.maxLength},{message:`String must be at most ${X.maxLength} characters long`})}}},XP6=class{apply(Y,Q){let X=Q;if(!X.pattern)return;if(Y.string!==!1){let J=Y.string||B.string();if(J instanceof B.ZodString){let G=new RegExp(X.pattern);Y.string=J.regex(G)}}}},JP6=class{apply(Y,Q){let X=Q;if(X.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)Y.number=J.min(X.minimum)}}},GP6=class{apply(Y,Q){let X=Q;if(X.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)Y.number=J.max(X.maximum)}}},WP6=class{apply(Y,Q){let X=Q;if(X.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)if(typeof X.exclusiveMinimum==="number")Y.number=J.gt(X.exclusiveMinimum);else Y.number=!1}}},ZP6=class{apply(Y,Q){let X=Q;if(X.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)if(typeof X.exclusiveMaximum==="number")Y.number=J.lt(X.exclusiveMaximum);else Y.number=!1}}},KP6=class{apply(Y,Q){let X=Q;if(X.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)Y.number=J.refine((G)=>{if(X.multipleOf===0)return!1;let K=G/X.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(X.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(X.multipleOf)},{message:`Must be a multiple of ${X.multipleOf}`})}}},HP6=class{apply(Y,Q){let X=Q;if(Q.type===void 0&&(X.minItems!==void 0||X.maxItems!==void 0||X.items!==void 0||X.prefixItems!==void 0)){if(Y.array===void 0)Y.array=B.array(B.any())}}},$P6=class{apply(Y,Q){let X=Q;if(X.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||B.array(B.any())).min(X.minItems)}},FP6=class{apply(Y,Q){let X=Q;if(X.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||B.array(B.any())).max(X.maxItems)}},VP6=class{apply(Y,Q){let X=Q;if(Y.array===!1)return;if(Array.isArray(X.items))Y.array=Y.array||B.array(B.any());else if(X.items&&typeof X.items!=="boolean"&&!X.prefixItems){let J=rX(X.items),G=B.array(J);if(Y.array&&Y.array instanceof B.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof X.items==="boolean"&&X.items===!1)if(!X.prefixItems)Y.array=B.array(B.any()).max(0);else Y.array=Y.array||B.array(B.any());else if(typeof X.items==="boolean"&&X.items===!0)Y.array=Y.array||B.array(B.any());else if(X.prefixItems)Y.array=Y.array||B.array(B.any())}},qP6=class{apply(Y,Q){if(Q.type!=="array")return;let X=Q;if(!Array.isArray(X.items))return;if(Y.array===!1)return;let J=X.items.map((K)=>rX(K)),G;if(J.length===0)G=B.tuple([]);else G=B.tuple(J);if(X.minItems!==void 0&&X.minItems>J.length)G=!1;if(X.maxItems!==void 0&&X.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},BP6=class{apply(Y,Q){let X=Q;if(Y.object===!1)return;if(X.properties||X.required||X.additionalProperties!==void 0)Y.object=Y.object||B.object({}).passthrough()}},UP6=class{apply(Y,Q){let X=Q;if(Q.type===void 0&&(X.maxProperties!==void 0||X.minProperties!==void 0)){if(Y.object===void 0)Y.object=B.object({}).passthrough()}}},zP6=class{apply(Y,Q){let X=Q;if(X.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||B.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=X.maxProperties,{message:`Object must have at most ${X.maxProperties} properties`})}}},DP6=class{apply(Y,Q){let X=Q;if(X.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||B.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=X.minProperties,{message:`Object must have at least ${X.minProperties} properties`})}}},NP6=class{apply(Y,Q){if(!Q.not)return Y;let X=rX(Q.not);return Y.refine((J)=>!_n(X,J),{message:"Value must not match the 'not' schema"})}},LP6=class{apply(Y,Q){if(Q.uniqueItems!==!0)return Y;return Y.refine(OP6(),{message:"Array items must be unique"})}},MP6=class{apply(Y,Q){if(!Q.allOf||Q.allOf.length===0)return Y;return Q.allOf.map((J)=>rX(J)).reduce((J,G)=>B.intersection(J,G),Y)}},wP6=class{apply(Y,Q){if(!Q.anyOf||Q.anyOf.length===0)return Y;let X=Q.anyOf.length===1?rX(Q.anyOf[0]):B.union([rX(Q.anyOf[0]),rX(Q.anyOf[1]),...Q.anyOf.slice(2).map((J)=>rX(J))]);return B.intersection(Y,X)}},AP6=class{apply(Y,Q){if(!Q.oneOf||Q.oneOf.length===0)return Y;let X=Q.oneOf.map((J)=>rX(J));return Y.refine((J)=>{let G=0;for(let K of X)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},PP6=class{apply(Y,Q){let X=Q;if(X.prefixItems&&Array.isArray(X.prefixItems)){let G=X.prefixItems.map((K)=>rX(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!_n(G[W],K[W]))return!1;if(K.length>G.length){if(typeof X.items==="boolean"&&X.items===!1)return!1;else if(X.items&&typeof X.items==="object"&&!Array.isArray(X.items)){let W=rX(X.items);for(let Z=G.length;Z<K.length;Z++)if(!_n(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},EP6=class{apply(Y,Q){let X=Q;if(!X.properties&&!X.required&&X.additionalProperties!==!1)return Y;if(Y instanceof B.ZodObject||Y instanceof B.ZodRecord){let J={};if(X.properties){for(let[G,K]of Object.entries(X.properties))if(K!==void 0)J[G]=rX(K)}if(X.required&&Array.isArray(X.required)){let G=new Set(X.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(X.additionalProperties===!1)return B.object(J);else return B.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(X.properties){for(let[G,K]of Object.entries(X.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!rX(K).safeParse(J[G]).success)return!1}}}if(X.required&&Array.isArray(X.required)){for(let G of X.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(X.additionalProperties===!1&&X.properties){let G=new Set(Object.keys(X.properties));for(let K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},TP6=class{apply(Y,Q){if(!Q.enum||Q.enum.length===0)return Y;let X=Q.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(X.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return X.some((G)=>AS(J,G))},{message:"Value must match one of the enum values"})}},CP6=class{apply(Y,Q){if(Q.const===void 0)return Y;let X=Q.const;if(typeof X!=="object"||X===null)return Y;return Y.refine((J)=>AS(J,X),{message:"Value must equal the const value"})}},RP6=class{apply(Y,Q){if(Q.description)Y=Y.describe(Q.description);return Y}},IP6=class{apply(Y,Q){var X;let J=Q;if(!((X=J.required)==null?void 0:X.includes("__proto__"))||Q.type!==void 0)return Y;return B.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,Q){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return Q.every((X)=>Object.prototype.hasOwnProperty.call(Y,X))}},jP6=class{apply(Y,Q){var X;let J=Q;if(J.contains===void 0)return Y;let G=rX(J.contains),K=(X=J.minContains)!=null?X:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let $ of Z)if(_n(G,$))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},SP6=class{apply(Y,Q){let{default:X}=Q;if(X===void 0)return Y;if(!Y.safeParse(X).success)return Y;return Y.default(X)}},kP6,vP6;var zj0=k(()=>{o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();kP6=[new oA6,new sA6,new rA6,new tA6,new eA6,new HP6,new UP6,new YP6,new QP6,new XP6,new JP6,new GP6,new WP6,new ZP6,new KP6,new qP6,new $P6,new FP6,new VP6,new zP6,new DP6,new BP6],vP6=[new IP6,new TP6,new CP6,new MP6,new wP6,new AP6,new PP6,new EP6,new jP6,new NP6,new LP6,new SP6,new RP6]});class fV1{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,Q)=>{this._socket=new WebSocket(this._url,_P6),this._socket.onerror=(X)=>{let J="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);Q(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(X)=>{let J;try{J=mG.parse(JSON.parse(X.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((Q,X)=>{if(!this._socket){X(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),Q()})}}var _P6="mcp";var Dj0=k(()=>{vQ()});var Oj0,Nj0=async(Y,Q,X)=>{let J=yP6(Y.connection,Q,X);if(!J)throw Error("Unknown MCP connection type");let G=new Oj0({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(X);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[V,q]of Object.entries(Y.connection.headers??{}))H.set(V,q);let $=new URL(Y.connection.url),F=$.pathname.replace(/\/+$/,"")||"/";return $.pathname=`${F}/call-tool/${encodeURIComponent(K)}`,fetch($.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},yP6=(Y,Q,X)=>{if(Y.type==="Websocket")return new fV1(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...X??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:Q}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:Q})}};return new SD(new URL(Y.url),K)}return new vn(new URL(Y.url),{requestInit:{headers:G,signal:Q,credentials:"include"}})};var Lj0=k(()=>{qz();Rn();Dj0();vQ();yV1();Oj0=class Oj0 extends G5{constructor(Y,Q){super(Y,Q)}async listTools(Y,Q){return await this.request({method:"tools/list",params:Y},cC,Q)}}});function Aj0(Y){let Q=(X)=>{if("connection"in Y)return Nj0({connection:Y.connection},void 0,X);return Y.client};return new Proxy({},{get(X,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return Z;async function G(H,$=J){let F=Y?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:U}=await Q(V);if(Y?.streamable?.[String($)]){if(!U)throw Error(`Tool ${String($)} requires streaming support but client doesn't provide callStreamableTool`);return await U(String($),H)}let{structuredContent:z,isError:D,content:L}=await q.callTool({name:String($),arguments:H});if(D){let E=L?.[0]?.text,T=typeof E==="string"?Mj0(E):null,C=T?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(T.code,T.message,T.traceId):null;if(C)throw C;throw Error(`Tool ${String($)} returned an error: ${JSON.stringify(z??L)}`)}if(z!==void 0)return z;let w=L?.[0]?.text;return typeof w==="string"?Mj0(w):void 0}async function K(){let{client:H}=await Q(),{tools:$}=await H.listTools();return $}async function W(){if(!("connection"in Y))return K();let H=Y.connection,$=JSON.stringify(H);try{if(!yn.has($))yn.set($,K());return await yn.get($)}catch(F){console.error("Failed to list tools",F),yn.delete($);return}}async function Z(){return(await W()??[]).map(($)=>wj0($,G))}return G.asTool=async()=>{let $=(await W()??[]).find((F)=>F.name===J);if(!$)throw Error(`Tool ${J} not found`);return wj0($,G)},G}})}var Mj0=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},yn,wj0=(Y,Q)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?rX(Y.inputSchema):void 0,outputSchema:Y.outputSchema?rX(Y.outputSchema):void 0,execute:(X)=>{return Q(X.context,Y.name)}}};var Pj0=k(()=>{zj0();Lj0();yn=new Map});function vD(Y){return Aj0(Y)}var bn;var bV1=k(()=>{Pj0();bn=new Proxy({},{get(Y,Q){if(Q==="toJSON")return null;if(Q==="forConnection")return(X)=>vD({connection:X});return global[Q]}})});function hn(Y){return{isImplementedBy:(Q)=>{for(let X of Y){let J=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,G=Q.find((K)=>J.test(K.name));if(!G&&X.opt)continue;if(!G)return!1}return!0}}}var yH=(Y)=>{return{...hn(Y),forClient:(Q)=>{return vD({client:Q,streamable:Y.reduce((X,J)=>{return X[J.name]=J.streamable===!0,X},{})})},forConnection:(Q)=>{return vD({connection:Q,streamable:Y.reduce((X,J)=>{return X[J.name]=J.streamable===!0,X},{})})}}};var _D=k(()=>{bV1()});var Ej0=k(()=>{yV1();bV1();_D()});var hV1=k(()=>{Ej0()});var gV1=(Y)=>{return typeof Y==="object"&&Y!==null&&typeof Y.__type==="string"&&typeof Y.value==="string"},Tj0=(Y,Q,X)=>{let J=X?{"x-caller-app":X}:void 0;if(Q.cookie)J??={},J.cookie=Q.cookie;if(Q.token)J??={},J["x-mesh-token"]=Q.token;return{type:"HTTP",url:new URL(`/mcp/${Y}`,Q.meshUrl).href,token:Q.token,headers:J}},fP6=(Y,Q,X)=>{let J=Tj0(Y,Q,X);return new Proxy(bn.forConnection(J),{get(G,K){if(K==="value")return Y;if(K==="__type")return X;return G[K]}})},xV1=(Y,Q)=>{if(Y===null||Y===void 0)return Y;if(Array.isArray(Y))return Y.map((X)=>xV1(X,Q));if(typeof Y==="object"){if(gV1(Y))return fP6(Y.value,Q,Y.__type);let X={};for(let[J,G]of Object.entries(Y))X[J]=xV1(G,Q);return X}return Y},Cj0=(Y)=>{return xV1(Y.state,Y)};var xn=k(()=>{hV1()});var bP6,Rj0=(Y,Q,X)=>{if(!Q)return null;if(Y===void 0||Y==="*")return"*";if(typeof Y==="string")return Y===Q?Y:null;if(Array.isArray(Y))return Y.includes(Q)?Q:null;if(typeof Y==="function")return Y(Q,X)??null;return null},hP6=(Y,Q,X)=>{let J=Q.headers.get("Origin"),G=Rj0(X.origin,J,Q);if(G)Y.set("Access-Control-Allow-Origin",G);if(X.credentials)Y.set("Access-Control-Allow-Credentials","true");if(X.exposeHeaders?.length)Y.set("Access-Control-Expose-Headers",X.exposeHeaders.join(", "))},Ij0=(Y,Q)=>{let X=new Headers,J=Y.headers.get("Origin"),G=Rj0(Q.origin,J,Y);if(G)X.set("Access-Control-Allow-Origin",G);if(Q.credentials)X.set("Access-Control-Allow-Credentials","true");let K=Q.allowMethods??bP6;X.set("Access-Control-Allow-Methods",K.join(", "));let W=Y.headers.get("Access-Control-Request-Headers");if(Q.allowHeaders?.length)X.set("Access-Control-Allow-Headers",Q.allowHeaders.join(", "));else if(W)X.set("Access-Control-Allow-Headers",W);if(Q.maxAge!==void 0)X.set("Access-Control-Max-Age",Q.maxAge.toString());return new Response(null,{status:204,headers:X})},jj0=(Y,Q,X)=>{let J=new Headers(Y.headers);return hP6(J,Q,X),new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:J})};var Sj0=k(()=>{bP6=["GET","HEAD","PUT","POST","DELETE","PATCH"]});function kj0(Y=32){let X=new Uint8Array(Y);return crypto.getRandomValues(X),Array.from(X,(J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[J%62]).join("")}function xP6(Y){try{let Q=new URL(Y);return Q.protocol==="https:"||Q.hostname==="localhost"||Q.hostname==="127.0.0.1"||!Q.protocol.startsWith("http")}catch{return!1}}function vj0(Y){return btoa(JSON.stringify(Y)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function _j0(Y){try{let Q=Y.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(Q))}catch{return null}}function yj0(Y){return{handleProtectedResourceMetadata:($)=>{let F=fH(new URL($.url)),V=`${F.origin}/mcp`;return Response.json({resource:V,authorization_servers:[F.origin],scopes_supported:["*"],bearer_methods_supported:["header"],resource_signing_alg_values_supported:["RS256","none"]})},handleAuthorizationServerMetadata:($)=>{let V=fH(new URL($.url)).origin;return Response.json({issuer:V,authorization_endpoint:`${V}/authorize`,token_endpoint:`${V}/token`,registration_endpoint:`${V}/register`,scopes_supported:["*"],response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:["none","client_secret_post"],code_challenge_methods_supported:["S256","plain"]})},handleAuthorize:($)=>{let F=fH(new URL($.url)),V=F.searchParams.get("redirect_uri"),q=F.searchParams.get("response_type"),U=F.searchParams.get("state"),z=F.searchParams.get("code_challenge"),D=F.searchParams.get("code_challenge_method");if(!V)return Response.json({error:"invalid_request",error_description:"redirect_uri required"},{status:400});if(q!=="code")return Response.json({error:"unsupported_response_type",error_description:"Only 'code' is supported"},{status:400});let L=fH(new URL(`${F.origin}/oauth/callback`)),w=L.toString(),T=vj0({redirectUri:V,clientState:U??void 0,codeChallenge:z??void 0,codeChallengeMethod:D??void 0,oauthCallbackUri:w});L.searchParams.set("state",T);let C=Y.authorizationUrl(L.toString());return Response.redirect(C,302)},handleOAuthCallback:async($)=>{let F=fH(new URL($.url)),V=F.searchParams.get("code"),q=F.searchParams.get("state"),U=F.searchParams.get("error"),z=q?_j0(q):null;if(U){let D=F.searchParams.get("error_description")??"Authorization failed";if(z?.redirectUri){let L=fH(new URL(z.redirectUri));if(L.searchParams.set("error",U),L.searchParams.set("error_description",D),z.clientState)L.searchParams.set("state",z.clientState);return Response.redirect(L.toString(),302)}return Response.json({error:U,error_description:D},{status:400})}if(!V||!z)return Response.json({error:"invalid_request",error_description:"Missing code or state"},{status:400});try{let D=z.oauthCallbackUri??fH(new URL(`${F.origin}/oauth/callback`)).toString(),L={code:V,redirect_uri:D},w=await Y.exchangeCode(L),E={accessToken:w.access_token,tokenType:w.token_type,refreshToken:w.refresh_token,expiresIn:w.expires_in,scope:w.scope,codeChallenge:z.codeChallenge,codeChallengeMethod:z.codeChallengeMethod},T=vj0(E),C=fH(new URL(z.redirectUri));if(C.searchParams.set("code",T),z.clientState)C.searchParams.set("state",z.clientState);return Response.redirect(C.toString(),302)}catch(D){console.error("OAuth callback error:",D);let L=fH(new URL(z.redirectUri));if(L.searchParams.set("error","server_error"),L.searchParams.set("error_description","Failed to exchange authorization code"),z.clientState)L.searchParams.set("state",z.clientState);return Response.redirect(L.toString(),302)}},handleToken:async($)=>{try{let F=$.headers.get("content-type")??"",V;if(F.includes("application/x-www-form-urlencoded")){let E=await $.formData();V=Object.fromEntries(E.entries())}else{let E=await $.json();if(typeof E!=="object"||E===null||Array.isArray(E))return Response.json({error:"invalid_request",error_description:"Request body must be a JSON object"},{status:400});V=E}let{code:q,code_verifier:U,grant_type:z,refresh_token:D}=V;if(z==="refresh_token"){if(typeof D!=="string"||!D)return Response.json({error:"invalid_request",error_description:"refresh_token is required and must be a string"},{status:400});if(!Y.refreshToken)return Response.json({error:"unsupported_grant_type",error_description:"refresh_token grant not supported"},{status:400});let E=await Y.refreshToken(D),T={access_token:E.access_token,token_type:E.token_type};if(E.refresh_token)T.refresh_token=E.refresh_token;if(E.expires_in!==void 0)T.expires_in=E.expires_in;if(E.scope)T.scope=E.scope;return Response.json(T,{headers:{"Cache-Control":"no-store",Pragma:"no-cache"}})}if(z!=="authorization_code")return Response.json({error:"unsupported_grant_type",error_description:"Only authorization_code and refresh_token supported"},{status:400});if(typeof q!=="string"||!q)return Response.json({error:"invalid_request",error_description:"code is required and must be a string"},{status:400});let L=_j0(q);if(!L||!L.accessToken)return Response.json({error:"invalid_grant",error_description:"Invalid or expired code"},{status:400});if(L.codeChallenge){if(typeof U!=="string"||!U)return Response.json({error:"invalid_grant",error_description:"code_verifier required and must be a string"},{status:400});let E;if(L.codeChallengeMethod==="S256"){let C=new TextEncoder().encode(U),P=await crypto.subtle.digest("SHA-256",C);E=btoa(String.fromCharCode(...new Uint8Array(P))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}else E=U;if(E!==L.codeChallenge)return Response.json({error:"invalid_grant",error_description:"Invalid code_verifier"},{status:400})}let w={access_token:L.accessToken,token_type:L.tokenType};if(L.refreshToken)w.refresh_token=L.refreshToken;if(L.expiresIn!==void 0)w.expires_in=L.expiresIn;if(L.scope)w.scope=L.scope;return Response.json(w,{headers:{"Cache-Control":"no-store",Pragma:"no-cache"}})}catch(F){return console.error("Token exchange error:",F),Response.json({error:"server_error",error_description:"Failed to process token request"},{status:500})}},handleClientRegistration:async($)=>{try{let F=await $.json();if(!F.redirect_uris||F.redirect_uris.length===0)return Response.json({error:"invalid_redirect_uri",error_description:"At least one redirect_uri is required"},{status:400});for(let D of F.redirect_uris)if(!xP6(D))return Response.json({error:"invalid_redirect_uri",error_description:`Invalid redirect URI: ${D}`},{status:400});let V=kj0(32),q=F.token_endpoint_auth_method!=="none"?kj0(32):void 0,U=Math.floor(Date.now()/1000),z={client_id:V,client_secret:q,client_name:F.client_name,redirect_uris:F.redirect_uris,grant_types:F.grant_types??["authorization_code"],response_types:F.response_types??["code"],token_endpoint_auth_method:F.token_endpoint_auth_method??"client_secret_post",scope:F.scope,client_id_issued_at:U,client_secret_expires_at:0};if(Y.persistence)await Y.persistence.saveClient(z);return new Response(JSON.stringify(z),{status:201,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache"}})}catch(F){return console.error("Client registration error:",F),Response.json({error:"invalid_client_metadata",error_description:"Invalid client registration request"},{status:400})}},createUnauthorizedResponse:($)=>{let q=`Bearer resource_metadata="${`${fH(new URL($.url)).origin}/.well-known/oauth-protected-resource`}", scope="*"`;return Response.json({jsonrpc:"2.0",error:{code:-32000,message:"Unauthorized: Authentication required"},id:null},{status:401,headers:{"WWW-Authenticate":q,"Access-Control-Expose-Headers":"WWW-Authenticate"}})},hasAuth:($)=>$.headers.has("Authorization")}}var fH=(Y)=>{if(!(Y.hostname==="localhost"||Y.hostname==="127.0.0.1"))Y.protocol="https:";return Y};import{AsyncLocalStorage as gP6}from"async_hooks";var fj0,PS;var uV1=k(()=>{fj0=new gP6,PS={getStore:()=>{return fj0.getStore()},run:(Y,Q,...X)=>fj0.run(Y,Q,...X)}});function x$(Y){return B.object({items:B.array(Y).describe("Array of collection items"),totalCount:B.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:B.boolean().optional().describe("Whether there are more items available")})}function TS(Y){return B.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function lP6(Y){return B.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function dP6(Y){return B.object({item:Y.describe("The created entity with generated id")})}function pP6(Y){return B.object({id:B.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function cP6(Y){return B.object({item:Y.describe("The updated entity")})}function RS(Y){return B.object({item:Y.describe("The deleted entity")})}function hH(Y,Q,X){let J=Y.toUpperCase(),G=X?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:uZ,outputSchema:x$(Q)},{name:`COLLECTION_${J}_GET`,inputSchema:ES,outputSchema:TS(Q)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:lP6(Q),outputSchema:dP6(Q),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:pP6(Q),outputSchema:cP6(Q),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:CS,outputSchema:RS(Q),opt:!0});return K}var bH,uP6,bj0,mP6,uZ,ES,CS;var MG=k(()=>{i1();bH=B.object({id:B.string().describe("Unique identifier for the entity"),title:B.string().describe("Human-readable title for the entity"),description:B.string().nullish().describe("Description of the entity"),created_at:B.string().datetime(),updated_at:B.string().datetime(),created_by:B.string().optional(),updated_by:B.string().optional()}),uP6=B.object({field:B.array(B.string()),operator:B.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:B.unknown()}),bj0=B.lazy(()=>B.union([uP6,B.object({operator:B.enum(["and","or","not"]),conditions:B.array(bj0)})])),mP6=B.object({field:B.array(B.string()),direction:B.enum(["asc","desc"]),nulls:B.enum(["first","last"]).optional()}),uZ=B.object({where:bj0.optional().describe("Filter expression"),orderBy:B.array(mP6).optional().describe("Sort expressions"),limit:B.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:B.number().int().min(0).optional().describe("Number of items to skip")});ES=B.object({id:B.string().describe("ID of the entity to retrieve")});CS=B.object({id:B.string().describe("ID of the entity to delete")})});var nP6,hj0,so8;var xj0=k(()=>{i1();MG();nP6=B.object({id:B.string(),name:B.string(),description:B.string().optional(),inputSchema:B.record(B.string(),B.unknown()),outputSchema:B.record(B.string(),B.unknown()).optional()}),hj0=bH.extend({_meta:B.object({"io.decocms":B.object({id:B.string(),verified:B.boolean(),scopeName:B.string(),appName:B.string(),friendlyName:B.string().nullable().optional(),metadata:B.record(B.string(),B.unknown()).nullable().optional(),publishedAt:B.string().datetime().optional(),updatedAt:B.string().datetime().optional(),tools:B.array(nP6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:B.object({$schema:B.string().optional(),_meta:B.record(B.string(),B.unknown()).optional(),name:B.string().describe("The server name (scope/app)"),title:B.string().optional().describe("User-friendly title"),description:B.string().optional().describe("Server description"),icons:B.array(B.object({src:B.string(),mimeType:B.string().optional(),sizes:B.array(B.string()).optional(),theme:B.enum(["light","dark"]).optional()})).optional(),remotes:B.array(B.object({type:B.enum(["http","stdio","sse"]),url:B.string().optional(),headers:B.array(B.unknown()).optional()})).optional(),packages:B.array(B.unknown()).optional(),repository:B.object({url:B.string(),source:B.string().optional(),subfolder:B.string().optional()}).optional(),version:B.string().optional(),websiteUrl:B.string().optional()})}),so8=hH("registry_app",hj0,{readOnly:!0})});var gj0,gn,uj0,un,mj0,mV1;var lj0=k(()=>{i1();_D();gj0=B.object({specversion:B.literal("1.0").describe("CloudEvents specification version"),id:B.string().describe("Unique identifier for this event (UUID recommended)"),source:B.string().describe("Connection ID of the event publisher"),type:B.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:B.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:B.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:B.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:B.string().url().optional().describe("URI to the schema for the data attribute"),data:B.unknown().optional().describe("Event payload (any JSON value)")}),gn=B.object({events:B.array(gj0).min(1).describe("Batch of CloudEvents to process")}),uj0=B.object({success:B.boolean().optional().describe("Whether this event was processed successfully"),error:B.string().optional().describe("Error message for this event"),retryAfter:B.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),un=B.object({success:B.boolean().optional().describe("Batch success - applies to events not in results"),error:B.string().optional().describe("Batch error message - applies to events not in results"),processedCount:B.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:B.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:B.record(B.string(),uj0).optional().describe("Per-event results keyed by event ID")}),mj0=[{name:"ON_EVENTS",inputSchema:gn,outputSchema:un}],mV1=yH(mj0)});var IS,jS,SS,kS,dj0,pj0,vS,_S,yS,fS,bS,hS,xS,gS,cj0,iP6;var nj0=k(()=>{i1();_D();IS=B.object({type:B.string().min(1).max(255).describe("Event type identifier"),subject:B.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:B.unknown().optional().describe("Event payload"),deliverAt:B.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:B.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),jS=B.object({id:B.string().describe("Unique event ID"),type:B.string().describe("Event type"),source:B.string().describe("Source connection ID"),time:B.string().describe("Event timestamp")}),SS=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),kS=B.object({subscription:B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")})}),dj0=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),pj0=B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")}),vS=B.object({subscriptions:B.array(dj0).describe("Desired subscriptions - system will create/update/delete to match")}),_S=B.object({created:B.number().int().min(0).describe("Number of subscriptions created"),updated:B.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:B.number().int().min(0).describe("Number of subscriptions removed"),unchanged:B.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:B.array(pj0).describe("Current subscriptions after sync")}),yS=B.object({subscriptionId:B.string().describe("Subscription ID to remove")}),fS=B.object({success:B.boolean().describe("Whether unsubscribe was successful"),subscriptionId:B.string().describe("Subscription ID that was removed")}),bS=B.object({eventId:B.string().describe("Event ID to cancel")}),hS=B.object({success:B.boolean().describe("Whether cancellation was successful"),eventId:B.string().describe("Event ID that was cancelled")}),xS=B.object({eventId:B.string().describe("Event ID to acknowledge")}),gS=B.object({success:B.boolean().describe("Whether ACK was successful"),eventId:B.string().describe("Event ID that was acknowledged")}),cj0=[{name:"EVENT_PUBLISH",inputSchema:IS,outputSchema:jS},{name:"EVENT_SUBSCRIBE",inputSchema:SS,outputSchema:kS},{name:"EVENT_UNSUBSCRIBE",inputSchema:yS,outputSchema:fS},{name:"EVENT_CANCEL",inputSchema:bS,outputSchema:hS},{name:"EVENT_ACK",inputSchema:xS,outputSchema:gS},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:vS,outputSchema:_S}],iP6=yH(cj0)});var aP6,rP6,oP6,sP6,tP6,eP6,YE6,QE6,XE6,JE6,GE6,WE6,uS;var mn=k(()=>{i1();aP6=B.object({prefix:B.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:B.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:B.string().optional().describe("Token for pagination from previous response"),delimiter:B.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),rP6=B.object({objects:B.array(B.object({key:B.string().describe("Object key/path"),size:B.number().describe("Object size in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object")})),nextContinuationToken:B.string().optional().describe("Token for fetching next page of results"),isTruncated:B.boolean().describe("Whether there are more results available"),commonPrefixes:B.array(B.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),oP6=B.object({key:B.string().describe("Object key/path to get metadata for")}),sP6=B.object({contentType:B.string().optional().describe("MIME type of the object"),contentLength:B.number().describe("Size of the object in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object"),metadata:B.record(B.string(),B.string()).optional().describe("Custom metadata key-value pairs")}),tP6=B.object({key:B.string().describe("Object key/path to generate URL for"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),eP6=B.object({url:B.string().describe("Presigned URL for downloading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),YE6=B.object({key:B.string().describe("Object key/path for the upload"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:B.string().optional().describe("MIME type for the object being uploaded")}),QE6=B.object({url:B.string().describe("Presigned URL for uploading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),XE6=B.object({key:B.string().describe("Object key/path to delete")}),JE6=B.object({success:B.boolean().describe("Whether the deletion was successful"),key:B.string().describe("The key that was deleted")}),GE6=B.object({keys:B.array(B.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),WE6=B.object({deleted:B.array(B.string()).describe("Array of successfully deleted keys"),errors:B.array(B.object({key:B.string(),message:B.string()})).describe("Array of errors for failed deletions")}),uS=[{name:"LIST_OBJECTS",inputSchema:aP6,outputSchema:rP6},{name:"GET_OBJECT_METADATA",inputSchema:oP6,outputSchema:sP6},{name:"GET_PRESIGNED_URL",inputSchema:tP6,outputSchema:eP6},{name:"PUT_PRESIGNED_URL",inputSchema:YE6,outputSchema:QE6},{name:"DELETE_OBJECT",inputSchema:XE6,outputSchema:JE6},{name:"DELETE_OBJECTS",inputSchema:GE6,outputSchema:WE6}]});function zE6(Y,Q){let X=[];function J(G){if(typeof G==="string"){let K=G.match(/@(\w+)/g);if(K)for(let W of K){let Z=W.substring(1);if(Q.has(Z))X.push(Z)}}else if(Array.isArray(G))G.forEach(J);else if(typeof G==="object"&&G!==null)Object.values(G).forEach(J)}return J(Y.input),[...new Set(X)]}function oj0(Y){let Q=new Set(Y.map((W)=>W.name)),X=new Map;for(let W of Y)X.set(W.name,zE6(W,Q));let J=new Set,G=new Set;function K(W,Z){if(G.has(W))return[...Z,W];if(J.has(W))return null;J.add(W),G.add(W);let H=X.get(W)||[];for(let $ of H){let F=K($,[...Z,W]);if(F)return F}return G.delete(W),null}for(let W of Y){let Z=K(W.name,[]);if(Z)return{isValid:!1,error:`Circular dependency detected: ${Z.join(" -> ")}`}}return{isValid:!0}}var lV1,ZE6,Fs8,KE6,HE6,ij0,yD,$E6,aj0,FE6,Vs8,VE6,rj0,qE6,BE6,UE6,qs8,Bs8;var DA=k(()=>{i1();_D();MG();lV1=B.object({toolName:B.string().describe("Name of the tool to invoke on that connection"),transformCode:B.string().optional().describe("Pure TypeScript function for data transformation of the tool call result. Must be a TypeScript file that declares the Output interface and exports a default function: `interface Output { ... } export default async function(input): Output { ... }`\n The input will match with the tool call outputSchema. If transformCode is not provided, the tool call result will be used as the step output. \n Providing an transformCode is recommended because it both allows you to transform the data and validate it against a JSON Schema - tools are ephemeral and may return unexpected data.")}),ZE6=B.object({code:B.string().describe(`Pure TypeScript function for data transformation. Useful to merge data from multiple steps and transform it. Must be a TypeScript file that declares the Output interface and exports a default function: \`interface Output { ... } export default async function(input): Output { ... }\`
1045
+ `.trim()});import{sql as eI0}from"kysely";var Yj0;var Qj0=k(()=>{Yj0={name:"001-private-registry",async up(Y){await Y.schema.createTable("private_registry_item").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("title","text",(Q)=>Q.notNull()).addColumn("description","text").addColumn("server_json","text",(Q)=>Q.notNull()).addColumn("meta_json","text").addColumn("tags","text").addColumn("categories","text").addColumn("is_public","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(eI0`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Q)=>Q.notNull().defaultTo(eI0`CURRENT_TIMESTAMP`)).addColumn("created_by","text",(Q)=>Q.references("user.id").onDelete("set null")).execute(),await Y.schema.createIndex("idx_private_registry_item_org").on("private_registry_item").column("organization_id").execute(),await Y.schema.createIndex("idx_private_registry_item_org_public").on("private_registry_item").columns(["organization_id","is_public"]).execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_item_org_public").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_item_org").ifExists().execute(),await Y.schema.dropTable("private_registry_item").ifExists().execute()}}});import{sql as Xj0}from"kysely";var Jj0;var Gj0=k(()=>{Jj0={name:"002-publish-requests",async up(Y){await Y.schema.createTable("private_registry_publish_request").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("status","text",(Q)=>Q.notNull().defaultTo("pending")).addColumn("title","text",(Q)=>Q.notNull()).addColumn("description","text").addColumn("server_json","text",(Q)=>Q.notNull()).addColumn("meta_json","text").addColumn("requester_name","text").addColumn("requester_email","text").addColumn("reviewer_notes","text").addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(Xj0`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Q)=>Q.notNull().defaultTo(Xj0`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_publish_request_org_status").on("private_registry_publish_request").columns(["organization_id","status"]).execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_publish_request_org_status").ifExists().execute(),await Y.schema.dropTable("private_registry_publish_request").ifExists().execute()}}});import{sql as iA6}from"kysely";var Wj0;var Zj0=k(()=>{Wj0={name:"003-publish-api-keys",async up(Y){await Y.schema.createTable("private_registry_publish_api_key").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("name","text",(Q)=>Q.notNull()).addColumn("key_hash","text",(Q)=>Q.notNull()).addColumn("prefix","text",(Q)=>Q.notNull()).addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(iA6`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_publish_api_key_org").on("private_registry_publish_api_key").columns(["organization_id"]).execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_publish_api_key_org").ifExists().execute(),await Y.schema.dropTable("private_registry_publish_api_key").ifExists().execute()}}});var Kj0;var Hj0=k(()=>{Kj0={name:"004-publish-request-requested-id",async up(Y){await Y.schema.alterTable("private_registry_publish_request").addColumn("requested_id","text").execute()},async down(Y){await Y.schema.alterTable("private_registry_publish_request").dropColumn("requested_id").execute()}}});import{sql as kn}from"kysely";var $j0;var Fj0=k(()=>{$j0={name:"005-monitor-runs",async up(Y){await Y.schema.createTable("private_registry_monitor_run").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("status","text",(Q)=>Q.notNull().defaultTo("pending")).addColumn("config_snapshot","text").addColumn("total_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("tested_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("passed_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("failed_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("skipped_items","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("current_item_id","text").addColumn("started_at","text").addColumn("finished_at","text").addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_monitor_run_org_created").on("private_registry_monitor_run").columns(["organization_id","created_at"]).execute(),await Y.schema.createTable("private_registry_monitor_result").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("run_id","text",(Q)=>Q.notNull().references("private_registry_monitor_run.id").onDelete("cascade")).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("item_id","text",(Q)=>Q.notNull()).addColumn("item_title","text",(Q)=>Q.notNull()).addColumn("status","text",(Q)=>Q.notNull()).addColumn("error_message","text").addColumn("connection_ok","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("tools_listed","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("tool_results","text").addColumn("agent_summary","text").addColumn("duration_ms","integer",(Q)=>Q.notNull().defaultTo(0)).addColumn("action_taken","text",(Q)=>Q.notNull().defaultTo("none")).addColumn("tested_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_monitor_result_run").on("private_registry_monitor_result").columns(["run_id","tested_at"]).execute(),await Y.schema.createIndex("idx_private_registry_monitor_result_run_status").on("private_registry_monitor_result").columns(["run_id","status"]).execute(),await Y.schema.createTable("private_registry_monitor_connection").addColumn("id","text",(Q)=>Q.primaryKey()).addColumn("organization_id","text",(Q)=>Q.notNull().references("organization.id").onDelete("cascade")).addColumn("item_id","text",(Q)=>Q.notNull()).addColumn("connection_id","text",(Q)=>Q.notNull().references("connections.id").onDelete("cascade")).addColumn("auth_status","text",(Q)=>Q.notNull().defaultTo("none")).addColumn("created_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).addColumn("updated_at","text",(Q)=>Q.notNull().defaultTo(kn`CURRENT_TIMESTAMP`)).execute(),await Y.schema.createIndex("idx_private_registry_monitor_connection_org_item").on("private_registry_monitor_connection").columns(["organization_id","item_id"]).unique().execute()},async down(Y){await Y.schema.dropIndex("idx_private_registry_monitor_connection_org_item").ifExists().execute(),await Y.schema.dropTable("private_registry_monitor_connection").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_monitor_result_run_status").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_monitor_result_run").ifExists().execute(),await Y.schema.dropTable("private_registry_monitor_result").ifExists().execute(),await Y.schema.dropIndex("idx_private_registry_monitor_run_org_created").ifExists().execute(),await Y.schema.dropTable("private_registry_monitor_run").ifExists().execute()}}});var Vj0;var qj0=k(()=>{Vj0={name:"006-unlisted",async up(Y){await Y.schema.alterTable("private_registry_item").addColumn("is_unlisted","integer",(Q)=>Q.notNull().defaultTo(0)).execute()},async down(Y){await Y.schema.alterTable("private_registry_item").dropColumn("is_unlisted").execute()}}});var Bj0;var Uj0=k(()=>{Qj0();Gj0();Zj0();Hj0();Fj0();qj0();Bj0=[Yj0,Jj0,Wj0,Kj0,$j0,Vj0]});function aA6(Y){let Q=Y;if(!Q||typeof Q!=="object"||!("method"in Q))return null;switch(Q.method){case"initialize":{let X=Q?.params?.protocolVersion;if(!X)return null;return{type:"emit",message:{result:{protocolVersion:X,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Q.jsonrpc??"2.0",id:Q.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var vn;var yV1=k(()=>{AR();vn=class vn extends bV{constructor(Y,Q){super(Y,Q)}send(Y,Q){let X=aA6(Y);if(X?.type==="emit")return this.onmessage?.(X.message),Promise.resolve();if(X?.type==="suppress")return Promise.resolve();return super.send(Y,Q)}}});function AS(Y,Q){if(Y===Q)return!0;if(Y==null||Q==null)return Y===Q;if(typeof Y!==typeof Q)return!1;if(Array.isArray(Y)&&Array.isArray(Q)){if(Y.length!==Q.length)return!1;return Y.every((X,J)=>AS(X,Q[J]))}if(typeof Y==="object"&&typeof Q==="object"){let X=Object.keys(Y),J=Object.keys(Q);if(X.length!==J.length)return!1;return X.every((G)=>J.includes(G)&&AS(Y[G],Q[G]))}return!1}function OP6(){return(Y)=>{if(!Array.isArray(Y))return!0;let Q=[];return Y.every((X)=>{if(Q.some((G)=>AS(X,G)))return!1;return Q.push(X),!0})}}function _n(Y,Q){return Y.safeParse(Q).success}function rX(Y){if(typeof Y==="boolean")return Y?B.any():B.never();let Q={};for(let G of kP6)G.apply(Q,Y);let X=[];if(Q.string!==!1)X.push(Q.string||B.string());if(Q.number!==!1)X.push(Q.number||B.number());if(Q.boolean!==!1)X.push(Q.boolean||B.boolean());if(Q.null!==!1)X.push(Q.null||B.null());if(Q.array!==!1)X.push(Q.array||B.array(B.any()));if(Q.tuple!==!1&&Q.tuple!==void 0)X.push(Q.tuple);if(Q.object!==!1)if(Q.object)X.push(Q.object);else{let G=B.custom((K)=>{return typeof K==="object"&&K!==null&&!Array.isArray(K)},"Must be an object, not an array");X.push(G)}if(Q.file!==!1&&Q.file!==void 0)X.push(Q.file);let J;if(X.length===0)J=B.never();else if(X.length===1)J=X[0];else if(!Object.keys(Y).some((K)=>K!=="$schema"&&K!=="title"&&K!=="description"))J=B.any();else J=B.union(X);for(let G of vP6)J=G.apply(J,Y);return J}var rA6=class{apply(Y,Q){if(!Q.type)return;let X=Array.isArray(Q.type)?Q.type:[Q.type],J=new Set(X);if(!J.has("string"))Y.string=!1;if(!J.has("number")&&!J.has("integer"))Y.number=!1;if(!J.has("boolean"))Y.boolean=!1;if(!J.has("null"))Y.null=!1;if(!J.has("array"))Y.array=!1;if(!J.has("object"))Y.object=!1;if(J.has("integer")&&Y.number!==!1){let G=Y.number||B.number();if(G instanceof B.ZodNumber)Y.number=G.int()}}},oA6=class{apply(Y,Q){if(Q.const===void 0)return;let X=Q.const;if(Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1,typeof X==="string")Y.string=B.literal(X);else if(typeof X==="number")Y.number=B.literal(X);else if(typeof X==="boolean")Y.boolean=B.literal(X);else if(X===null)Y.null=B.null();else if(Array.isArray(X))Y.array=void 0;else if(typeof X==="object")Y.object=void 0}},sA6=class{apply(Y,Q){if(!Q.enum)return;if(Q.enum.length===0){if(!Q.type)Y.string=!1,Y.number=!1,Y.boolean=!1,Y.null=!1,Y.array=!1,Y.object=!1;return}let X={string:Q.enum.filter((J)=>typeof J==="string"),number:Q.enum.filter((J)=>typeof J==="number"),boolean:Q.enum.filter((J)=>typeof J==="boolean"),null:Q.enum.filter((J)=>J===null),array:Q.enum.filter((J)=>Array.isArray(J)),object:Q.enum.filter((J)=>typeof J==="object"&&J!==null&&!Array.isArray(J))};Y.string=this.createTypeSchema(X.string,"string"),Y.number=this.createTypeSchema(X.number,"number"),Y.boolean=this.createTypeSchema(X.boolean,"boolean"),Y.null=X.null.length>0?B.null():!1,Y.array=X.array.length>0?void 0:!1,Y.object=X.object.length>0?void 0:!1}createTypeSchema(Y,Q){if(Y.length===0)return!1;if(Y.length===1)return B.literal(Y[0]);if(Q==="string")return B.enum(Y);if(Q==="number"){let[X,J,...G]=Y;return B.union([B.literal(X),B.literal(J),...G.map((K)=>B.literal(K))])}if(Q==="boolean")return B.union([B.literal(!0),B.literal(!1)]);return!1}},tA6=class{apply(Y,Q){let X=Q;if(X.type==="string"&&X.format==="binary"&&X.contentEncoding==="binary"){let J=B.file();if(X.minLength!==void 0)J=J.min(X.minLength);if(X.maxLength!==void 0)J=J.max(X.maxLength);if(X.contentMediaType!==void 0)J=J.mime(X.contentMediaType);Y.file=J,Y.string=!1}}},eA6=class{apply(Y,Q){let X=Q;if(Q.type===void 0&&(X.minLength!==void 0||X.maxLength!==void 0||X.pattern!==void 0)){if(Y.string===void 0)Y.string=B.string()}}},YP6=class{apply(Y,Q){let X=Q;if(X.minLength===void 0)return;if(Y.string!==!1){let J=Y.string||B.string();if(J instanceof B.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length>=X.minLength},{message:`String must be at least ${X.minLength} characters long`})}}},QP6=class{apply(Y,Q){let X=Q;if(X.maxLength===void 0)return;if(Y.string!==!1){let J=Y.string||B.string();if(J instanceof B.ZodString)Y.string=J.refine((G)=>{return Array.from(G).length<=X.maxLength},{message:`String must be at most ${X.maxLength} characters long`})}}},XP6=class{apply(Y,Q){let X=Q;if(!X.pattern)return;if(Y.string!==!1){let J=Y.string||B.string();if(J instanceof B.ZodString){let G=new RegExp(X.pattern);Y.string=J.regex(G)}}}},JP6=class{apply(Y,Q){let X=Q;if(X.minimum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)Y.number=J.min(X.minimum)}}},GP6=class{apply(Y,Q){let X=Q;if(X.maximum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)Y.number=J.max(X.maximum)}}},WP6=class{apply(Y,Q){let X=Q;if(X.exclusiveMinimum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)if(typeof X.exclusiveMinimum==="number")Y.number=J.gt(X.exclusiveMinimum);else Y.number=!1}}},ZP6=class{apply(Y,Q){let X=Q;if(X.exclusiveMaximum===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)if(typeof X.exclusiveMaximum==="number")Y.number=J.lt(X.exclusiveMaximum);else Y.number=!1}}},KP6=class{apply(Y,Q){let X=Q;if(X.multipleOf===void 0)return;if(Y.number!==!1){let J=Y.number||B.number();if(J instanceof B.ZodNumber)Y.number=J.refine((G)=>{if(X.multipleOf===0)return!1;let K=G/X.multipleOf,W=Math.round(K),Z=Math.min(Math.abs(G)*Number.EPSILON*10,Math.abs(X.multipleOf)*Number.EPSILON*10);return Math.abs(K-W)<=Z/Math.abs(X.multipleOf)},{message:`Must be a multiple of ${X.multipleOf}`})}}},HP6=class{apply(Y,Q){let X=Q;if(Q.type===void 0&&(X.minItems!==void 0||X.maxItems!==void 0||X.items!==void 0||X.prefixItems!==void 0)){if(Y.array===void 0)Y.array=B.array(B.any())}}},$P6=class{apply(Y,Q){let X=Q;if(X.minItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||B.array(B.any())).min(X.minItems)}},FP6=class{apply(Y,Q){let X=Q;if(X.maxItems===void 0)return;if(Y.array!==!1)Y.array=(Y.array||B.array(B.any())).max(X.maxItems)}},VP6=class{apply(Y,Q){let X=Q;if(Y.array===!1)return;if(Array.isArray(X.items))Y.array=Y.array||B.array(B.any());else if(X.items&&typeof X.items!=="boolean"&&!X.prefixItems){let J=rX(X.items),G=B.array(J);if(Y.array&&Y.array instanceof B.ZodArray){let K=Y.array._def;if(K.checks)K.checks.forEach((W)=>{if(W._zod&&W._zod.def){let Z=W._zod.def;if(Z.check==="min_length"&&Z.minimum!==void 0)G=G.min(Z.minimum);else if(Z.check==="max_length"&&Z.maximum!==void 0)G=G.max(Z.maximum)}})}Y.array=G}else if(typeof X.items==="boolean"&&X.items===!1)if(!X.prefixItems)Y.array=B.array(B.any()).max(0);else Y.array=Y.array||B.array(B.any());else if(typeof X.items==="boolean"&&X.items===!0)Y.array=Y.array||B.array(B.any());else if(X.prefixItems)Y.array=Y.array||B.array(B.any())}},qP6=class{apply(Y,Q){if(Q.type!=="array")return;let X=Q;if(!Array.isArray(X.items))return;if(Y.array===!1)return;let J=X.items.map((K)=>rX(K)),G;if(J.length===0)G=B.tuple([]);else G=B.tuple(J);if(X.minItems!==void 0&&X.minItems>J.length)G=!1;if(X.maxItems!==void 0&&X.maxItems<J.length)G=!1;Y.tuple=G,Y.array=!1}},BP6=class{apply(Y,Q){let X=Q;if(Y.object===!1)return;if(X.properties||X.required||X.additionalProperties!==void 0)Y.object=Y.object||B.object({}).passthrough()}},UP6=class{apply(Y,Q){let X=Q;if(Q.type===void 0&&(X.maxProperties!==void 0||X.minProperties!==void 0)){if(Y.object===void 0)Y.object=B.object({}).passthrough()}}},zP6=class{apply(Y,Q){let X=Q;if(X.maxProperties===void 0)return;if(Y.object!==!1){let J=Y.object||B.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length<=X.maxProperties,{message:`Object must have at most ${X.maxProperties} properties`})}}},DP6=class{apply(Y,Q){let X=Q;if(X.minProperties===void 0)return;if(Y.object!==!1){let J=Y.object||B.object({}).passthrough();Y.object=J.refine((G)=>Object.keys(G).length>=X.minProperties,{message:`Object must have at least ${X.minProperties} properties`})}}},NP6=class{apply(Y,Q){if(!Q.not)return Y;let X=rX(Q.not);return Y.refine((J)=>!_n(X,J),{message:"Value must not match the 'not' schema"})}},LP6=class{apply(Y,Q){if(Q.uniqueItems!==!0)return Y;return Y.refine(OP6(),{message:"Array items must be unique"})}},MP6=class{apply(Y,Q){if(!Q.allOf||Q.allOf.length===0)return Y;return Q.allOf.map((J)=>rX(J)).reduce((J,G)=>B.intersection(J,G),Y)}},wP6=class{apply(Y,Q){if(!Q.anyOf||Q.anyOf.length===0)return Y;let X=Q.anyOf.length===1?rX(Q.anyOf[0]):B.union([rX(Q.anyOf[0]),rX(Q.anyOf[1]),...Q.anyOf.slice(2).map((J)=>rX(J))]);return B.intersection(Y,X)}},AP6=class{apply(Y,Q){if(!Q.oneOf||Q.oneOf.length===0)return Y;let X=Q.oneOf.map((J)=>rX(J));return Y.refine((J)=>{let G=0;for(let K of X)if(K.safeParse(J).success){if(G++,G>1)return!1}return G===1},{message:"Value must match exactly one of the oneOf schemas"})}},PP6=class{apply(Y,Q){let X=Q;if(X.prefixItems&&Array.isArray(X.prefixItems)){let G=X.prefixItems.map((K)=>rX(K));return Y.refine((K)=>{if(!Array.isArray(K))return!0;for(let W=0;W<Math.min(K.length,G.length);W++)if(!_n(G[W],K[W]))return!1;if(K.length>G.length){if(typeof X.items==="boolean"&&X.items===!1)return!1;else if(X.items&&typeof X.items==="object"&&!Array.isArray(X.items)){let W=rX(X.items);for(let Z=G.length;Z<K.length;Z++)if(!_n(W,K[Z]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return Y}},EP6=class{apply(Y,Q){let X=Q;if(!X.properties&&!X.required&&X.additionalProperties!==!1)return Y;if(Y instanceof B.ZodObject||Y instanceof B.ZodRecord){let J={};if(X.properties){for(let[G,K]of Object.entries(X.properties))if(K!==void 0)J[G]=rX(K)}if(X.required&&Array.isArray(X.required)){let G=new Set(X.required);for(let K of Object.keys(J))if(!G.has(K))J[K]=J[K].optional()}else for(let G of Object.keys(J))J[G]=J[G].optional();if(X.additionalProperties===!1)return B.object(J);else return B.object(J).passthrough()}return Y.refine((J)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return!0;if(X.properties){for(let[G,K]of Object.entries(X.properties))if(K!==void 0){if(Object.getOwnPropertyDescriptor(J,G)!==void 0){if(!rX(K).safeParse(J[G]).success)return!1}}}if(X.required&&Array.isArray(X.required)){for(let G of X.required)if(Object.getOwnPropertyDescriptor(J,G)===void 0)return!1}if(X.additionalProperties===!1&&X.properties){let G=new Set(Object.keys(X.properties));for(let K in J)if(!G.has(K))return!1}return!0},{message:"Object constraints validation failed"})}},TP6=class{apply(Y,Q){if(!Q.enum||Q.enum.length===0)return Y;let X=Q.enum.filter((J)=>Array.isArray(J)||typeof J==="object"&&J!==null);if(X.length===0)return Y;return Y.refine((J)=>{if(typeof J!=="object"||J===null)return!0;return X.some((G)=>AS(J,G))},{message:"Value must match one of the enum values"})}},CP6=class{apply(Y,Q){if(Q.const===void 0)return Y;let X=Q.const;if(typeof X!=="object"||X===null)return Y;return Y.refine((J)=>AS(J,X),{message:"Value must equal the const value"})}},RP6=class{apply(Y,Q){if(Q.description)Y=Y.describe(Q.description);return Y}},IP6=class{apply(Y,Q){var X;let J=Q;if(!((X=J.required)==null?void 0:X.includes("__proto__"))||Q.type!==void 0)return Y;return B.any().refine((G)=>this.validateRequired(G,J.required),{message:"Missing required properties"})}validateRequired(Y,Q){if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;return Q.every((X)=>Object.prototype.hasOwnProperty.call(Y,X))}},jP6=class{apply(Y,Q){var X;let J=Q;if(J.contains===void 0)return Y;let G=rX(J.contains),K=(X=J.minContains)!=null?X:1,W=J.maxContains;return Y.refine((Z)=>{if(!Array.isArray(Z))return!0;let H=0;for(let $ of Z)if(_n(G,$))H++;if(H<K)return!1;if(W!==void 0&&H>W)return!1;return!0},{message:"Array must contain required items matching the schema"})}},SP6=class{apply(Y,Q){let{default:X}=Q;if(X===void 0)return Y;if(!Y.safeParse(X).success)return Y;return Y.default(X)}},kP6,vP6;var zj0=k(()=>{o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();o6();kP6=[new oA6,new sA6,new rA6,new tA6,new eA6,new HP6,new UP6,new YP6,new QP6,new XP6,new JP6,new GP6,new WP6,new ZP6,new KP6,new qP6,new $P6,new FP6,new VP6,new zP6,new DP6,new BP6],vP6=[new IP6,new TP6,new CP6,new MP6,new wP6,new AP6,new PP6,new EP6,new jP6,new NP6,new LP6,new SP6,new RP6]});class fV1{constructor(Y){this._url=Y}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((Y,Q)=>{this._socket=new WebSocket(this._url,_P6),this._socket.onerror=(X)=>{let J="error"in X?X.error:Error(`WebSocket error: ${JSON.stringify(X)}`);Q(J),this.onerror?.(J)},this._socket.onopen=()=>{Y()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(X)=>{let J;try{J=mG.parse(JSON.parse(X.data))}catch(G){this.onerror?.(G);return}this.onmessage?.(J)}})}async close(){this._socket?.close()}send(Y){return new Promise((Q,X)=>{if(!this._socket){X(Error("Not connected"));return}this._socket?.send(JSON.stringify(Y)),Q()})}}var _P6="mcp";var Dj0=k(()=>{vQ()});var Oj0,Nj0=async(Y,Q,X)=>{let J=yP6(Y.connection,Q,X);if(!J)throw Error("Unknown MCP connection type");let G=new Oj0({name:Y?.name??"MCP Client",version:"1.0.0"});return await G.connect(J),{client:G,callStreamableTool:(K,W,Z)=>{if(Y.connection.type!=="HTTP")throw Error("HTTP connection required");let H=new Headers(X);if(!H.has("Authorization"))H.set("Authorization",`Bearer ${Y.connection.token}`);for(let[V,q]of Object.entries(Y.connection.headers??{}))H.set(V,q);let $=new URL(Y.connection.url),F=$.pathname.replace(/\/+$/,"")||"/";return $.pathname=`${F}/call-tool/${encodeURIComponent(K)}`,fetch($.href,{method:"POST",redirect:"manual",body:JSON.stringify(W),headers:H,signal:Z})}}},yP6=(Y,Q,X)=>{if(Y.type==="Websocket")return new fV1(new URL(Y.url));if(Y.type!=="SSE"&&Y.type!=="HTTP")return null;let G={...Y.token?{authorization:`Bearer ${Y.token}`}:{},...X??{},..."headers"in Y?Y.headers||{}:{}};if(Y.type==="SSE"){let K={requestInit:{headers:G,signal:Q}};if(Y.token)K.eventSourceInit={fetch:(W,Z)=>{return fetch(W,{...Z,headers:{...G,Accept:"text/event-stream"},signal:Q})}};return new SD(new URL(Y.url),K)}return new vn(new URL(Y.url),{requestInit:{headers:G,signal:Q,credentials:"include"}})};var Lj0=k(()=>{qz();Rn();Dj0();vQ();yV1();Oj0=class Oj0 extends G5{constructor(Y,Q){super(Y,Q)}async listTools(Y,Q){return await this.request({method:"tools/list",params:Y},cC,Q)}}});function Aj0(Y){let Q=(X)=>{if("connection"in Y)return Nj0({connection:Y.connection},void 0,X);return Y.client};return new Proxy({},{get(X,J){if(J==="toJSON")return null;if(typeof J!=="string")throw Error("Name must be a string");if(J==="listTools")return Z;async function G(H,$=J){let F=Y?.debugId?.(),V=F?{"x-trace-debug-id":F}:void 0,{client:q,callStreamableTool:U}=await Q(V);if(Y?.streamable?.[String($)]){if(!U)throw Error(`Tool ${String($)} requires streaming support but client doesn't provide callStreamableTool`);return await U(String($),H)}let{structuredContent:z,isError:D,content:L}=await q.callTool({name:String($),arguments:H});if(D){let E=L?.[0]?.text,T=typeof E==="string"?Mj0(E):null,C=T?.code&&typeof Y?.getErrorByStatusCode==="function"?Y.getErrorByStatusCode(T.code,T.message,T.traceId):null;if(C)throw C;throw Error(`Tool ${String($)} returned an error: ${JSON.stringify(z??L)}`)}if(z!==void 0)return z;let w=L?.[0]?.text;return typeof w==="string"?Mj0(w):void 0}async function K(){let{client:H}=await Q(),{tools:$}=await H.listTools();return $}async function W(){if(!("connection"in Y))return K();let H=Y.connection,$=JSON.stringify(H);try{if(!yn.has($))yn.set($,K());return await yn.get($)}catch(F){console.error("Failed to list tools",F),yn.delete($);return}}async function Z(){return(await W()??[]).map(($)=>wj0($,G))}return G.asTool=async()=>{let $=(await W()??[]).find((F)=>F.name===J);if(!$)throw Error(`Tool ${J} not found`);return wj0($,G)},G}})}var Mj0=(Y)=>{try{return JSON.parse(Y)}catch{return Y}},yn,wj0=(Y,Q)=>{return{...Y,id:Y.name,inputSchema:Y.inputSchema?rX(Y.inputSchema):void 0,outputSchema:Y.outputSchema?rX(Y.outputSchema):void 0,execute:(X)=>{return Q(X.context,Y.name)}}};var Pj0=k(()=>{zj0();Lj0();yn=new Map});function vD(Y){return Aj0(Y)}var bn;var bV1=k(()=>{Pj0();bn=new Proxy({},{get(Y,Q){if(Q==="toJSON")return null;if(Q==="forConnection")return(X)=>vD({connection:X});return global[Q]}})});function hn(Y){return{isImplementedBy:(Q)=>{for(let X of Y){let J=typeof X.name==="string"?new RegExp(`^${X.name}$`):X.name,G=Q.find((K)=>J.test(K.name));if(!G&&X.opt)continue;if(!G)return!1}return!0}}}var yH=(Y)=>{return{...hn(Y),forClient:(Q)=>{return vD({client:Q,streamable:Y.reduce((X,J)=>{return X[J.name]=J.streamable===!0,X},{})})},forConnection:(Q)=>{return vD({connection:Q,streamable:Y.reduce((X,J)=>{return X[J.name]=J.streamable===!0,X},{})})}}};var _D=k(()=>{bV1()});var Ej0=k(()=>{yV1();bV1();_D()});var hV1=k(()=>{Ej0()});var gV1=(Y)=>{return typeof Y==="object"&&Y!==null&&typeof Y.__type==="string"&&typeof Y.value==="string"},Tj0=(Y,Q,X)=>{let J=X?{"x-caller-app":X}:void 0;if(Q.cookie)J??={},J.cookie=Q.cookie;if(Q.token)J??={},J["x-mesh-token"]=Q.token;return console.log("[EventBus:Debug] proxyConnectionForId",{connectionId:Y,meshUrl:Q.meshUrl,hasToken:!!Q.token,tokenPreview:Q.token?.slice(0,20)??"NONE",targetUrl:new URL(`/mcp/${Y}`,Q.meshUrl).href}),{type:"HTTP",url:new URL(`/mcp/${Y}`,Q.meshUrl).href,token:Q.token,headers:J}},fP6=(Y,Q,X)=>{let J=Tj0(Y,Q,X);return new Proxy(bn.forConnection(J),{get(G,K){if(K==="value")return Y;if(K==="__type")return X;return G[K]}})},xV1=(Y,Q)=>{if(Y===null||Y===void 0)return Y;if(Array.isArray(Y))return Y.map((X)=>xV1(X,Q));if(typeof Y==="object"){if(gV1(Y))return fP6(Y.value,Q,Y.__type);let X={};for(let[J,G]of Object.entries(Y))X[J]=xV1(G,Q);return X}return Y},Cj0=(Y)=>{return xV1(Y.state,Y)};var xn=k(()=>{hV1()});var bP6,Rj0=(Y,Q,X)=>{if(!Q)return null;if(Y===void 0||Y==="*")return"*";if(typeof Y==="string")return Y===Q?Y:null;if(Array.isArray(Y))return Y.includes(Q)?Q:null;if(typeof Y==="function")return Y(Q,X)??null;return null},hP6=(Y,Q,X)=>{let J=Q.headers.get("Origin"),G=Rj0(X.origin,J,Q);if(G)Y.set("Access-Control-Allow-Origin",G);if(X.credentials)Y.set("Access-Control-Allow-Credentials","true");if(X.exposeHeaders?.length)Y.set("Access-Control-Expose-Headers",X.exposeHeaders.join(", "))},Ij0=(Y,Q)=>{let X=new Headers,J=Y.headers.get("Origin"),G=Rj0(Q.origin,J,Y);if(G)X.set("Access-Control-Allow-Origin",G);if(Q.credentials)X.set("Access-Control-Allow-Credentials","true");let K=Q.allowMethods??bP6;X.set("Access-Control-Allow-Methods",K.join(", "));let W=Y.headers.get("Access-Control-Request-Headers");if(Q.allowHeaders?.length)X.set("Access-Control-Allow-Headers",Q.allowHeaders.join(", "));else if(W)X.set("Access-Control-Allow-Headers",W);if(Q.maxAge!==void 0)X.set("Access-Control-Max-Age",Q.maxAge.toString());return new Response(null,{status:204,headers:X})},jj0=(Y,Q,X)=>{let J=new Headers(Y.headers);return hP6(J,Q,X),new Response(Y.body,{status:Y.status,statusText:Y.statusText,headers:J})};var Sj0=k(()=>{bP6=["GET","HEAD","PUT","POST","DELETE","PATCH"]});function kj0(Y=32){let X=new Uint8Array(Y);return crypto.getRandomValues(X),Array.from(X,(J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[J%62]).join("")}function xP6(Y){try{let Q=new URL(Y);return Q.protocol==="https:"||Q.hostname==="localhost"||Q.hostname==="127.0.0.1"||!Q.protocol.startsWith("http")}catch{return!1}}function vj0(Y){return btoa(JSON.stringify(Y)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function _j0(Y){try{let Q=Y.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(Q))}catch{return null}}function yj0(Y){return{handleProtectedResourceMetadata:($)=>{let F=fH(new URL($.url)),V=`${F.origin}/mcp`;return Response.json({resource:V,authorization_servers:[F.origin],scopes_supported:["*"],bearer_methods_supported:["header"],resource_signing_alg_values_supported:["RS256","none"]})},handleAuthorizationServerMetadata:($)=>{let V=fH(new URL($.url)).origin;return Response.json({issuer:V,authorization_endpoint:`${V}/authorize`,token_endpoint:`${V}/token`,registration_endpoint:`${V}/register`,scopes_supported:["*"],response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:["none","client_secret_post"],code_challenge_methods_supported:["S256","plain"]})},handleAuthorize:($)=>{let F=fH(new URL($.url)),V=F.searchParams.get("redirect_uri"),q=F.searchParams.get("response_type"),U=F.searchParams.get("state"),z=F.searchParams.get("code_challenge"),D=F.searchParams.get("code_challenge_method");if(!V)return Response.json({error:"invalid_request",error_description:"redirect_uri required"},{status:400});if(q!=="code")return Response.json({error:"unsupported_response_type",error_description:"Only 'code' is supported"},{status:400});let L=fH(new URL(`${F.origin}/oauth/callback`)),w=L.toString(),T=vj0({redirectUri:V,clientState:U??void 0,codeChallenge:z??void 0,codeChallengeMethod:D??void 0,oauthCallbackUri:w});L.searchParams.set("state",T);let C=Y.authorizationUrl(L.toString());return Response.redirect(C,302)},handleOAuthCallback:async($)=>{let F=fH(new URL($.url)),V=F.searchParams.get("code"),q=F.searchParams.get("state"),U=F.searchParams.get("error"),z=q?_j0(q):null;if(U){let D=F.searchParams.get("error_description")??"Authorization failed";if(z?.redirectUri){let L=fH(new URL(z.redirectUri));if(L.searchParams.set("error",U),L.searchParams.set("error_description",D),z.clientState)L.searchParams.set("state",z.clientState);return Response.redirect(L.toString(),302)}return Response.json({error:U,error_description:D},{status:400})}if(!V||!z)return Response.json({error:"invalid_request",error_description:"Missing code or state"},{status:400});try{let D=z.oauthCallbackUri??fH(new URL(`${F.origin}/oauth/callback`)).toString(),L={code:V,redirect_uri:D},w=await Y.exchangeCode(L),E={accessToken:w.access_token,tokenType:w.token_type,refreshToken:w.refresh_token,expiresIn:w.expires_in,scope:w.scope,codeChallenge:z.codeChallenge,codeChallengeMethod:z.codeChallengeMethod},T=vj0(E),C=fH(new URL(z.redirectUri));if(C.searchParams.set("code",T),z.clientState)C.searchParams.set("state",z.clientState);return Response.redirect(C.toString(),302)}catch(D){console.error("OAuth callback error:",D);let L=fH(new URL(z.redirectUri));if(L.searchParams.set("error","server_error"),L.searchParams.set("error_description","Failed to exchange authorization code"),z.clientState)L.searchParams.set("state",z.clientState);return Response.redirect(L.toString(),302)}},handleToken:async($)=>{try{let F=$.headers.get("content-type")??"",V;if(F.includes("application/x-www-form-urlencoded")){let E=await $.formData();V=Object.fromEntries(E.entries())}else{let E=await $.json();if(typeof E!=="object"||E===null||Array.isArray(E))return Response.json({error:"invalid_request",error_description:"Request body must be a JSON object"},{status:400});V=E}let{code:q,code_verifier:U,grant_type:z,refresh_token:D}=V;if(z==="refresh_token"){if(typeof D!=="string"||!D)return Response.json({error:"invalid_request",error_description:"refresh_token is required and must be a string"},{status:400});if(!Y.refreshToken)return Response.json({error:"unsupported_grant_type",error_description:"refresh_token grant not supported"},{status:400});let E=await Y.refreshToken(D),T={access_token:E.access_token,token_type:E.token_type};if(E.refresh_token)T.refresh_token=E.refresh_token;if(E.expires_in!==void 0)T.expires_in=E.expires_in;if(E.scope)T.scope=E.scope;return Response.json(T,{headers:{"Cache-Control":"no-store",Pragma:"no-cache"}})}if(z!=="authorization_code")return Response.json({error:"unsupported_grant_type",error_description:"Only authorization_code and refresh_token supported"},{status:400});if(typeof q!=="string"||!q)return Response.json({error:"invalid_request",error_description:"code is required and must be a string"},{status:400});let L=_j0(q);if(!L||!L.accessToken)return Response.json({error:"invalid_grant",error_description:"Invalid or expired code"},{status:400});if(L.codeChallenge){if(typeof U!=="string"||!U)return Response.json({error:"invalid_grant",error_description:"code_verifier required and must be a string"},{status:400});let E;if(L.codeChallengeMethod==="S256"){let C=new TextEncoder().encode(U),P=await crypto.subtle.digest("SHA-256",C);E=btoa(String.fromCharCode(...new Uint8Array(P))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}else E=U;if(E!==L.codeChallenge)return Response.json({error:"invalid_grant",error_description:"Invalid code_verifier"},{status:400})}let w={access_token:L.accessToken,token_type:L.tokenType};if(L.refreshToken)w.refresh_token=L.refreshToken;if(L.expiresIn!==void 0)w.expires_in=L.expiresIn;if(L.scope)w.scope=L.scope;return Response.json(w,{headers:{"Cache-Control":"no-store",Pragma:"no-cache"}})}catch(F){return console.error("Token exchange error:",F),Response.json({error:"server_error",error_description:"Failed to process token request"},{status:500})}},handleClientRegistration:async($)=>{try{let F=await $.json();if(!F.redirect_uris||F.redirect_uris.length===0)return Response.json({error:"invalid_redirect_uri",error_description:"At least one redirect_uri is required"},{status:400});for(let D of F.redirect_uris)if(!xP6(D))return Response.json({error:"invalid_redirect_uri",error_description:`Invalid redirect URI: ${D}`},{status:400});let V=kj0(32),q=F.token_endpoint_auth_method!=="none"?kj0(32):void 0,U=Math.floor(Date.now()/1000),z={client_id:V,client_secret:q,client_name:F.client_name,redirect_uris:F.redirect_uris,grant_types:F.grant_types??["authorization_code"],response_types:F.response_types??["code"],token_endpoint_auth_method:F.token_endpoint_auth_method??"client_secret_post",scope:F.scope,client_id_issued_at:U,client_secret_expires_at:0};if(Y.persistence)await Y.persistence.saveClient(z);return new Response(JSON.stringify(z),{status:201,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache"}})}catch(F){return console.error("Client registration error:",F),Response.json({error:"invalid_client_metadata",error_description:"Invalid client registration request"},{status:400})}},createUnauthorizedResponse:($)=>{let q=`Bearer resource_metadata="${`${fH(new URL($.url)).origin}/.well-known/oauth-protected-resource`}", scope="*"`;return Response.json({jsonrpc:"2.0",error:{code:-32000,message:"Unauthorized: Authentication required"},id:null},{status:401,headers:{"WWW-Authenticate":q,"Access-Control-Expose-Headers":"WWW-Authenticate"}})},hasAuth:($)=>$.headers.has("Authorization")}}var fH=(Y)=>{if(!(Y.hostname==="localhost"||Y.hostname==="127.0.0.1"))Y.protocol="https:";return Y};import{AsyncLocalStorage as gP6}from"async_hooks";var fj0,PS;var uV1=k(()=>{fj0=new gP6,PS={getStore:()=>{return fj0.getStore()},run:(Y,Q,...X)=>fj0.run(Y,Q,...X)}});function x$(Y){return B.object({items:B.array(Y).describe("Array of collection items"),totalCount:B.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:B.boolean().optional().describe("Whether there are more items available")})}function TS(Y){return B.object({item:Y.nullable().describe("The retrieved item, or null if not found")})}function lP6(Y){return B.object({data:Y.partial().describe("Data for the new entity (id may be auto-generated)")})}function dP6(Y){return B.object({item:Y.describe("The created entity with generated id")})}function pP6(Y){return B.object({id:B.string().describe("ID of the entity to update"),data:Y.partial().describe("Partial entity data to update")})}function cP6(Y){return B.object({item:Y.describe("The updated entity")})}function RS(Y){return B.object({item:Y.describe("The deleted entity")})}function hH(Y,Q,X){let J=Y.toUpperCase(),G=X?.readOnly??!1,K=[{name:`COLLECTION_${J}_LIST`,inputSchema:uZ,outputSchema:x$(Q)},{name:`COLLECTION_${J}_GET`,inputSchema:ES,outputSchema:TS(Q)}];if(!G)K.push({name:`COLLECTION_${J}_CREATE`,inputSchema:lP6(Q),outputSchema:dP6(Q),opt:!0},{name:`COLLECTION_${J}_UPDATE`,inputSchema:pP6(Q),outputSchema:cP6(Q),opt:!0},{name:`COLLECTION_${J}_DELETE`,inputSchema:CS,outputSchema:RS(Q),opt:!0});return K}var bH,uP6,bj0,mP6,uZ,ES,CS;var MG=k(()=>{i1();bH=B.object({id:B.string().describe("Unique identifier for the entity"),title:B.string().describe("Human-readable title for the entity"),description:B.string().nullish().describe("Description of the entity"),created_at:B.string().datetime(),updated_at:B.string().datetime(),created_by:B.string().optional(),updated_by:B.string().optional()}),uP6=B.object({field:B.array(B.string()),operator:B.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:B.unknown()}),bj0=B.lazy(()=>B.union([uP6,B.object({operator:B.enum(["and","or","not"]),conditions:B.array(bj0)})])),mP6=B.object({field:B.array(B.string()),direction:B.enum(["asc","desc"]),nulls:B.enum(["first","last"]).optional()}),uZ=B.object({where:bj0.optional().describe("Filter expression"),orderBy:B.array(mP6).optional().describe("Sort expressions"),limit:B.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:B.number().int().min(0).optional().describe("Number of items to skip")});ES=B.object({id:B.string().describe("ID of the entity to retrieve")});CS=B.object({id:B.string().describe("ID of the entity to delete")})});var nP6,hj0,so8;var xj0=k(()=>{i1();MG();nP6=B.object({id:B.string(),name:B.string(),description:B.string().optional(),inputSchema:B.record(B.string(),B.unknown()),outputSchema:B.record(B.string(),B.unknown()).optional()}),hj0=bH.extend({_meta:B.object({"io.decocms":B.object({id:B.string(),verified:B.boolean(),scopeName:B.string(),appName:B.string(),friendlyName:B.string().nullable().optional(),metadata:B.record(B.string(),B.unknown()).nullable().optional(),publishedAt:B.string().datetime().optional(),updatedAt:B.string().datetime().optional(),tools:B.array(nP6).nullable().optional().describe("Available tools exposed by this app")}).optional()}).optional(),server:B.object({$schema:B.string().optional(),_meta:B.record(B.string(),B.unknown()).optional(),name:B.string().describe("The server name (scope/app)"),title:B.string().optional().describe("User-friendly title"),description:B.string().optional().describe("Server description"),icons:B.array(B.object({src:B.string(),mimeType:B.string().optional(),sizes:B.array(B.string()).optional(),theme:B.enum(["light","dark"]).optional()})).optional(),remotes:B.array(B.object({type:B.enum(["http","stdio","sse"]),url:B.string().optional(),headers:B.array(B.unknown()).optional()})).optional(),packages:B.array(B.unknown()).optional(),repository:B.object({url:B.string(),source:B.string().optional(),subfolder:B.string().optional()}).optional(),version:B.string().optional(),websiteUrl:B.string().optional()})}),so8=hH("registry_app",hj0,{readOnly:!0})});var gj0,gn,uj0,un,mj0,mV1;var lj0=k(()=>{i1();_D();gj0=B.object({specversion:B.literal("1.0").describe("CloudEvents specification version"),id:B.string().describe("Unique identifier for this event (UUID recommended)"),source:B.string().describe("Connection ID of the event publisher"),type:B.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:B.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:B.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:B.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:B.string().url().optional().describe("URI to the schema for the data attribute"),data:B.unknown().optional().describe("Event payload (any JSON value)")}),gn=B.object({events:B.array(gj0).min(1).describe("Batch of CloudEvents to process")}),uj0=B.object({success:B.boolean().optional().describe("Whether this event was processed successfully"),error:B.string().optional().describe("Error message for this event"),retryAfter:B.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),un=B.object({success:B.boolean().optional().describe("Batch success - applies to events not in results"),error:B.string().optional().describe("Batch error message - applies to events not in results"),processedCount:B.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:B.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:B.record(B.string(),uj0).optional().describe("Per-event results keyed by event ID")}),mj0=[{name:"ON_EVENTS",inputSchema:gn,outputSchema:un}],mV1=yH(mj0)});var IS,jS,SS,kS,dj0,pj0,vS,_S,yS,fS,bS,hS,xS,gS,cj0,iP6;var nj0=k(()=>{i1();_D();IS=B.object({type:B.string().min(1).max(255).describe("Event type identifier"),subject:B.string().max(255).optional().describe("Subject/resource identifier (e.g., order ID)"),data:B.unknown().optional().describe("Event payload"),deliverAt:B.string().datetime().optional().describe("Scheduled delivery time (ISO 8601). Omit for immediate delivery."),cron:B.string().max(100).optional().describe("Cron expression for recurring delivery. Use EVENT_CANCEL to stop.")}),jS=B.object({id:B.string().describe("Unique event ID"),type:B.string().describe("Event type"),source:B.string().describe("Source connection ID"),time:B.string().describe("Event timestamp")}),SS=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),kS=B.object({subscription:B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")})}),dj0=B.object({eventType:B.string().min(1).max(255).describe("Event type to subscribe to"),publisher:B.string().optional().describe("Filter events by publisher connection ID"),filter:B.string().max(1000).optional().describe("JSONPath filter expression on event data")}),pj0=B.object({id:B.string().describe("Subscription ID"),connectionId:B.string().describe("Subscriber connection ID"),eventType:B.string().describe("Event type pattern"),publisher:B.string().nullable().describe("Publisher connection filter"),filter:B.string().nullable().describe("JSONPath filter expression"),enabled:B.boolean().describe("Whether subscription is enabled"),createdAt:B.string().datetime().describe("Created timestamp (ISO 8601)"),updatedAt:B.string().datetime().describe("Updated timestamp (ISO 8601)")}),vS=B.object({subscriptions:B.array(dj0).describe("Desired subscriptions - system will create/update/delete to match")}),_S=B.object({created:B.number().int().min(0).describe("Number of subscriptions created"),updated:B.number().int().min(0).describe("Number of subscriptions with filter updated"),deleted:B.number().int().min(0).describe("Number of subscriptions removed"),unchanged:B.number().int().min(0).describe("Number of subscriptions unchanged"),subscriptions:B.array(pj0).describe("Current subscriptions after sync")}),yS=B.object({subscriptionId:B.string().describe("Subscription ID to remove")}),fS=B.object({success:B.boolean().describe("Whether unsubscribe was successful"),subscriptionId:B.string().describe("Subscription ID that was removed")}),bS=B.object({eventId:B.string().describe("Event ID to cancel")}),hS=B.object({success:B.boolean().describe("Whether cancellation was successful"),eventId:B.string().describe("Event ID that was cancelled")}),xS=B.object({eventId:B.string().describe("Event ID to acknowledge")}),gS=B.object({success:B.boolean().describe("Whether ACK was successful"),eventId:B.string().describe("Event ID that was acknowledged")}),cj0=[{name:"EVENT_PUBLISH",inputSchema:IS,outputSchema:jS},{name:"EVENT_SUBSCRIBE",inputSchema:SS,outputSchema:kS},{name:"EVENT_UNSUBSCRIBE",inputSchema:yS,outputSchema:fS},{name:"EVENT_CANCEL",inputSchema:bS,outputSchema:hS},{name:"EVENT_ACK",inputSchema:xS,outputSchema:gS},{name:"EVENT_SYNC_SUBSCRIPTIONS",inputSchema:vS,outputSchema:_S}],iP6=yH(cj0)});var aP6,rP6,oP6,sP6,tP6,eP6,YE6,QE6,XE6,JE6,GE6,WE6,uS;var mn=k(()=>{i1();aP6=B.object({prefix:B.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:B.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:B.string().optional().describe("Token for pagination from previous response"),delimiter:B.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),rP6=B.object({objects:B.array(B.object({key:B.string().describe("Object key/path"),size:B.number().describe("Object size in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object")})),nextContinuationToken:B.string().optional().describe("Token for fetching next page of results"),isTruncated:B.boolean().describe("Whether there are more results available"),commonPrefixes:B.array(B.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),oP6=B.object({key:B.string().describe("Object key/path to get metadata for")}),sP6=B.object({contentType:B.string().optional().describe("MIME type of the object"),contentLength:B.number().describe("Size of the object in bytes"),lastModified:B.string().describe("Last modified timestamp"),etag:B.string().describe("Entity tag for the object"),metadata:B.record(B.string(),B.string()).optional().describe("Custom metadata key-value pairs")}),tP6=B.object({key:B.string().describe("Object key/path to generate URL for"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),eP6=B.object({url:B.string().describe("Presigned URL for downloading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),YE6=B.object({key:B.string().describe("Object key/path for the upload"),expiresIn:B.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:B.string().optional().describe("MIME type for the object being uploaded")}),QE6=B.object({url:B.string().describe("Presigned URL for uploading the object"),expiresIn:B.number().describe("Expiration time in seconds that was used")}),XE6=B.object({key:B.string().describe("Object key/path to delete")}),JE6=B.object({success:B.boolean().describe("Whether the deletion was successful"),key:B.string().describe("The key that was deleted")}),GE6=B.object({keys:B.array(B.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),WE6=B.object({deleted:B.array(B.string()).describe("Array of successfully deleted keys"),errors:B.array(B.object({key:B.string(),message:B.string()})).describe("Array of errors for failed deletions")}),uS=[{name:"LIST_OBJECTS",inputSchema:aP6,outputSchema:rP6},{name:"GET_OBJECT_METADATA",inputSchema:oP6,outputSchema:sP6},{name:"GET_PRESIGNED_URL",inputSchema:tP6,outputSchema:eP6},{name:"PUT_PRESIGNED_URL",inputSchema:YE6,outputSchema:QE6},{name:"DELETE_OBJECT",inputSchema:XE6,outputSchema:JE6},{name:"DELETE_OBJECTS",inputSchema:GE6,outputSchema:WE6}]});function zE6(Y,Q){let X=[];function J(G){if(typeof G==="string"){let K=G.match(/@(\w+)/g);if(K)for(let W of K){let Z=W.substring(1);if(Q.has(Z))X.push(Z)}}else if(Array.isArray(G))G.forEach(J);else if(typeof G==="object"&&G!==null)Object.values(G).forEach(J)}return J(Y.input),[...new Set(X)]}function oj0(Y){let Q=new Set(Y.map((W)=>W.name)),X=new Map;for(let W of Y)X.set(W.name,zE6(W,Q));let J=new Set,G=new Set;function K(W,Z){if(G.has(W))return[...Z,W];if(J.has(W))return null;J.add(W),G.add(W);let H=X.get(W)||[];for(let $ of H){let F=K($,[...Z,W]);if(F)return F}return G.delete(W),null}for(let W of Y){let Z=K(W.name,[]);if(Z)return{isValid:!1,error:`Circular dependency detected: ${Z.join(" -> ")}`}}return{isValid:!0}}var lV1,ZE6,Fs8,KE6,HE6,ij0,yD,$E6,aj0,FE6,Vs8,VE6,rj0,qE6,BE6,UE6,qs8,Bs8;var DA=k(()=>{i1();_D();MG();lV1=B.object({toolName:B.string().describe("Name of the tool to invoke on that connection"),transformCode:B.string().optional().describe("Pure TypeScript function for data transformation of the tool call result. Must be a TypeScript file that declares the Output interface and exports a default function: `interface Output { ... } export default async function(input): Output { ... }`\n The input will match with the tool call outputSchema. If transformCode is not provided, the tool call result will be used as the step output. \n Providing an transformCode is recommended because it both allows you to transform the data and validate it against a JSON Schema - tools are ephemeral and may return unexpected data.")}),ZE6=B.object({code:B.string().describe(`Pure TypeScript function for data transformation. Useful to merge data from multiple steps and transform it. Must be a TypeScript file that declares the Output interface and exports a default function: \`interface Output { ... } export default async function(input): Output { ... }\`
1046
1046
  The input is the resolved value of the references in the input field. Example:
1047
1047
  {
1048
1048
  "input": {
@@ -1062,7 +1062,7 @@ data:
1062
1062
  `;if(J)G+=`id: ${J}
1063
1063
  `;return G+=`data: ${JSON.stringify(X)}
1064
1064
 
1065
- `,Y.enqueue(Q.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(Y,Q){try{let X=Y.headers.get("accept");if(!X?.includes("application/json")||!X.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=Y.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(Y.headers.entries())},K;if(Q?.parsedBody!==void 0)K=Q.parsedBody;else try{K=await Y.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let W;try{if(Array.isArray(K))W=K.map((L)=>mG.parse(L));else W=[mG.parse(K)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let Z=W.some(cJ1);if(Z){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(W.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(!Z){let L=this.validateSession(Y);if(L)return L;let w=this.validateProtocolVersion(Y);if(w)return w}if(!W.some(lK)){for(let L of W)this.onmessage?.(L,{authInfo:Q?.authInfo,requestInfo:G});return new Response(null,{status:202})}let $=crypto.randomUUID(),F=W.find((L)=>cJ1(L)),V=F?F.params.protocolVersion:Y.headers.get("mcp-protocol-version")??w70;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set($,{resolveJson:L,cleanup:()=>{this._streamMapping.delete($)}});for(let w of W)if(lK(w))this._requestToStreamMapping.set(w.id,$);for(let w of W)this.onmessage?.(w,{authInfo:Q?.authInfo,requestInfo:G})});let q=new TextEncoder,U,z=new ReadableStream({start:(L)=>{U=L},cancel:()=>{this._streamMapping.delete($)}}),D={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)D["mcp-session-id"]=this.sessionId;for(let L of W)if(lK(L))this._streamMapping.set($,{controller:U,encoder:q,cleanup:()=>{this._streamMapping.delete($);try{U.close()}catch{}}}),this._requestToStreamMapping.set(L.id,$);await this.writePrimingEvent(U,q,$,V);for(let L of W){let w,E;if(lK(L)&&this._eventStore&&V>="2025-11-25")w=()=>{this.closeSSEStream(L.id)},E=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:Q?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:E})}return new Response(z,{status:200,headers:D})}catch(X){return this.onerror?.(X),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(X)})}}async handleDeleteRequest(Y){let Q=this.validateSession(Y);if(Q)return Q;let X=this.validateProtocolVersion(Y);if(X)return X;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Y){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Q=Y.headers.get("mcp-session-id");if(!Q)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Q!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Y){let Q=Y.headers.get("mcp-protocol-version");if(Q!==null&&!Wz.includes(Q))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Q} (supported versions: ${Wz.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Y})=>{Y()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Y){let Q=this._requestToStreamMapping.get(Y);if(!Q)return;let X=this._streamMapping.get(Q);if(X)X.cleanup()}closeStandaloneSSEStream(){let Y=this._streamMapping.get(this._standaloneSseStreamId);if(Y)Y.cleanup()}async send(Y,Q){let X=Q?.relatedRequestId;if(zZ(Y)||mL(Y))X=Y.id;if(X===void 0){if(zZ(Y)||mL(Y))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let K;if(this._eventStore)K=await this._eventStore.storeEvent(this._standaloneSseStreamId,Y);let W=this._streamMapping.get(this._standaloneSseStreamId);if(W===void 0)return;if(W.controller&&W.encoder)this.writeSSEEvent(W.controller,W.encoder,Y,K);return}let J=this._requestToStreamMapping.get(X);if(!J)throw Error(`No connection established for request ID: ${String(X)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let K;if(this._eventStore)K=await this._eventStore.storeEvent(J,Y);this.writeSSEEvent(G.controller,G.encoder,Y,K)}if(zZ(Y)||mL(Y)){this._requestResponseMap.set(X,Y);let K=Array.from(this._requestToStreamMapping.entries()).filter(([Z,H])=>H===J).map(([Z])=>Z);if(K.every((Z)=>this._requestResponseMap.has(Z))){if(!G)throw Error(`No connection established for request ID: ${String(X)}`);if(this._enableJsonResponse&&G.resolveJson){let Z={"Content-Type":"application/json"};if(this.sessionId!==void 0)Z["mcp-session-id"]=this.sessionId;let H=K.map(($)=>this._requestResponseMap.get($));if(H.length===1)G.resolveJson(new Response(JSON.stringify(H[0]),{status:200,headers:Z}));else G.resolveJson(new Response(JSON.stringify(H),{status:200,headers:Z}))}else G.cleanup();for(let Z of K)this._requestResponseMap.delete(Z),this._requestToStreamMapping.delete(Z)}}}}var dS=k(()=>{vQ()});var QS0="SELF",dn=(Y)=>{return typeof Y==="object"&&Y!==null&&"handler"in Y&&"events"in Y&&typeof Y.handler==="function"&&Array.isArray(Y.events)},XS0=(Y)=>{return typeof Y==="object"&&Y!==null&&"handler"in Y&&"events"in Y&&typeof Y.handler==="function"&&Array.isArray(Y.events)},YS0="::",JS0=(Y)=>{let Q=Y.indexOf(YS0);if(Q===-1)return null;let X=Y.substring(0,Q),J=Y.substring(Q+YS0.length);return[X,J]},LE6=(Y)=>{if(!Y.startsWith("cron/"))return null;let Q=Y.substring(5),X=Q.indexOf("/");if(X===-1)return null;let J=Q.substring(0,X),G=Q.substring(X+1);return[J,G]},GS0=(Y)=>{if(dn(Y))return[];return Object.keys(Y)},ME6=(Y,Q)=>{if(dn(Y))return Y.events;let X=Y[Q];if(!X)return[];if(XS0(X))return X.events;return Object.keys(X)},ln=(Y,Q,X)=>{if(Y===QS0){if(!X)return console.warn("[Event] SELF binding used but no connectionId available"),null;return X}let J=Q[Y];if(!gV1(J))return console.warn(`[Event] Binding "${Y}" not found in state`),null;return J.value},wE6=(Y,Q,X)=>{let J=Q;if(dn(Y)){let K=[];for(let W of Y.events){let Z=JS0(W);if(!Z){console.warn(`[Event] Global handler event "${W}" must be prefixed with BINDING:: (e.g., "SELF::${W}" or "DATABASE::${W}")`);continue}let[H,$]=Z,F=ln(H,J,X);if(!F)continue;K.push({eventType:$,publisher:F})}return K}let G=[];for(let K of GS0(Y)){let W=ln(K,J,X);if(!W)continue;let Z=ME6(Y,K);for(let H of Z)G.push({eventType:H,publisher:W})}return G},AE6=(Y)=>{let Q=new Map;for(let X of Y){let J=X.source,G=Q.get(J)||[];G.push(X),Q.set(J,G)}return Q},PE6=(Y)=>{let Q=new Map;for(let X of Y){let J=X.type,G=Q.get(J)||[];G.push(X),Q.set(J,G)}return Q},EE6=(Y)=>{let Q={},X={},J=!1,G=0,K=[];for(let W of Y){if(W.results)Object.assign(X,W.results);if(W.success===!1){if(J=!0,W.error)K.push(W.error)}if(W.processedCount!==void 0)G+=W.processedCount}if(Object.keys(X).length>0)Q.results=X;if(Q.success=!J,K.length>0)Q.error=K.join("; ");if(G>0)Q.processedCount=G;return Q},TE6=async(Y,Q,X,J,G)=>{let K=J;if(dn(Y)){let F=new Set;for(let q of Y.events){let U=JS0(q);if(!U)continue;let[z,D]=U,L=ln(z,K,G);if(!L)continue;F.add(`${L}:${D}`)}let V=Q.filter((q)=>{let U=`${q.source}:${q.type}`;return F.has(U)});if(V.length===0)return{success:!0};try{return await Y.handler({events:V},X)}catch(q){return{success:!1,error:q instanceof Error?q.message:String(q)}}}let W=new Map;for(let F of GS0(Y)){let V=ln(F,K,G);if(V)W.set(V,F)}let Z=AE6(Q),H=[];for(let[F,V]of Z){let q=W.get(F);if(!q)continue;let U=Y[q];if(!U)continue;if(XS0(U)){H.push((async()=>{try{return await U.handler({events:V},X)}catch(L){let w={};for(let E of V)w[E.id]={success:!1,error:L instanceof Error?L.message:String(L)};return{results:w}}})());continue}let z=U,D=PE6(V);for(let[L,w]of D){let E=z[L];if(!E)continue;H.push((async()=>{try{let T=await E({events:w},X),C={};for(let P of w)C[P.id]=T;return{results:C}}catch(T){let C={};for(let P of w)C[P.id]={success:!1,error:T instanceof Error?T.message:String(T)};return{results:C}}})())}}let $=await Promise.all(H);if($.length===0)return{success:!0};return EE6($)},pn;var cV1=k(()=>{xn();pn={subscriptions:wE6,execute:TE6,parseCron:LE6}});function u$(Y){return{...Y,execute:(Q)=>{return Y.execute({...Q,runtimeContext:pS(Q.runtimeContext)})}}}function nV1(Y){return Y&&"streamable"in Y&&Y.streamable===!0}var pS=(Y)=>{let Q=PS.getStore();if(!Q){if(Y)return Y;throw Error("Missing context, did you forget to call State.bind?")}return Q},CE6=(Y,Q)=>{let X=Q;return typeof X[Y]<"u"?X[Y]:Q?.MESH_REQUEST_CONTEXT?.state?.[Y]},RE6=({events:Y,configuration:{state:Q,scopes:X,onChange:J}={}}={})=>{let G=Q?B.toJSONSchema(Q):{type:"object",properties:{}},K=String(Y?.bus??"EVENT_BUS");return[...J||Y?[u$({id:"ON_MCP_CONFIGURATION",description:"MCP Configuration On Change",inputSchema:B.object({state:Q??B.unknown(),scopes:B.array(B.string()).describe("Array of scopes in format 'KEY::SCOPE' (e.g., 'GMAIL::GetCurrentUser')")}),outputSchema:B.object({}),execute:async(W)=>{let Z=W.context.state;await J?.(W.runtimeContext.env,{state:Z,scopes:W.context.scopes});let H=CE6(K,W.runtimeContext.env);if(Y&&Z&&H){let $=W.runtimeContext.env.MESH_REQUEST_CONTEXT?.connectionId,F=pn.subscriptions(Y?.handlers??{},Z,$);if(await H.EVENT_SYNC_SUBSCRIPTIONS({subscriptions:F}),$){let V=F.filter((q)=>q.eventType.startsWith("cron/")&&q.publisher===$);await Promise.all(V.map(async(q)=>{let U=pn.parseCron(q.eventType);if(U){let[,z]=U;await H.EVENT_PUBLISH({type:q.eventType,cron:z})}}))}}return Promise.resolve({})}})]:[],...Y?.handlers?[u$({id:"ON_EVENTS",description:"Receive and process CloudEvents from the event bus. Returns per-event or batch results.",inputSchema:gn,outputSchema:un,execute:async(W)=>{let Z=W.runtimeContext.env,H=Z.MESH_REQUEST_CONTEXT?.state,$=Z.MESH_REQUEST_CONTEXT?.connectionId;return pn.execute(Y.handlers,W.context.events,Z,H,$)}})]:[],u$({id:"MCP_CONFIGURATION",description:"MCP Configuration",inputSchema:B.object({}),outputSchema:B.object({stateSchema:B.unknown(),scopes:B.array(B.string()).optional()}),execute:()=>{return Promise.resolve({stateSchema:G,scopes:[...X??[],...Y?[`${K}::EVENT_SYNC_SUBSCRIPTIONS`]:[]]})}})]},WS0=(Y)=>{let Q=async(G)=>{await Y.before?.(G);let K=new Oz({name:"@deco/mcp-api",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}}),Z=await(typeof Y.tools==="function"?Y.tools:async(q)=>{if(typeof Y.tools==="function")return await Y.tools(q);return await Promise.all(Y.tools?.flatMap(async(U)=>{let D=await U(q);if(Array.isArray(D))return D;return[D]})??[]).then((U)=>U.flat())})(G);Z.push(...RE6(Y));for(let q of Z)K.registerTool(q.id,{_meta:{streamable:nV1(q),...q._meta??{}},description:q.description,annotations:q.annotations,inputSchema:q.inputSchema&&"shape"in q.inputSchema?q.inputSchema.shape:B.object({}).shape,outputSchema:nV1(q)?B.object({bytes:B.record(B.string(),B.number())}).shape:q.outputSchema&&typeof q.outputSchema==="object"&&("shape"in q.outputSchema)?q.outputSchema.shape:void 0},async(U)=>{let z=await q.execute({context:U,runtimeContext:pS()});if(nV1(q)&&z instanceof Response)return{structuredContent:{streamable:!0,status:z.status,statusText:z.statusText},content:[{type:"text",text:`Streaming response: ${z.status} ${z.statusText}`}]};return{structuredContent:z,content:[{type:"text",text:JSON.stringify(z)}]}});let $=await(typeof Y.prompts==="function"?Y.prompts:async(q)=>{if(typeof Y.prompts==="function")return await Y.prompts(q);return await Promise.all(Y.prompts?.flatMap(async(U)=>{let D=await U(q);if(Array.isArray(D))return D;return[D]})??[]).then((U)=>U.flat())})(G);for(let q of $)K.registerPrompt(q.name,{title:q.title,description:q.description,argsSchema:q.argsSchema?q.argsSchema:B.object({}).shape},async(U)=>{return await q.execute({args:U,runtimeContext:pS()})});let V=await(typeof Y.resources==="function"?Y.resources:async(q)=>{if(typeof Y.resources==="function")return await Y.resources(q);return await Promise.all(Y.resources?.flatMap(async(U)=>{let D=await U(q);if(Array.isArray(D))return D;return[D]})??[]).then((U)=>U.flat())})(G);for(let q of V)K.resource(q.name,q.uri,{description:q.description,mimeType:q.mimeType},async(U)=>{let z=await q.read({uri:U,runtimeContext:pS()}),D={uri:z.uri};if(z.mimeType)D.mimeType=z.mimeType;if(z.text!==void 0)return{contents:[{uri:z.uri,mimeType:z.mimeType,text:z.text}]};else if(z.blob!==void 0)return{contents:[{uri:z.uri,mimeType:z.mimeType,blob:z.blob}]};return{contents:[{uri:z.uri,mimeType:z.mimeType,text:""}]}});return{server:K,tools:Z,prompts:$,resources:V}};return{fetch:async(G,K)=>{let{server:W}=await Q(K),Z=new g$;await W.connect(Z);try{let H=await Z.handleRequest(G),$=H.headers.get("content-type");if(!($?.includes("text/event-stream")||$?.includes("application/json-rpc"))){console.debug("[MCP Transport] Closing transport for non-streaming response");try{await Z.close?.()}catch{}}else console.debug("[MCP Transport] Keeping transport open for streaming response (Content-Type: %s)",$);return H}catch(H){console.debug("[MCP Transport] Closing transport due to error:",H instanceof Error?H.message:H);try{await Z.close?.()}catch{}throw H}},callTool:async({toolCallId:G,toolCallInput:K})=>{let W=PS.getStore();if(!W)throw Error("Missing state, did you forget to call State.bind?");let Z=W?.env,{tools:H}=await Q(Z),F=H.find((V)=>V.id===G)?.execute;if(!F)throw Error(`Tool ${G} not found or does not have an execute function`);return F({context:K,runtimeContext:pS()})}}};var cn=k(()=>{lS();am();dS();i1();cV1();uV1();cV1()});var IE6=({env:Y,server:Q,url:X})=>{Y.SELF=new Proxy({},{get:(J,G)=>{if(G==="toJSON")return null;return async(K)=>{return await Q.callTool({toolCallId:G,toolCallInput:K})}}}),Y.IS_LOCAL=(X?.startsWith("http://localhost")||X?.startsWith("http://127.0.0.1"))??!1},ZS0=(Y)=>()=>{return{...Y??{}}},jE6=({env:Y,server:Q,tokenOrContext:X,url:J,authToken:G})=>{let K=Y,W=G?G.split(" ")[1]:void 0,Z;if(typeof X==="string"){let H=m9(X),$=H.metadata??{};Z={authorization:W,state:H.state??$.state??{},token:X,meshUrl:H.meshUrl??$.meshUrl,connectionId:H.connectionId??$.connectionId,organizationId:H.organizationId??$.organizationId,ensureAuthenticated:ZS0(H.user??H.sub)}}else if(typeof X==="object"){Z=X;let H=m9(X.token),$=H.metadata??{},F=H.appName;Z.authorization??=W,Z.callerApp=F,Z.connectionId??=H.connectionId??$.connectionId,Z.ensureAuthenticated=ZS0(H.user??H.sub)}else Z={state:{},authorization:W,token:void 0,meshUrl:void 0,connectionId:void 0,ensureAuthenticated:()=>{throw Error("Unauthorized")}};return K.MESH_REQUEST_CONTEXT=Z,Z.state=Cj0(Z),IE6({env:K,server:Q,url:J}),K},SE6,KS0=(Y)=>{let Q=WS0(Y),X=Y.cors??SE6,J=Y.oauth,G=J?yj0(J):null,K=async(W,Z,H)=>{let $=new URL(W.url);if(G){if($.pathname==="/.well-known/oauth-protected-resource"||$.pathname==="/mcp/.well-known/oauth-protected-resource")return G.handleProtectedResourceMetadata(W);if($.pathname==="/.well-known/oauth-authorization-server")return G.handleAuthorizationServerMetadata(W);if($.pathname==="/authorize")return G.handleAuthorize(W);if($.pathname==="/oauth/callback")return G.handleOAuthCallback(W);if($.pathname==="/token"&&W.method==="POST")return G.handleToken(W);if(($.pathname==="/register"||$.pathname==="/mcp/register")&&W.method==="POST")return G.handleClientRegistration(W)}if($.pathname==="/mcp"){if(W.method==="GET")return new Response("Method not allowed",{status:405});if(G&&!G.hasAuth(W)){let F=W.clone();try{if((await F.json())?.method!=="tools/list")return G.createUnauthorizedResponse(W)}catch{return G.createUnauthorizedResponse(W)}}return Q.fetch(W,Z,H)}if($.pathname.startsWith("/mcp/call-tool")){let F=$.pathname.split("/").pop();if(!F)return new Response("Not found",{status:404});let V=await W.json(),q=await Q.callTool({toolCallId:F,toolCallInput:V});if(q instanceof Response)return q;return new Response(JSON.stringify(q),{headers:{"Content-Type":"application/json"}})}return Y.fetch?.(W,Z,H)||new Response("Not found",{status:404})};return{fetch:async(W,Z,H)=>{if(new URL(W.url).pathname==="/_healthcheck")return new Response("OK",{status:200});if(X!==!1&&W.method==="OPTIONS")return Ij0(W,X??{});let $=jE6({authToken:W.headers.get("authorization")??null,env:{...process.env,...Z},server:Q,tokenOrContext:W.headers.get("x-mesh-token")??void 0,url:W.url}),F=await PS.run({req:W,env:$,ctx:H},async()=>await K(W,$,H));if(X!==!1)return jj0(F,W,X??{});return F}}};var HS0=k(()=>{UG();xn();Sj0();uV1();cn();cn();xn();hV1();SE6={origin:(Y)=>{if(Y.includes("localhost")||Y.includes("127.0.0.1"))return Y;return Y},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]}});function nn(Y){return Buffer.from(String(Y),"utf8").toString("base64")}function an(Y){if(!Y)return null;try{let Q=Buffer.from(Y,"base64").toString("utf8"),X=Number.parseInt(Q,10);return Number.isNaN(X)||X<0?null:X}catch{return null}}function NX(Y){if(!Y?.length)return[];return Array.from(new Set(Y.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.toLowerCase())))}function fD(Y){if(!Y)return[];return NX(Y.split(","))}function rn(Y,Q){if(!Y)return Q;try{return JSON.parse(Y)}catch{return Q}}function on(Y){return Y?.["mcp.mesh"]??{}}function sn(Y){return Y.length?Y.join(","):null}function kE6(Y,Q){if(!Q?.length)return;let X=Y;for(let J of Q){if(X===null||X===void 0)return;if(typeof X!=="object")return;X=X[J]}return X}function vE6(Y,Q,X){if(!Q)return!1;if(Q==="eq")return Y===X;if(Q==="contains"||Q==="like"){let J=String(Y??"").toLowerCase(),G=String(X??"").toLowerCase();return J.includes(G)}if(Q==="in"){if(!Array.isArray(X))return!1;return X.includes(Y)}if(Q==="gt")return Number(Y)>Number(X);if(Q==="gte")return Number(Y)>=Number(X);if(Q==="lt")return Number(Y)<Number(X);if(Q==="lte")return Number(Y)<=Number(X);return!1}function cS(Y,Q){if(!Q)return!0;if(Array.isArray(Q.conditions)&&Q.conditions.length){if(Q.operator==="and")return Q.conditions.every((X)=>cS(Y,X));if(Q.operator==="or")return Q.conditions.some((X)=>cS(Y,X));if(Q.operator==="not")return!Q.conditions.some((X)=>cS(Y,X))}return vE6(kE6(Y,Q.field),Q.operator,Q.value)}class nS{db;constructor(Y){this.db=Y}async create(Y){let Q=new Date().toISOString(),X=Y._meta??{},J=on(X),G=NX(J.tags),K=NX(J.categories),W={id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,server_json:JSON.stringify(Y.server),meta_json:JSON.stringify(X),tags:sn(G),categories:sn(K),is_public:Y.is_public?1:0,is_unlisted:Y.is_unlisted?1:0,created_at:Q,updated_at:Q,created_by:Y.created_by??null};await this.db.insertInto("private_registry_item").values(W).execute();let Z=await this.findById(Y.organization_id,Y.id);if(!Z)throw Error(`Failed to create registry item "${Y.id}"`);return Z}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async findByIdOrName(Y,Q){let X=await this.findById(Y,Q);if(X)return X;let J=await this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).where("title","=",Q).executeTakeFirst();return J?this.deserialize(J):null}async update(Y,Q,X){let J=await this.findById(Y,Q);if(!J)throw Error(`Registry item not found: ${Q}`);let G=X._meta??J._meta??{},K=on(G),W=NX(K.tags),Z=NX(K.categories),H={updated_at:new Date().toISOString()};if(X.title!==void 0)H.title=X.title;if(X.description!==void 0)H.description=X.description;if(X.server!==void 0)H.server_json=JSON.stringify(X.server);if(X._meta!==void 0)H.meta_json=JSON.stringify(X._meta);if(X._meta!==void 0)H.tags=sn(W),H.categories=sn(Z);if(X.is_public!==void 0)H.is_public=X.is_public?1:0;if(X.is_unlisted!==void 0)H.is_unlisted=X.is_unlisted?1:0;await this.db.updateTable("private_registry_item").set(H).where("organization_id","=",Y).where("id","=",Q).execute();let $=await this.findById(Y,Q);if(!$)throw Error(`Registry item not found after update: ${Q}`);return $}async delete(Y,Q){let X=await this.findById(Y,Q);if(!X)return null;return await this.db.deleteFrom("private_registry_item").where("organization_id","=",Y).where("id","=",Q).execute(),X}async list(Y,Q={}){let X=this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).orderBy("created_at","desc");if(!Q.includeUnlisted)X=X.where("is_unlisted","=",0);let G=(await X.execute()).map((z)=>this.deserialize(z)),K=NX(Q.tags),W=NX(Q.categories),Z=G.filter((z)=>{let D=on(z._meta),L=NX(D.tags),w=NX(D.categories),E=K.length===0||K.every((P)=>L.includes(P)),T=W.length===0||W.every((P)=>w.includes(P)),C=cS(z,Q.where);return E&&T&&C}),$=an(Q.cursor)??Q.offset??0,F=Q.limit??24,V=Z.slice($,$+F),q=$+F<Z.length,U=q?nn($+F):void 0;return{items:V,totalCount:Z.length,hasMore:q,nextCursor:U}}async listPublic(Y,Q={}){let J=(await this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).where("is_public","=",1).where("is_unlisted","=",0).orderBy("created_at","desc").execute()).map((U)=>this.deserialize(U)),G=NX(Q.tags),K=NX(Q.categories),W=J.filter((U)=>{let z=on(U._meta),D=NX(z.tags),L=NX(z.categories),w=G.length===0||G.every((C)=>D.includes(C)),E=K.length===0||K.every((C)=>L.includes(C)),T=cS(U,Q.where);return w&&E&&T}),H=an(Q.cursor)??Q.offset??0,$=Q.limit??24,F=W.slice(H,H+$),V=H+$<W.length,q=V?nn(H+$):void 0;return{items:F,totalCount:W.length,hasMore:V,nextCursor:q}}async getFilters(Y,Q){let X=this.db.selectFrom("private_registry_item").select(["tags","categories"]).where("organization_id","=",Y);if(Q?.publicOnly)X=X.where("is_public","=",1);if(!Q?.includeUnlisted)X=X.where("is_unlisted","=",0);let J=await X.execute(),G=new Map,K=new Map;for(let Z of J){for(let H of fD(Z.tags))G.set(H,(G.get(H)??0)+1);for(let H of fD(Z.categories))K.set(H,(K.get(H)??0)+1)}let W=(Z)=>Array.from(Z.entries()).map(([H,$])=>({value:H,count:$})).sort((H,$)=>H.value.localeCompare($.value));return{tags:W(G),categories:W(K)}}async search(Y,Q={},X){let J=this.db.selectFrom("private_registry_item").select(["id","title","description","meta_json","server_json","tags","categories","is_public","is_unlisted"]).where("organization_id","=",Y).orderBy("created_at","desc");if(X?.publicOnly)J=J.where("is_public","=",1);if(!X?.includeUnlisted)J=J.where("is_unlisted","=",0);let G=await J.execute(),K=Q.query?.trim().toLowerCase(),W=NX(Q.tags),Z=NX(Q.categories),H=G.filter((L)=>{if(K){let w=rn(L.server_json,{}),T=rn(L.meta_json,{})?.["mcp.mesh"]?.short_description??"";if(![L.id,L.title,L.description??"",w.name??"",w.description??"",T].join(" ").toLowerCase().includes(K))return!1}if(W.length>0){let w=NX(fD(L.tags));if(!W.every((E)=>w.includes(E)))return!1}if(Z.length>0){let w=NX(fD(L.categories));if(!Z.every((E)=>w.includes(E)))return!1}return!0}),F=an(Q.cursor)??0,V=Q.limit??20,q=H.slice(F,F+V),U=F+V<H.length,z=U?nn(F+V):void 0;return{items:q.map((L)=>({id:L.id,title:L.title,tags:fD(L.tags),categories:fD(L.categories),is_public:L.is_public===1,is_unlisted:L.is_unlisted===1})),totalCount:H.length,hasMore:U,nextCursor:z}}deserialize(Y){let Q=rn(Y.server_json,{}),X=rn(Y.meta_json,{});return{id:Y.id,name:typeof Q.name==="string"?Q.name:void 0,title:Y.title,description:Y.description,_meta:X,server:Q,is_public:Y.is_public===1,is_unlisted:Y.is_unlisted===1,created_at:Y.created_at,updated_at:Y.updated_at,...Y.created_by?{created_by:Y.created_by}:{}}}}var iV1=()=>{};var tn,_E6,en,mZ,aV1,yE6,mq,OA,wG,bD,rV1,$S0,oV1,FS0,sV1,VS0,tV1,qS0,NA,fE6,iS,bE6,Yi,eV1,BS0,US0,Yq1,zS0,DS0,OS0,NS0,LS0,MS0,wS0,AS0,hE6,Qq1,PS0,ES0,Xq1,TS0;var cY=k(()=>{MG();i1();tn=B.object({name:B.string(),title:B.string().optional(),description:B.string().optional(),version:B.string().optional(),websiteUrl:B.string().optional(),icons:B.array(B.object({src:B.string()})).optional(),remotes:B.array(B.object({type:B.string().optional(),url:B.string().optional(),name:B.string().optional(),title:B.string().optional(),description:B.string().optional()})).optional(),packages:B.array(B.object({identifier:B.string(),version:B.string().optional()})).optional(),repository:B.object({url:B.string().optional(),source:B.string().optional(),subfolder:B.string().optional()}).optional()}),_E6=B.object({name:B.string(),description:B.string().nullable().optional()}),en=B.object({"mcp.mesh":B.object({verified:B.boolean().optional(),tags:B.array(B.string()).optional(),categories:B.array(B.string()).optional(),friendly_name:B.string().nullable().optional(),short_description:B.string().max(160).nullable().optional(),owner:B.string().nullable().optional(),readme:B.string().max(50000).nullable().optional(),readme_url:B.string().url().nullable().optional(),has_remote:B.boolean().optional(),has_oauth:B.boolean().optional(),tools:B.array(_E6).optional()}).optional()}).catchall(B.unknown()),mZ=B.object({id:B.string(),name:B.string().optional(),title:B.string(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn,is_public:B.boolean().optional(),created_at:B.string(),updated_at:B.string(),created_by:B.string().optional()}),aV1=B.object({id:B.string(),title:B.string(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn,is_public:B.boolean().optional()}),yE6=B.object({title:B.string().optional(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn.optional(),is_public:B.boolean().optional()}),mq=uZ.extend({tags:B.array(B.string()).optional().describe("Filter by tags (AND semantics)"),categories:B.array(B.string()).optional().describe("Filter by categories (AND semantics)"),cursor:B.string().optional().describe("Pagination cursor")}).describe("List registry items with optional filtering and pagination."),OA=B.object({items:B.array(mZ),totalCount:B.number(),hasMore:B.boolean().optional(),nextCursor:B.string().optional()}),wG=B.object({id:B.string().optional().describe("Registry item ID"),name:B.string().optional().describe("Registry item name (alias for id)")}).refine((Y)=>Y.id||Y.name,{message:"At least one of 'id' or 'name' is required"}).describe("Get a registry item by ID or name."),bD=B.object({item:mZ.nullable()}),rV1=B.object({data:aV1}),$S0=B.object({item:mZ}),oV1=B.object({items:B.array(aV1).min(1)}),FS0=B.object({created:B.number(),errors:B.array(B.object({id:B.string(),error:B.string()}))}),sV1=B.object({id:B.string(),data:yE6}),VS0=B.object({item:mZ}),tV1=B.object({id:B.string()}),qS0=B.object({item:mZ}),NA=B.object({tags:B.array(B.object({value:B.string(),count:B.number()})),categories:B.array(B.object({value:B.string(),count:B.number()}))}),fE6=B.enum(["description","short_description","tags","categories","readme"]),iS=B.object({query:B.string().optional().describe("Free-text search across id, title, description, server name"),tags:B.array(B.string()).optional().describe("Filter by tags (AND)"),categories:B.array(B.string()).optional().describe("Filter by categories (AND)"),limit:B.number().int().min(1).max(100).optional().describe("Max results (default 20)"),cursor:B.string().optional().describe("Pagination cursor")}).describe("Lightweight search returning minimal fields (id, title, tags, categories, is_public)."),bE6=B.object({id:B.string(),title:B.string(),tags:B.array(B.string()),categories:B.array(B.string()),is_public:B.boolean()}),Yi=B.object({items:B.array(bE6),totalCount:B.number(),hasMore:B.boolean().optional(),nextCursor:B.string().optional()}),eV1=B.object({type:fE6.describe("Which content to generate"),llmConnectionId:B.string().describe("Connection ID of a language model"),modelId:B.string().describe("Model ID to use"),context:B.object({name:B.string().optional(),provider:B.string().optional(),url:B.string().optional(),owner:B.string().optional(),repositoryUrl:B.string().optional(),description:B.string().optional(),shortDescription:B.string().optional(),tags:B.array(B.string()).optional(),categories:B.array(B.string()).optional(),availableTags:B.array(B.string()).optional(),availableCategories:B.array(B.string()).optional(),tools:B.array(B.object({name:B.string(),description:B.string().nullable().optional()})).optional()})}),BS0=B.object({result:B.string().optional(),items:B.array(B.string()).optional()}),US0=B.enum(["pending","approved","rejected"]),Yq1=B.object({id:B.string(),organization_id:B.string(),requested_id:B.string().nullable().optional(),status:US0,title:B.string(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn,requester_name:B.string().nullable().optional(),requester_email:B.string().nullable().optional(),reviewer_notes:B.string().nullable().optional(),created_at:B.string(),updated_at:B.string()}),zS0=B.object({status:US0.optional(),limit:B.number().int().min(1).max(200).optional(),offset:B.number().int().min(0).optional(),sortBy:B.enum(["created_at","title"]).optional(),sortDirection:B.enum(["asc","desc"]).optional()}),DS0=B.object({items:B.array(Yq1),totalCount:B.number()}),OS0=B.object({id:B.string(),status:B.enum(["approved","rejected"]),reviewerNotes:B.string().nullable().optional()}),NS0=B.object({item:Yq1}),LS0=B.object({pending:B.number()}),MS0=B.object({id:B.string()}),wS0=B.object({item:Yq1.nullable()}),AS0=B.object({data:aV1,requester:B.object({name:B.string().optional(),email:B.string().email().optional()}).optional()}),hE6=B.object({id:B.string(),name:B.string(),prefix:B.string(),createdAt:B.string()}),Qq1=B.object({name:B.string().min(1).max(64).describe("A descriptive name for this key")}),PS0=B.object({id:B.string(),name:B.string(),prefix:B.string(),key:B.string().describe("The full API key \u2014 shown only once!"),createdAt:B.string()}),ES0=B.object({items:B.array(hE6)}),Xq1=B.object({keyId:B.string()}),TS0=B.object({success:B.boolean(),keyId:B.string()})});function xE6(Y,Q){let X=u$({id:"COLLECTION_REGISTRY_APP_LIST",description:"List public registry items",inputSchema:mq,outputSchema:OA,execute:async({context:Z})=>{return await Y.listPublic(Q,{limit:Z.limit,offset:Z.offset,cursor:Z.cursor,tags:Z.tags,categories:Z.categories,where:Z.where})}}),J=u$({id:"COLLECTION_REGISTRY_APP_GET",description:"Get a public registry item by ID or name",inputSchema:wG,outputSchema:bD,execute:async({context:Z})=>{let H=Z.id??Z.name;if(!H)return{item:null};let $=await Y.findByIdOrName(Q,H);if($&&$.is_public)return{item:$};return{item:null}}}),G=u$({id:"COLLECTION_REGISTRY_APP_VERSIONS",description:"Get available versions of a public registry item",inputSchema:wG,outputSchema:B.object({versions:B.array(bD.shape.item)}),execute:async({context:Z})=>{let H=Z.id??Z.name;if(!H)return{versions:[]};let $=await Y.findByIdOrName(Q,H);if($&&$.is_public)return{versions:[$]};return{versions:[]}}}),K=u$({id:"COLLECTION_REGISTRY_APP_SEARCH",description:"Search public registry items returning minimal data (id, title, tags, categories, is_public). Use this instead of LIST when you need to find items efficiently without loading full details.",inputSchema:iS,outputSchema:Yi,execute:async({context:Z})=>{return await Y.search(Q,Z,{publicOnly:!0})}}),W=u$({id:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get available tags and categories for public registry items",inputSchema:B.object({}),outputSchema:NA,execute:async()=>{return await Y.getFilters(Q,{publicOnly:!0})}});return[X,K,J,G,W]}function Jq1(Y,Q){let X=Q.db,J=new nS(X);Y.all("/org/:orgSlug/registry/*",async(G)=>{let K=G.req.param("orgSlug");console.log(`[Public Registry MCP] Request for org slug: ${K}, path: ${G.req.path}`);let W=await X.selectFrom("organization").select(["id","slug","name"]).where("slug","=",K).executeTakeFirst();if(console.log("[Public Registry MCP] Found org:",W),!W)return console.log(`[Public Registry MCP] Organization not found: ${K}`),G.json({error:"Organization not found"},404);let Z=xE6(J,W.id),H=KS0({tools:()=>Z}),$=new URL(G.req.url),F=G.req.path.replace(`/org/${K}/registry`,""),V=new URL(F||"/",$.origin);$.searchParams.forEach((z,D)=>{V.searchParams.set(D,z)}),console.log(`[Public Registry MCP] Rewriting ${$.pathname} to ${V.pathname}`);let q=new Request(V.toString(),{method:G.req.method,headers:G.req.raw.headers,body:G.req.method!=="GET"&&G.req.method!=="HEAD"?G.req.raw.body:void 0}),U={organizationId:W.id,db:X,MESH_REQUEST_CONTEXT:{},MESH_APP_DEPLOYMENT_ID:"public-registry",IS_LOCAL:!1};return await H.fetch(q,U,G)})}var CS0=k(()=>{HS0();cn();i1();iV1();cY()});import{randomUUID as gE6}from"crypto";function RS0(Y,Q){if(!Y)return Q;try{return JSON.parse(Y)}catch{return Q}}class aS{db;constructor(Y){this.db=Y}async createOrUpdate(Y){let Q=new Date().toISOString(),X=await this.findPendingByRequestedId(Y.organization_id,Y.requested_id);if(X){let W={title:Y.title,description:Y.description??null,server_json:JSON.stringify(Y.server),meta_json:Y._meta?JSON.stringify(Y._meta):null,requester_name:Y.requester_name??null,requester_email:Y.requester_email??null,updated_at:Q};await this.db.updateTable("private_registry_publish_request").set(W).where("organization_id","=",Y.organization_id).where("id","=",X.id).execute();let Z=await this.findById(Y.organization_id,X.id);if(!Z)throw Error("Failed to update publish request");return Z}let J=gE6(),G={id:J,organization_id:Y.organization_id,requested_id:Y.requested_id,status:"pending",title:Y.title,description:Y.description??null,server_json:JSON.stringify(Y.server),meta_json:Y._meta?JSON.stringify(Y._meta):null,requester_name:Y.requester_name??null,requester_email:Y.requester_email??null,reviewer_notes:null,created_at:Q,updated_at:Q};await this.db.insertInto("private_registry_publish_request").values(G).execute();let K=await this.findById(Y.organization_id,J);if(!K)throw Error("Failed to create publish request");return K}async findPendingByRequestedId(Y,Q){let X=await this.db.selectFrom("private_registry_publish_request").selectAll().where("organization_id","=",Y).where("requested_id","=",Q).where("status","=","pending").executeTakeFirst();return X?this.deserialize(X):null}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_publish_request").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async list(Y,Q={}){let X=this.db.selectFrom("private_registry_publish_request").selectAll().where("organization_id","=",Y),J=this.db.selectFrom("private_registry_publish_request").select(($)=>$.fn.countAll().as("count")).where("organization_id","=",Y);if(Q.status)X=X.where("status","=",Q.status),J=J.where("status","=",Q.status);let G=await J.executeTakeFirst(),K=Number(G?.count??0),W=Q.sortBy??"created_at",Z=Q.sortDirection??"desc";if(W==="title")X=X.orderBy("title",Z);else X=X.orderBy("created_at",Z);return{items:(await X.limit(Q.limit??24).offset(Q.offset??0).execute()).map(($)=>this.deserialize($)),totalCount:K}}async updateStatus(Y,Q,X,J){let G={status:X,updated_at:new Date().toISOString(),reviewer_notes:J??null};await this.db.updateTable("private_registry_publish_request").set(G).where("organization_id","=",Y).where("id","=",Q).execute();let K=await this.findById(Y,Q);if(!K)throw Error(`Publish request not found: ${Q}`);return K}async countPending(Y){let Q=await this.db.selectFrom("private_registry_publish_request").select((X)=>X.fn.countAll().as("count")).where("organization_id","=",Y).where("status","=","pending").executeTakeFirst();return Number(Q?.count??0)}async delete(Y,Q){let X=await this.findById(Y,Q);if(!X)return null;return await this.db.deleteFrom("private_registry_publish_request").where("organization_id","=",Y).where("id","=",Q).execute(),X}deserialize(Y){return{id:Y.id,organization_id:Y.organization_id,requested_id:Y.requested_id??null,status:Y.status,title:Y.title,description:Y.description,_meta:RS0(Y.meta_json,{}),server:RS0(Y.server_json,{name:""}),requester_name:Y.requester_name,requester_email:Y.requester_email,reviewer_notes:Y.reviewer_notes,created_at:Y.created_at,updated_at:Y.updated_at}}}var Gq1=()=>{};import{randomUUID as uE6}from"crypto";async function IS0(Y){let X=new TextEncoder().encode(Y),J=await crypto.subtle.digest("SHA-256",X);return Array.from(new Uint8Array(J)).map((K)=>K.toString(16).padStart(2,"0")).join("")}function mE6(){let Y=new Uint8Array(32);return crypto.getRandomValues(Y),`prk_${Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}`}class rS{db;constructor(Y){this.db=Y}async generate(Y,Q){let X=uE6(),J=mE6(),G=await IS0(J),K=J.slice(0,12),W=new Date().toISOString();return await this.db.insertInto("private_registry_publish_api_key").values({id:X,organization_id:Y,name:Q,key_hash:G,prefix:K,created_at:W}).execute(),{entity:{id:X,organization_id:Y,name:Q,prefix:K,created_at:W},key:J}}async list(Y){return await this.db.selectFrom("private_registry_publish_api_key").select(["id","organization_id","name","prefix","created_at"]).where("organization_id","=",Y).orderBy("created_at","desc").execute()}async revoke(Y,Q){return(await this.db.deleteFrom("private_registry_publish_api_key").where("organization_id","=",Y).where("id","=",Q).execute()).length>0}async validate(Y,Q){let X=await IS0(Q),J=await this.db.selectFrom("private_registry_publish_api_key").select(["id"]).where("organization_id","=",Y).where("key_hash","=",X).executeTakeFirst();return Boolean(J)}async hasKeys(Y){let Q=await this.db.selectFrom("private_registry_publish_api_key").select((X)=>X.fn.countAll().as("count")).where("organization_id","=",Y).executeTakeFirst();return Number(Q?.count??0)>0}}var Wq1=()=>{};import{sql as lE6}from"kysely";import{randomUUID as jS0}from"crypto";async function pE6(Y){let Q=new Date().toISOString(),X=jS0(),J=IY.SELF(Y.organizationId),G="registry.publish_request.created",K={requestId:Y.request.id,requestedId:Y.request.requested_id,title:Y.request.title,status:Y.request.status,createdAt:Y.request.created_at,requester:{name:Y.request.requester_name,email:Y.request.requester_email}};await Y.db.insertInto("events").values({id:X,organization_id:Y.organizationId,type:"registry.publish_request.created",source:J,specversion:"1.0",subject:Y.request.id,time:Q,datacontenttype:"application/json",dataschema:null,data:JSON.stringify(K),cron:null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute();let W=await Y.db.selectFrom("event_subscriptions").select(["id"]).where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=","registry.publish_request.created").where((Z)=>Z.or([Z("publisher","is",null),Z("publisher","=",J)])).execute();if(W.length>0)await Y.db.insertInto("event_deliveries").values(W.map((Z)=>({id:jS0(),event_id:X,subscription_id:Z.id,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:null,created_at:Q}))).execute();try{await lE6`SELECT pg_notify('mesh_events', ${X})`.execute(Y.db)}catch{}}async function cE6(Y,Q){let J=(await Y.selectFrom("organization").select(["id"]).where("id","=",Q).execute())[0];if(J?.id)return J.id;return(await Y.selectFrom("organization").select(["id"]).where("slug","=",Q).execute())[0]?.id??null}async function nE6(Y,Q){let X=await Y.selectFrom("project_plugin_configs").innerJoin("projects","projects.id","project_plugin_configs.project_id").select(["project_plugin_configs.settings as settings"]).where("projects.organization_id","=",Q).where("project_plugin_configs.plugin_id","=",_H).execute();for(let J of X){let G=J.settings,K=typeof G==="string"?(()=>{try{return JSON.parse(G)}catch{return{}}})():G??{};if(K.acceptPublishRequests===!0){let W=K.rateLimitWindow==="minute"?"minute":"hour",Z=K.rateLimitMax,H=typeof Z==="number"&&Number.isFinite(Z)&&Z>=1?Math.floor(Z):kS0;return{acceptPublishRequests:!0,requireApiToken:K.requireApiToken===!0,rateLimitEnabled:K.rateLimitEnabled===void 0?SS0:K.rateLimitEnabled===!0,rateLimitWindow:W,rateLimitMax:H}}}return{acceptPublishRequests:!1,requireApiToken:!1,rateLimitEnabled:SS0,rateLimitWindow:dE6,rateLimitMax:kS0}}async function iE6(Y,Q,X){let J=X==="minute"?60000:3600000,G=new Date(Date.now()-J).toISOString(),K=await Y.selectFrom("private_registry_publish_request").select((W)=>W.fn.countAll().as("count")).where("organization_id","=",Q).where("created_at",">=",G).executeTakeFirst();return Number(K?.count??0)}async function aE6(Y,Q,X,J){let G=await Y.selectFrom("private_registry_item").select(["id","title"]).where("organization_id","=",Q).where((K)=>K.or([K("id","=",X),K("title","=",J)])).executeTakeFirst();return G?{id:String(G.id),title:String(G.title)}:null}function Zq1(Y,Q){let{db:X,db:J}=Q,G=new aS(J),K=new rS(J);Y.post("/org/:orgRef/registry/publish-request",async(W)=>{let Z=W.req.param("orgRef"),H=await cE6(X,Z);if(!H)return W.json({error:"Organization not found"},404);let $=await nE6(X,H);if(!$.acceptPublishRequests)return W.json({error:"Publish requests are not enabled for this registry."},403);if($.requireApiToken){let z=W.req.header("Authorization"),D=z?.startsWith("Bearer ")?z.slice(7).trim():null;if(!D)return W.json({error:"API key required. Use Authorization: Bearer <key>"},401);if(!await K.validate(H,D))return W.json({error:"Invalid API key"},401)}if($.rateLimitEnabled){if(await iE6(J,H,$.rateLimitWindow)>=$.rateLimitMax)return W.json({error:"Too many publish requests. Please try again later.",retryAfterSeconds:$.rateLimitWindow==="minute"?60:3600},429)}let F;try{F=await W.req.json()}catch{return W.json({error:"Invalid JSON body"},400)}let V=AS0.safeParse(F);if(!V.success)return W.json({error:"Invalid publish request payload",details:B.treeifyError(V.error)},400);let q=await aE6(J,H,V.data.data.id,V.data.data.title);if(q)return W.json({error:"A registry item with the same id or title already exists. Please use a different name/id.",conflict:q},409);let U=await G.createOrUpdate({organization_id:H,requested_id:V.data.data.id,title:V.data.data.title,description:V.data.data.description??null,_meta:V.data.data._meta,server:V.data.data.server,requester_name:V.data.requester?.name??null,requester_email:V.data.requester?.email??null});try{await pE6({db:X,organizationId:H,request:U})}catch(z){console.warn("[private-registry] failed to emit publish-request event:",z)}return W.json({id:U.id,requested_id:U.requested_id,status:U.status},201)})}var SS0=!0,dE6="hour",kS0=100;var vS0=k(()=>{KY();i1();kD();Gq1();Wq1();cY()});var _S0=k(()=>{CS0();vS0()});function yS0(Y){Kq1=Y}function S4(){if(!Kq1)throw Error(`Plugin storage not initialized. Make sure the "${_H}" plugin is enabled.`);return Kq1}async function rE6(Y){if(!Y.organization)throw Error("Organization context required");return await Y.access.check(),Y}function Y6(Y,Q){return async(X,J)=>{let G=await rE6(J);return Q(X,G)}}function oE6(Y){if(!Y)return{};if(typeof Y==="string")try{return JSON.parse(Y)}catch{return{}}if(typeof Y==="object")return Y;return{}}async function oS(Y,Q){let J=(await Y.db.selectFrom("project_plugin_configs").innerJoin("projects","projects.id","project_plugin_configs.project_id").select(["project_plugin_configs.settings as settings"]).where("projects.organization_id","=",Q).where("project_plugin_configs.plugin_id","=",_H).execute()).map((K)=>oE6(K.settings)),G={acceptPublishRequests:J.some((K)=>K.acceptPublishRequests===!0),requireApiToken:J.some((K)=>K.requireApiToken===!0),storePrivateOnly:J.some((K)=>K.storePrivateOnly===!0)};if(G.acceptPublishRequests||G.requireApiToken||G.storePrivateOnly)return G;for(let K of J)if(Object.keys(K).length>0)return K;return{}}var Kq1=null;var J9=k(()=>{kD()});import{randomUUID as fS0}from"crypto";function bS0(Y,Q){if(!Y)return Q;try{return JSON.parse(Y)}catch{return Q}}class Hq1{db;constructor(Y){this.db=Y}async create(Y){let Q=fS0(),X=new Date().toISOString(),J={id:Q,organization_id:Y.organization_id,status:Y.status??"pending",config_snapshot:Y.config_snapshot?JSON.stringify(Y.config_snapshot):null,total_items:Y.total_items??0,tested_items:0,passed_items:0,failed_items:0,skipped_items:0,current_item_id:null,started_at:Y.started_at??null,finished_at:null,created_at:X};await this.db.insertInto("private_registry_monitor_run").values(J).execute();let G=await this.findById(Y.organization_id,Q);if(!G)throw Error(`Failed to create monitor run ${Q}`);return G}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_run").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserializeRun(X):null}async list(Y,Q={}){let X=this.db.selectFrom("private_registry_monitor_run").selectAll().where("organization_id","=",Y),J=this.db.selectFrom("private_registry_monitor_run").select((Z)=>Z.fn.countAll().as("count")).where("organization_id","=",Y);if(Q.status)X=X.where("status","=",Q.status),J=J.where("status","=",Q.status);let G=await J.executeTakeFirst(),K=Number(G?.count??0);return{items:(await X.orderBy("created_at","desc").limit(Q.limit??24).offset(Q.offset??0).execute()).map((Z)=>this.deserializeRun(Z)),totalCount:K}}async update(Y,Q,X){let J={};if(X.total_items!==void 0)J.total_items=X.total_items;if(X.status!==void 0)J.status=X.status;if(X.tested_items!==void 0)J.tested_items=X.tested_items;if(X.passed_items!==void 0)J.passed_items=X.passed_items;if(X.failed_items!==void 0)J.failed_items=X.failed_items;if(X.skipped_items!==void 0)J.skipped_items=X.skipped_items;if(X.current_item_id!==void 0)J.current_item_id=X.current_item_id;if(X.started_at!==void 0)J.started_at=X.started_at;if(X.finished_at!==void 0)J.finished_at=X.finished_at;await this.db.updateTable("private_registry_monitor_run").set(J).where("organization_id","=",Y).where("id","=",Q).execute();let G=await this.findById(Y,Q);if(!G)throw Error(`Monitor run not found: ${Q}`);return G}deserializeRun(Y){return{id:Y.id,organization_id:Y.organization_id,status:Y.status,config_snapshot:bS0(Y.config_snapshot,null),total_items:Number(Y.total_items??0),tested_items:Number(Y.tested_items??0),passed_items:Number(Y.passed_items??0),failed_items:Number(Y.failed_items??0),skipped_items:Number(Y.skipped_items??0),current_item_id:Y.current_item_id,started_at:Y.started_at,finished_at:Y.finished_at,created_at:Y.created_at}}}class $q1{db;constructor(Y){this.db=Y}async create(Y){let Q=fS0(),X=new Date().toISOString(),J={id:Q,run_id:Y.run_id,organization_id:Y.organization_id,item_id:Y.item_id,item_title:Y.item_title,status:Y.status,error_message:Y.error_message??null,connection_ok:Y.connection_ok?1:0,tools_listed:Y.tools_listed?1:0,tool_results:Y.tool_results?JSON.stringify(Y.tool_results):null,agent_summary:Y.agent_summary??null,duration_ms:Y.duration_ms??0,action_taken:Y.action_taken??"none",tested_at:X};await this.db.insertInto("private_registry_monitor_result").values(J).execute();let G=await this.findById(Y.organization_id,Q);if(!G)throw Error("Failed to create test result");return G}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_result").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async listByRun(Y,Q,X={}){let J=this.db.selectFrom("private_registry_monitor_result").selectAll().where("organization_id","=",Y).where("run_id","=",Q),G=this.db.selectFrom("private_registry_monitor_result").select((H)=>H.fn.countAll().as("count")).where("organization_id","=",Y).where("run_id","=",Q);if(X.status)J=J.where("status","=",X.status),G=G.where("status","=",X.status);let K=await G.executeTakeFirst(),W=Number(K?.count??0);return{items:(await J.orderBy("tested_at","desc").limit(X.limit??50).offset(X.offset??0).execute()).map((H)=>this.deserialize(H)),totalCount:W}}async update(Y,Q,X){let J={};if(X.status!==void 0)J.status=X.status;if(X.error_message!==void 0)J.error_message=X.error_message;if(X.connection_ok!==void 0)J.connection_ok=X.connection_ok?1:0;if(X.tools_listed!==void 0)J.tools_listed=X.tools_listed?1:0;if(X.tool_results!==void 0)J.tool_results=JSON.stringify(X.tool_results);if(X.agent_summary!==void 0)J.agent_summary=X.agent_summary;if(X.duration_ms!==void 0)J.duration_ms=X.duration_ms;if(X.action_taken!==void 0)J.action_taken=X.action_taken;await this.db.updateTable("private_registry_monitor_result").set(J).where("organization_id","=",Y).where("id","=",Q).execute();let G=await this.findById(Y,Q);if(!G)throw Error(`Monitor result not found: ${Q}`);return G}deserialize(Y){return{id:Y.id,run_id:Y.run_id,organization_id:Y.organization_id,item_id:Y.item_id,item_title:Y.item_title,status:Y.status,error_message:Y.error_message,connection_ok:Y.connection_ok===1,tools_listed:Y.tools_listed===1,tool_results:bS0(Y.tool_results,[]),agent_summary:Y.agent_summary,duration_ms:Number(Y.duration_ms??0),action_taken:Y.action_taken,tested_at:Y.tested_at}}}var hS0=()=>{};import{randomUUID as sE6}from"crypto";class Fq1{db;constructor(Y){this.db=Y}async findByItemId(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_connection").selectAll().where("organization_id","=",Y).where("item_id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async list(Y){return(await this.db.selectFrom("private_registry_monitor_connection").selectAll().where("organization_id","=",Y).orderBy("updated_at","desc").execute()).map((X)=>this.deserialize(X))}async findByConnectionId(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_connection").selectAll().where("organization_id","=",Y).where("connection_id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async upsert(Y){let Q=await this.findByItemId(Y.organization_id,Y.item_id),X=new Date().toISOString();if(!Q){let G={id:sE6(),organization_id:Y.organization_id,item_id:Y.item_id,connection_id:Y.connection_id,auth_status:Y.auth_status??"none",created_at:X,updated_at:X};await this.db.insertInto("private_registry_monitor_connection").values(G).execute()}else{let G={connection_id:Y.connection_id,auth_status:Y.auth_status??Q.auth_status,updated_at:X};await this.db.updateTable("private_registry_monitor_connection").set(G).where("organization_id","=",Y.organization_id).where("item_id","=",Y.item_id).execute()}let J=await this.findByItemId(Y.organization_id,Y.item_id);if(!J)throw Error("Failed to save monitor connection");return J}async updateAuthStatus(Y,Q,X){return await this.db.updateTable("private_registry_monitor_connection").set({auth_status:X,updated_at:new Date().toISOString()}).where("organization_id","=",Y).where("item_id","=",Q).execute(),this.findByItemId(Y,Q)}deserialize(Y){return{id:Y.id,organization_id:Y.organization_id,item_id:Y.item_id,connection_id:Y.connection_id,auth_status:Y.auth_status,created_at:Y.created_at,updated_at:Y.updated_at}}}var xS0=()=>{};function gS0(Y){let Q=Y.db,X={items:new nS(Q),publishRequests:new aS(Q),publishApiKeys:new rS(Q),monitorRuns:new Hq1(Q),monitorResults:new $q1(Q),monitorConnections:new Fq1(Q)};return yS0(X),X}var uS0=k(()=>{J9();iV1();Gq1();Wq1();hS0();xS0()});var mS0;var lS0=k(()=>{cY();J9();mS0={name:"REGISTRY_ITEM_BULK_CREATE",description:"Create many private registry items at once",inputSchema:oV1,outputSchema:FS0,handler:Y6(oV1,async(Y,Q)=>{let X=S4(),J=[],G=0;for(let K of Y.items)try{await X.items.create({...K,organization_id:Q.organization.id,created_by:Q.auth.user?.id??null}),G+=1}catch(W){J.push({id:K.id,error:W instanceof Error?W.message:"Unknown error"})}return{created:G,errors:J}})}});function tE6(Y){return Array.from(new Set(Y.map((Q)=>Q.trim().toLowerCase()).filter((Q)=>Q.length>0)))}function eE6(Y){let X=Y.structuredContent?.content?.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text??"").join(`
1065
+ `,Y.enqueue(Q.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(Y,Q){try{let X=Y.headers.get("accept");if(!X?.includes("application/json")||!X.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=Y.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(Y.headers.entries())},K;if(Q?.parsedBody!==void 0)K=Q.parsedBody;else try{K=await Y.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let W;try{if(Array.isArray(K))W=K.map((L)=>mG.parse(L));else W=[mG.parse(K)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let Z=W.some(cJ1);if(Z){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(W.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(!Z){let L=this.validateSession(Y);if(L)return L;let w=this.validateProtocolVersion(Y);if(w)return w}if(!W.some(lK)){for(let L of W)this.onmessage?.(L,{authInfo:Q?.authInfo,requestInfo:G});return new Response(null,{status:202})}let $=crypto.randomUUID(),F=W.find((L)=>cJ1(L)),V=F?F.params.protocolVersion:Y.headers.get("mcp-protocol-version")??w70;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set($,{resolveJson:L,cleanup:()=>{this._streamMapping.delete($)}});for(let w of W)if(lK(w))this._requestToStreamMapping.set(w.id,$);for(let w of W)this.onmessage?.(w,{authInfo:Q?.authInfo,requestInfo:G})});let q=new TextEncoder,U,z=new ReadableStream({start:(L)=>{U=L},cancel:()=>{this._streamMapping.delete($)}}),D={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)D["mcp-session-id"]=this.sessionId;for(let L of W)if(lK(L))this._streamMapping.set($,{controller:U,encoder:q,cleanup:()=>{this._streamMapping.delete($);try{U.close()}catch{}}}),this._requestToStreamMapping.set(L.id,$);await this.writePrimingEvent(U,q,$,V);for(let L of W){let w,E;if(lK(L)&&this._eventStore&&V>="2025-11-25")w=()=>{this.closeSSEStream(L.id)},E=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:Q?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:E})}return new Response(z,{status:200,headers:D})}catch(X){return this.onerror?.(X),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(X)})}}async handleDeleteRequest(Y){let Q=this.validateSession(Y);if(Q)return Q;let X=this.validateProtocolVersion(Y);if(X)return X;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Y){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Q=Y.headers.get("mcp-session-id");if(!Q)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Q!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Y){let Q=Y.headers.get("mcp-protocol-version");if(Q!==null&&!Wz.includes(Q))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Q} (supported versions: ${Wz.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Y})=>{Y()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Y){let Q=this._requestToStreamMapping.get(Y);if(!Q)return;let X=this._streamMapping.get(Q);if(X)X.cleanup()}closeStandaloneSSEStream(){let Y=this._streamMapping.get(this._standaloneSseStreamId);if(Y)Y.cleanup()}async send(Y,Q){let X=Q?.relatedRequestId;if(zZ(Y)||mL(Y))X=Y.id;if(X===void 0){if(zZ(Y)||mL(Y))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let K;if(this._eventStore)K=await this._eventStore.storeEvent(this._standaloneSseStreamId,Y);let W=this._streamMapping.get(this._standaloneSseStreamId);if(W===void 0)return;if(W.controller&&W.encoder)this.writeSSEEvent(W.controller,W.encoder,Y,K);return}let J=this._requestToStreamMapping.get(X);if(!J)throw Error(`No connection established for request ID: ${String(X)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let K;if(this._eventStore)K=await this._eventStore.storeEvent(J,Y);this.writeSSEEvent(G.controller,G.encoder,Y,K)}if(zZ(Y)||mL(Y)){this._requestResponseMap.set(X,Y);let K=Array.from(this._requestToStreamMapping.entries()).filter(([Z,H])=>H===J).map(([Z])=>Z);if(K.every((Z)=>this._requestResponseMap.has(Z))){if(!G)throw Error(`No connection established for request ID: ${String(X)}`);if(this._enableJsonResponse&&G.resolveJson){let Z={"Content-Type":"application/json"};if(this.sessionId!==void 0)Z["mcp-session-id"]=this.sessionId;let H=K.map(($)=>this._requestResponseMap.get($));if(H.length===1)G.resolveJson(new Response(JSON.stringify(H[0]),{status:200,headers:Z}));else G.resolveJson(new Response(JSON.stringify(H),{status:200,headers:Z}))}else G.cleanup();for(let Z of K)this._requestResponseMap.delete(Z),this._requestToStreamMapping.delete(Z)}}}}var dS=k(()=>{vQ()});var QS0="SELF",dn=(Y)=>{return typeof Y==="object"&&Y!==null&&"handler"in Y&&"events"in Y&&typeof Y.handler==="function"&&Array.isArray(Y.events)},XS0=(Y)=>{return typeof Y==="object"&&Y!==null&&"handler"in Y&&"events"in Y&&typeof Y.handler==="function"&&Array.isArray(Y.events)},YS0="::",JS0=(Y)=>{let Q=Y.indexOf(YS0);if(Q===-1)return null;let X=Y.substring(0,Q),J=Y.substring(Q+YS0.length);return[X,J]},LE6=(Y)=>{if(!Y.startsWith("cron/"))return null;let Q=Y.substring(5),X=Q.indexOf("/");if(X===-1)return null;let J=Q.substring(0,X),G=Q.substring(X+1);return[J,G]},GS0=(Y)=>{if(dn(Y))return[];return Object.keys(Y)},ME6=(Y,Q)=>{if(dn(Y))return Y.events;let X=Y[Q];if(!X)return[];if(XS0(X))return X.events;return Object.keys(X)},ln=(Y,Q,X)=>{if(Y===QS0){if(!X)return console.warn("[Event] SELF binding used but no connectionId available"),null;return X}let J=Q[Y];if(!gV1(J))return console.warn(`[Event] Binding "${Y}" not found in state`),null;return J.value},wE6=(Y,Q,X)=>{let J=Q;if(dn(Y)){let K=[];for(let W of Y.events){let Z=JS0(W);if(!Z){console.warn(`[Event] Global handler event "${W}" must be prefixed with BINDING:: (e.g., "SELF::${W}" or "DATABASE::${W}")`);continue}let[H,$]=Z,F=ln(H,J,X);if(!F)continue;K.push({eventType:$,publisher:F})}return K}let G=[];for(let K of GS0(Y)){let W=ln(K,J,X);if(!W)continue;let Z=ME6(Y,K);for(let H of Z)G.push({eventType:H,publisher:W})}return G},AE6=(Y)=>{let Q=new Map;for(let X of Y){let J=X.source,G=Q.get(J)||[];G.push(X),Q.set(J,G)}return Q},PE6=(Y)=>{let Q=new Map;for(let X of Y){let J=X.type,G=Q.get(J)||[];G.push(X),Q.set(J,G)}return Q},EE6=(Y)=>{let Q={},X={},J=!1,G=0,K=[];for(let W of Y){if(W.results)Object.assign(X,W.results);if(W.success===!1){if(J=!0,W.error)K.push(W.error)}if(W.processedCount!==void 0)G+=W.processedCount}if(Object.keys(X).length>0)Q.results=X;if(Q.success=!J,K.length>0)Q.error=K.join("; ");if(G>0)Q.processedCount=G;return Q},TE6=async(Y,Q,X,J,G)=>{let K=J;if(dn(Y)){let F=new Set;for(let q of Y.events){let U=JS0(q);if(!U)continue;let[z,D]=U,L=ln(z,K,G);if(!L)continue;F.add(`${L}:${D}`)}let V=Q.filter((q)=>{let U=`${q.source}:${q.type}`;return F.has(U)});if(V.length===0)return{success:!0};try{return await Y.handler({events:V},X)}catch(q){return{success:!1,error:q instanceof Error?q.message:String(q)}}}let W=new Map;for(let F of GS0(Y)){let V=ln(F,K,G);if(V)W.set(V,F)}let Z=AE6(Q),H=[];for(let[F,V]of Z){let q=W.get(F);if(!q)continue;let U=Y[q];if(!U)continue;if(XS0(U)){H.push((async()=>{try{return await U.handler({events:V},X)}catch(L){let w={};for(let E of V)w[E.id]={success:!1,error:L instanceof Error?L.message:String(L)};return{results:w}}})());continue}let z=U,D=PE6(V);for(let[L,w]of D){let E=z[L];if(!E)continue;H.push((async()=>{try{let T=await E({events:w},X),C={};for(let P of w)C[P.id]=T;return{results:C}}catch(T){let C={};for(let P of w)C[P.id]={success:!1,error:T instanceof Error?T.message:String(T)};return{results:C}}})())}}let $=await Promise.all(H);if($.length===0)return{success:!0};return EE6($)},pn;var cV1=k(()=>{xn();pn={subscriptions:wE6,execute:TE6,parseCron:LE6}});function u$(Y){return{...Y,execute:(Q)=>{return Y.execute({...Q,runtimeContext:pS(Q.runtimeContext)})}}}function nV1(Y){return Y&&"streamable"in Y&&Y.streamable===!0}var pS=(Y)=>{let Q=PS.getStore();if(!Q){if(Y)return Y;throw Error("Missing context, did you forget to call State.bind?")}return Q},CE6=(Y,Q)=>{let X=Q;return typeof X[Y]<"u"?X[Y]:Q?.MESH_REQUEST_CONTEXT?.state?.[Y]},RE6=({events:Y,configuration:{state:Q,scopes:X,onChange:J}={}}={})=>{let G=Q?B.toJSONSchema(Q):{type:"object",properties:{}},K=String(Y?.bus??"EVENT_BUS");return[...J||Y?[u$({id:"ON_MCP_CONFIGURATION",description:"MCP Configuration On Change",inputSchema:B.object({state:Q??B.unknown(),scopes:B.array(B.string()).describe("Array of scopes in format 'KEY::SCOPE' (e.g., 'GMAIL::GetCurrentUser')")}),outputSchema:B.object({}),execute:async(W)=>{let Z=W.context.state;await J?.(W.runtimeContext.env,{state:Z,scopes:W.context.scopes});let H=CE6(K,W.runtimeContext.env);if(Y&&Z&&H){let $=W.runtimeContext.env.MESH_REQUEST_CONTEXT?.connectionId,F=pn.subscriptions(Y?.handlers??{},Z,$);if(await H.EVENT_SYNC_SUBSCRIPTIONS({subscriptions:F}),$){let V=F.filter((q)=>q.eventType.startsWith("cron/")&&q.publisher===$);await Promise.all(V.map(async(q)=>{let U=pn.parseCron(q.eventType);if(U){let[,z]=U;await H.EVENT_PUBLISH({type:q.eventType,cron:z})}}))}}return Promise.resolve({})}})]:[],...Y?.handlers?[u$({id:"ON_EVENTS",description:"Receive and process CloudEvents from the event bus. Returns per-event or batch results.",inputSchema:gn,outputSchema:un,execute:async(W)=>{let Z=W.runtimeContext.env,H=Z.MESH_REQUEST_CONTEXT?.state,$=Z.MESH_REQUEST_CONTEXT?.connectionId;return pn.execute(Y.handlers,W.context.events,Z,H,$)}})]:[],u$({id:"MCP_CONFIGURATION",description:"MCP Configuration",inputSchema:B.object({}),outputSchema:B.object({stateSchema:B.unknown(),scopes:B.array(B.string()).optional()}),execute:()=>{return Promise.resolve({stateSchema:G,scopes:[...X??[],...Y?[`${K}::EVENT_SYNC_SUBSCRIPTIONS`]:[]]})}})]},WS0=(Y)=>{let Q=async(G)=>{await Y.before?.(G);let K=new Oz({name:"@deco/mcp-api",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}}),Z=await(typeof Y.tools==="function"?Y.tools:async(q)=>{if(typeof Y.tools==="function")return await Y.tools(q);return await Promise.all(Y.tools?.flatMap(async(U)=>{let D=await U(q);if(Array.isArray(D))return D;return[D]})??[]).then((U)=>U.flat())})(G);Z.push(...RE6(Y));for(let q of Z)K.registerTool(q.id,{_meta:{streamable:nV1(q),...q._meta??{}},description:q.description,annotations:q.annotations,inputSchema:q.inputSchema&&"shape"in q.inputSchema?q.inputSchema.shape:B.object({}).shape,outputSchema:nV1(q)?B.object({bytes:B.record(B.string(),B.number())}).shape:q.outputSchema&&typeof q.outputSchema==="object"&&("shape"in q.outputSchema)?q.outputSchema.shape:void 0},async(U)=>{let z=await q.execute({context:U,runtimeContext:pS()});if(nV1(q)&&z instanceof Response)return{structuredContent:{streamable:!0,status:z.status,statusText:z.statusText},content:[{type:"text",text:`Streaming response: ${z.status} ${z.statusText}`}]};return{structuredContent:z,content:[{type:"text",text:JSON.stringify(z)}]}});let $=await(typeof Y.prompts==="function"?Y.prompts:async(q)=>{if(typeof Y.prompts==="function")return await Y.prompts(q);return await Promise.all(Y.prompts?.flatMap(async(U)=>{let D=await U(q);if(Array.isArray(D))return D;return[D]})??[]).then((U)=>U.flat())})(G);for(let q of $)K.registerPrompt(q.name,{title:q.title,description:q.description,argsSchema:q.argsSchema?q.argsSchema:B.object({}).shape},async(U)=>{return await q.execute({args:U,runtimeContext:pS()})});let V=await(typeof Y.resources==="function"?Y.resources:async(q)=>{if(typeof Y.resources==="function")return await Y.resources(q);return await Promise.all(Y.resources?.flatMap(async(U)=>{let D=await U(q);if(Array.isArray(D))return D;return[D]})??[]).then((U)=>U.flat())})(G);for(let q of V)K.resource(q.name,q.uri,{description:q.description,mimeType:q.mimeType},async(U)=>{let z=await q.read({uri:U,runtimeContext:pS()}),D={uri:z.uri};if(z.mimeType)D.mimeType=z.mimeType;if(z.text!==void 0)return{contents:[{uri:z.uri,mimeType:z.mimeType,text:z.text}]};else if(z.blob!==void 0)return{contents:[{uri:z.uri,mimeType:z.mimeType,blob:z.blob}]};return{contents:[{uri:z.uri,mimeType:z.mimeType,text:""}]}});return{server:K,tools:Z,prompts:$,resources:V}};return{fetch:async(G,K)=>{let{server:W}=await Q(K),Z=new g$;await W.connect(Z);try{let H=await Z.handleRequest(G),$=H.headers.get("content-type");if(!($?.includes("text/event-stream")||$?.includes("application/json-rpc"))){console.debug("[MCP Transport] Closing transport for non-streaming response");try{await Z.close?.()}catch{}}else console.debug("[MCP Transport] Keeping transport open for streaming response (Content-Type: %s)",$);return H}catch(H){console.debug("[MCP Transport] Closing transport due to error:",H instanceof Error?H.message:H);try{await Z.close?.()}catch{}throw H}},callTool:async({toolCallId:G,toolCallInput:K})=>{let W=PS.getStore();if(!W)throw Error("Missing state, did you forget to call State.bind?");let Z=W?.env,{tools:H}=await Q(Z),F=H.find((V)=>V.id===G)?.execute;if(!F)throw Error(`Tool ${G} not found or does not have an execute function`);return F({context:K,runtimeContext:pS()})}}};var cn=k(()=>{lS();am();dS();i1();cV1();uV1();cV1()});var IE6=({env:Y,server:Q,url:X})=>{Y.SELF=new Proxy({},{get:(J,G)=>{if(G==="toJSON")return null;return async(K)=>{return await Q.callTool({toolCallId:G,toolCallInput:K})}}}),Y.IS_LOCAL=(X?.startsWith("http://localhost")||X?.startsWith("http://127.0.0.1"))??!1},ZS0=(Y)=>()=>{return{...Y??{}}},jE6=({env:Y,server:Q,tokenOrContext:X,url:J,authToken:G})=>{let K=Y,W=G?G.split(" ")[1]:void 0,Z;if(typeof X==="string"){let H=m9(X),$=H.metadata??{};Z={authorization:W,state:H.state??$.state??{},token:X,meshUrl:H.meshUrl??$.meshUrl,connectionId:H.connectionId??$.connectionId,organizationId:H.organizationId??$.organizationId,ensureAuthenticated:ZS0(H.user??H.sub)},console.log("[EventBus:Debug] withBindings decoded",{meshUrl:Z.meshUrl??"NONE",connectionId:Z.connectionId??"NONE",organizationId:Z.organizationId??"NONE",stateKeys:Z.state?Object.keys(Z.state):[],hasAuth:!!Z.authorization})}else if(typeof X==="object"){Z=X;let H=m9(X.token),$=H.metadata??{},F=H.appName;Z.authorization??=W,Z.callerApp=F,Z.connectionId??=H.connectionId??$.connectionId,Z.ensureAuthenticated=ZS0(H.user??H.sub)}else Z={state:{},authorization:W,token:void 0,meshUrl:void 0,connectionId:void 0,ensureAuthenticated:()=>{throw Error("Unauthorized")}};return K.MESH_REQUEST_CONTEXT=Z,Z.state=Cj0(Z),IE6({env:K,server:Q,url:J}),K},SE6,KS0=(Y)=>{let Q=WS0(Y),X=Y.cors??SE6,J=Y.oauth,G=J?yj0(J):null,K=async(W,Z,H)=>{let $=new URL(W.url);if(G){if($.pathname==="/.well-known/oauth-protected-resource"||$.pathname==="/mcp/.well-known/oauth-protected-resource")return G.handleProtectedResourceMetadata(W);if($.pathname==="/.well-known/oauth-authorization-server")return G.handleAuthorizationServerMetadata(W);if($.pathname==="/authorize")return G.handleAuthorize(W);if($.pathname==="/oauth/callback")return G.handleOAuthCallback(W);if($.pathname==="/token"&&W.method==="POST")return G.handleToken(W);if(($.pathname==="/register"||$.pathname==="/mcp/register")&&W.method==="POST")return G.handleClientRegistration(W)}if($.pathname==="/mcp"){if(W.method==="GET")return new Response("Method not allowed",{status:405});if(G&&!G.hasAuth(W)){let F=W.clone();try{if((await F.json())?.method!=="tools/list")return G.createUnauthorizedResponse(W)}catch{return G.createUnauthorizedResponse(W)}}return Q.fetch(W,Z,H)}if($.pathname.startsWith("/mcp/call-tool")){let F=$.pathname.split("/").pop();if(!F)return new Response("Not found",{status:404});let V=await W.json(),q=await Q.callTool({toolCallId:F,toolCallInput:V});if(q instanceof Response)return q;return new Response(JSON.stringify(q),{headers:{"Content-Type":"application/json"}})}return Y.fetch?.(W,Z,H)||new Response("Not found",{status:404})};return{fetch:async(W,Z,H)=>{if(new URL(W.url).pathname==="/_healthcheck")return new Response("OK",{status:200});if(X!==!1&&W.method==="OPTIONS")return Ij0(W,X??{});let $=jE6({authToken:W.headers.get("authorization")??null,env:{...process.env,...Z},server:Q,tokenOrContext:W.headers.get("x-mesh-token")??void 0,url:W.url}),F=await PS.run({req:W,env:$,ctx:H},async()=>await K(W,$,H));if(X!==!1)return jj0(F,W,X??{});return F}}};var HS0=k(()=>{UG();xn();Sj0();uV1();cn();cn();xn();hV1();SE6={origin:(Y)=>{if(Y.includes("localhost")||Y.includes("127.0.0.1"))return Y;return Y},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]}});function nn(Y){return Buffer.from(String(Y),"utf8").toString("base64")}function an(Y){if(!Y)return null;try{let Q=Buffer.from(Y,"base64").toString("utf8"),X=Number.parseInt(Q,10);return Number.isNaN(X)||X<0?null:X}catch{return null}}function NX(Y){if(!Y?.length)return[];return Array.from(new Set(Y.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.toLowerCase())))}function fD(Y){if(!Y)return[];return NX(Y.split(","))}function rn(Y,Q){if(!Y)return Q;try{return JSON.parse(Y)}catch{return Q}}function on(Y){return Y?.["mcp.mesh"]??{}}function sn(Y){return Y.length?Y.join(","):null}function kE6(Y,Q){if(!Q?.length)return;let X=Y;for(let J of Q){if(X===null||X===void 0)return;if(typeof X!=="object")return;X=X[J]}return X}function vE6(Y,Q,X){if(!Q)return!1;if(Q==="eq")return Y===X;if(Q==="contains"||Q==="like"){let J=String(Y??"").toLowerCase(),G=String(X??"").toLowerCase();return J.includes(G)}if(Q==="in"){if(!Array.isArray(X))return!1;return X.includes(Y)}if(Q==="gt")return Number(Y)>Number(X);if(Q==="gte")return Number(Y)>=Number(X);if(Q==="lt")return Number(Y)<Number(X);if(Q==="lte")return Number(Y)<=Number(X);return!1}function cS(Y,Q){if(!Q)return!0;if(Array.isArray(Q.conditions)&&Q.conditions.length){if(Q.operator==="and")return Q.conditions.every((X)=>cS(Y,X));if(Q.operator==="or")return Q.conditions.some((X)=>cS(Y,X));if(Q.operator==="not")return!Q.conditions.some((X)=>cS(Y,X))}return vE6(kE6(Y,Q.field),Q.operator,Q.value)}class nS{db;constructor(Y){this.db=Y}async create(Y){let Q=new Date().toISOString(),X=Y._meta??{},J=on(X),G=NX(J.tags),K=NX(J.categories),W={id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,server_json:JSON.stringify(Y.server),meta_json:JSON.stringify(X),tags:sn(G),categories:sn(K),is_public:Y.is_public?1:0,is_unlisted:Y.is_unlisted?1:0,created_at:Q,updated_at:Q,created_by:Y.created_by??null};await this.db.insertInto("private_registry_item").values(W).execute();let Z=await this.findById(Y.organization_id,Y.id);if(!Z)throw Error(`Failed to create registry item "${Y.id}"`);return Z}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async findByIdOrName(Y,Q){let X=await this.findById(Y,Q);if(X)return X;let J=await this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).where("title","=",Q).executeTakeFirst();return J?this.deserialize(J):null}async update(Y,Q,X){let J=await this.findById(Y,Q);if(!J)throw Error(`Registry item not found: ${Q}`);let G=X._meta??J._meta??{},K=on(G),W=NX(K.tags),Z=NX(K.categories),H={updated_at:new Date().toISOString()};if(X.title!==void 0)H.title=X.title;if(X.description!==void 0)H.description=X.description;if(X.server!==void 0)H.server_json=JSON.stringify(X.server);if(X._meta!==void 0)H.meta_json=JSON.stringify(X._meta);if(X._meta!==void 0)H.tags=sn(W),H.categories=sn(Z);if(X.is_public!==void 0)H.is_public=X.is_public?1:0;if(X.is_unlisted!==void 0)H.is_unlisted=X.is_unlisted?1:0;await this.db.updateTable("private_registry_item").set(H).where("organization_id","=",Y).where("id","=",Q).execute();let $=await this.findById(Y,Q);if(!$)throw Error(`Registry item not found after update: ${Q}`);return $}async delete(Y,Q){let X=await this.findById(Y,Q);if(!X)return null;return await this.db.deleteFrom("private_registry_item").where("organization_id","=",Y).where("id","=",Q).execute(),X}async list(Y,Q={}){let X=this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).orderBy("created_at","desc");if(!Q.includeUnlisted)X=X.where("is_unlisted","=",0);let G=(await X.execute()).map((z)=>this.deserialize(z)),K=NX(Q.tags),W=NX(Q.categories),Z=G.filter((z)=>{let D=on(z._meta),L=NX(D.tags),w=NX(D.categories),E=K.length===0||K.every((P)=>L.includes(P)),T=W.length===0||W.every((P)=>w.includes(P)),C=cS(z,Q.where);return E&&T&&C}),$=an(Q.cursor)??Q.offset??0,F=Q.limit??24,V=Z.slice($,$+F),q=$+F<Z.length,U=q?nn($+F):void 0;return{items:V,totalCount:Z.length,hasMore:q,nextCursor:U}}async listPublic(Y,Q={}){let J=(await this.db.selectFrom("private_registry_item").selectAll().where("organization_id","=",Y).where("is_public","=",1).where("is_unlisted","=",0).orderBy("created_at","desc").execute()).map((U)=>this.deserialize(U)),G=NX(Q.tags),K=NX(Q.categories),W=J.filter((U)=>{let z=on(U._meta),D=NX(z.tags),L=NX(z.categories),w=G.length===0||G.every((C)=>D.includes(C)),E=K.length===0||K.every((C)=>L.includes(C)),T=cS(U,Q.where);return w&&E&&T}),H=an(Q.cursor)??Q.offset??0,$=Q.limit??24,F=W.slice(H,H+$),V=H+$<W.length,q=V?nn(H+$):void 0;return{items:F,totalCount:W.length,hasMore:V,nextCursor:q}}async getFilters(Y,Q){let X=this.db.selectFrom("private_registry_item").select(["tags","categories"]).where("organization_id","=",Y);if(Q?.publicOnly)X=X.where("is_public","=",1);if(!Q?.includeUnlisted)X=X.where("is_unlisted","=",0);let J=await X.execute(),G=new Map,K=new Map;for(let Z of J){for(let H of fD(Z.tags))G.set(H,(G.get(H)??0)+1);for(let H of fD(Z.categories))K.set(H,(K.get(H)??0)+1)}let W=(Z)=>Array.from(Z.entries()).map(([H,$])=>({value:H,count:$})).sort((H,$)=>H.value.localeCompare($.value));return{tags:W(G),categories:W(K)}}async search(Y,Q={},X){let J=this.db.selectFrom("private_registry_item").select(["id","title","description","meta_json","server_json","tags","categories","is_public","is_unlisted"]).where("organization_id","=",Y).orderBy("created_at","desc");if(X?.publicOnly)J=J.where("is_public","=",1);if(!X?.includeUnlisted)J=J.where("is_unlisted","=",0);let G=await J.execute(),K=Q.query?.trim().toLowerCase(),W=NX(Q.tags),Z=NX(Q.categories),H=G.filter((L)=>{if(K){let w=rn(L.server_json,{}),T=rn(L.meta_json,{})?.["mcp.mesh"]?.short_description??"";if(![L.id,L.title,L.description??"",w.name??"",w.description??"",T].join(" ").toLowerCase().includes(K))return!1}if(W.length>0){let w=NX(fD(L.tags));if(!W.every((E)=>w.includes(E)))return!1}if(Z.length>0){let w=NX(fD(L.categories));if(!Z.every((E)=>w.includes(E)))return!1}return!0}),F=an(Q.cursor)??0,V=Q.limit??20,q=H.slice(F,F+V),U=F+V<H.length,z=U?nn(F+V):void 0;return{items:q.map((L)=>({id:L.id,title:L.title,tags:fD(L.tags),categories:fD(L.categories),is_public:L.is_public===1,is_unlisted:L.is_unlisted===1})),totalCount:H.length,hasMore:U,nextCursor:z}}deserialize(Y){let Q=rn(Y.server_json,{}),X=rn(Y.meta_json,{});return{id:Y.id,name:typeof Q.name==="string"?Q.name:void 0,title:Y.title,description:Y.description,_meta:X,server:Q,is_public:Y.is_public===1,is_unlisted:Y.is_unlisted===1,created_at:Y.created_at,updated_at:Y.updated_at,...Y.created_by?{created_by:Y.created_by}:{}}}}var iV1=()=>{};var tn,_E6,en,mZ,aV1,yE6,mq,OA,wG,bD,rV1,$S0,oV1,FS0,sV1,VS0,tV1,qS0,NA,fE6,iS,bE6,Yi,eV1,BS0,US0,Yq1,zS0,DS0,OS0,NS0,LS0,MS0,wS0,AS0,hE6,Qq1,PS0,ES0,Xq1,TS0;var cY=k(()=>{MG();i1();tn=B.object({name:B.string(),title:B.string().optional(),description:B.string().optional(),version:B.string().optional(),websiteUrl:B.string().optional(),icons:B.array(B.object({src:B.string()})).optional(),remotes:B.array(B.object({type:B.string().optional(),url:B.string().optional(),name:B.string().optional(),title:B.string().optional(),description:B.string().optional()})).optional(),packages:B.array(B.object({identifier:B.string(),version:B.string().optional()})).optional(),repository:B.object({url:B.string().optional(),source:B.string().optional(),subfolder:B.string().optional()}).optional()}),_E6=B.object({name:B.string(),description:B.string().nullable().optional()}),en=B.object({"mcp.mesh":B.object({verified:B.boolean().optional(),tags:B.array(B.string()).optional(),categories:B.array(B.string()).optional(),friendly_name:B.string().nullable().optional(),short_description:B.string().max(160).nullable().optional(),owner:B.string().nullable().optional(),readme:B.string().max(50000).nullable().optional(),readme_url:B.string().url().nullable().optional(),has_remote:B.boolean().optional(),has_oauth:B.boolean().optional(),tools:B.array(_E6).optional()}).optional()}).catchall(B.unknown()),mZ=B.object({id:B.string(),name:B.string().optional(),title:B.string(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn,is_public:B.boolean().optional(),created_at:B.string(),updated_at:B.string(),created_by:B.string().optional()}),aV1=B.object({id:B.string(),title:B.string(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn,is_public:B.boolean().optional()}),yE6=B.object({title:B.string().optional(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn.optional(),is_public:B.boolean().optional()}),mq=uZ.extend({tags:B.array(B.string()).optional().describe("Filter by tags (AND semantics)"),categories:B.array(B.string()).optional().describe("Filter by categories (AND semantics)"),cursor:B.string().optional().describe("Pagination cursor")}).describe("List registry items with optional filtering and pagination."),OA=B.object({items:B.array(mZ),totalCount:B.number(),hasMore:B.boolean().optional(),nextCursor:B.string().optional()}),wG=B.object({id:B.string().optional().describe("Registry item ID"),name:B.string().optional().describe("Registry item name (alias for id)")}).refine((Y)=>Y.id||Y.name,{message:"At least one of 'id' or 'name' is required"}).describe("Get a registry item by ID or name."),bD=B.object({item:mZ.nullable()}),rV1=B.object({data:aV1}),$S0=B.object({item:mZ}),oV1=B.object({items:B.array(aV1).min(1)}),FS0=B.object({created:B.number(),errors:B.array(B.object({id:B.string(),error:B.string()}))}),sV1=B.object({id:B.string(),data:yE6}),VS0=B.object({item:mZ}),tV1=B.object({id:B.string()}),qS0=B.object({item:mZ}),NA=B.object({tags:B.array(B.object({value:B.string(),count:B.number()})),categories:B.array(B.object({value:B.string(),count:B.number()}))}),fE6=B.enum(["description","short_description","tags","categories","readme"]),iS=B.object({query:B.string().optional().describe("Free-text search across id, title, description, server name"),tags:B.array(B.string()).optional().describe("Filter by tags (AND)"),categories:B.array(B.string()).optional().describe("Filter by categories (AND)"),limit:B.number().int().min(1).max(100).optional().describe("Max results (default 20)"),cursor:B.string().optional().describe("Pagination cursor")}).describe("Lightweight search returning minimal fields (id, title, tags, categories, is_public)."),bE6=B.object({id:B.string(),title:B.string(),tags:B.array(B.string()),categories:B.array(B.string()),is_public:B.boolean()}),Yi=B.object({items:B.array(bE6),totalCount:B.number(),hasMore:B.boolean().optional(),nextCursor:B.string().optional()}),eV1=B.object({type:fE6.describe("Which content to generate"),llmConnectionId:B.string().describe("Connection ID of a language model"),modelId:B.string().describe("Model ID to use"),context:B.object({name:B.string().optional(),provider:B.string().optional(),url:B.string().optional(),owner:B.string().optional(),repositoryUrl:B.string().optional(),description:B.string().optional(),shortDescription:B.string().optional(),tags:B.array(B.string()).optional(),categories:B.array(B.string()).optional(),availableTags:B.array(B.string()).optional(),availableCategories:B.array(B.string()).optional(),tools:B.array(B.object({name:B.string(),description:B.string().nullable().optional()})).optional()})}),BS0=B.object({result:B.string().optional(),items:B.array(B.string()).optional()}),US0=B.enum(["pending","approved","rejected"]),Yq1=B.object({id:B.string(),organization_id:B.string(),requested_id:B.string().nullable().optional(),status:US0,title:B.string(),description:B.string().nullable().optional(),_meta:en.optional(),server:tn,requester_name:B.string().nullable().optional(),requester_email:B.string().nullable().optional(),reviewer_notes:B.string().nullable().optional(),created_at:B.string(),updated_at:B.string()}),zS0=B.object({status:US0.optional(),limit:B.number().int().min(1).max(200).optional(),offset:B.number().int().min(0).optional(),sortBy:B.enum(["created_at","title"]).optional(),sortDirection:B.enum(["asc","desc"]).optional()}),DS0=B.object({items:B.array(Yq1),totalCount:B.number()}),OS0=B.object({id:B.string(),status:B.enum(["approved","rejected"]),reviewerNotes:B.string().nullable().optional()}),NS0=B.object({item:Yq1}),LS0=B.object({pending:B.number()}),MS0=B.object({id:B.string()}),wS0=B.object({item:Yq1.nullable()}),AS0=B.object({data:aV1,requester:B.object({name:B.string().optional(),email:B.string().email().optional()}).optional()}),hE6=B.object({id:B.string(),name:B.string(),prefix:B.string(),createdAt:B.string()}),Qq1=B.object({name:B.string().min(1).max(64).describe("A descriptive name for this key")}),PS0=B.object({id:B.string(),name:B.string(),prefix:B.string(),key:B.string().describe("The full API key \u2014 shown only once!"),createdAt:B.string()}),ES0=B.object({items:B.array(hE6)}),Xq1=B.object({keyId:B.string()}),TS0=B.object({success:B.boolean(),keyId:B.string()})});function xE6(Y,Q){let X=u$({id:"COLLECTION_REGISTRY_APP_LIST",description:"List public registry items",inputSchema:mq,outputSchema:OA,execute:async({context:Z})=>{return await Y.listPublic(Q,{limit:Z.limit,offset:Z.offset,cursor:Z.cursor,tags:Z.tags,categories:Z.categories,where:Z.where})}}),J=u$({id:"COLLECTION_REGISTRY_APP_GET",description:"Get a public registry item by ID or name",inputSchema:wG,outputSchema:bD,execute:async({context:Z})=>{let H=Z.id??Z.name;if(!H)return{item:null};let $=await Y.findByIdOrName(Q,H);if($&&$.is_public)return{item:$};return{item:null}}}),G=u$({id:"COLLECTION_REGISTRY_APP_VERSIONS",description:"Get available versions of a public registry item",inputSchema:wG,outputSchema:B.object({versions:B.array(bD.shape.item)}),execute:async({context:Z})=>{let H=Z.id??Z.name;if(!H)return{versions:[]};let $=await Y.findByIdOrName(Q,H);if($&&$.is_public)return{versions:[$]};return{versions:[]}}}),K=u$({id:"COLLECTION_REGISTRY_APP_SEARCH",description:"Search public registry items returning minimal data (id, title, tags, categories, is_public). Use this instead of LIST when you need to find items efficiently without loading full details.",inputSchema:iS,outputSchema:Yi,execute:async({context:Z})=>{return await Y.search(Q,Z,{publicOnly:!0})}}),W=u$({id:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get available tags and categories for public registry items",inputSchema:B.object({}),outputSchema:NA,execute:async()=>{return await Y.getFilters(Q,{publicOnly:!0})}});return[X,K,J,G,W]}function Jq1(Y,Q){let X=Q.db,J=new nS(X);Y.all("/org/:orgSlug/registry/*",async(G)=>{let K=G.req.param("orgSlug");console.log(`[Public Registry MCP] Request for org slug: ${K}, path: ${G.req.path}`);let W=await X.selectFrom("organization").select(["id","slug","name"]).where("slug","=",K).executeTakeFirst();if(console.log("[Public Registry MCP] Found org:",W),!W)return console.log(`[Public Registry MCP] Organization not found: ${K}`),G.json({error:"Organization not found"},404);let Z=xE6(J,W.id),H=KS0({tools:()=>Z}),$=new URL(G.req.url),F=G.req.path.replace(`/org/${K}/registry`,""),V=new URL(F||"/",$.origin);$.searchParams.forEach((z,D)=>{V.searchParams.set(D,z)}),console.log(`[Public Registry MCP] Rewriting ${$.pathname} to ${V.pathname}`);let q=new Request(V.toString(),{method:G.req.method,headers:G.req.raw.headers,body:G.req.method!=="GET"&&G.req.method!=="HEAD"?G.req.raw.body:void 0}),U={organizationId:W.id,db:X,MESH_REQUEST_CONTEXT:{},MESH_APP_DEPLOYMENT_ID:"public-registry",IS_LOCAL:!1};return await H.fetch(q,U,G)})}var CS0=k(()=>{HS0();cn();i1();iV1();cY()});import{randomUUID as gE6}from"crypto";function RS0(Y,Q){if(!Y)return Q;try{return JSON.parse(Y)}catch{return Q}}class aS{db;constructor(Y){this.db=Y}async createOrUpdate(Y){let Q=new Date().toISOString(),X=await this.findPendingByRequestedId(Y.organization_id,Y.requested_id);if(X){let W={title:Y.title,description:Y.description??null,server_json:JSON.stringify(Y.server),meta_json:Y._meta?JSON.stringify(Y._meta):null,requester_name:Y.requester_name??null,requester_email:Y.requester_email??null,updated_at:Q};await this.db.updateTable("private_registry_publish_request").set(W).where("organization_id","=",Y.organization_id).where("id","=",X.id).execute();let Z=await this.findById(Y.organization_id,X.id);if(!Z)throw Error("Failed to update publish request");return Z}let J=gE6(),G={id:J,organization_id:Y.organization_id,requested_id:Y.requested_id,status:"pending",title:Y.title,description:Y.description??null,server_json:JSON.stringify(Y.server),meta_json:Y._meta?JSON.stringify(Y._meta):null,requester_name:Y.requester_name??null,requester_email:Y.requester_email??null,reviewer_notes:null,created_at:Q,updated_at:Q};await this.db.insertInto("private_registry_publish_request").values(G).execute();let K=await this.findById(Y.organization_id,J);if(!K)throw Error("Failed to create publish request");return K}async findPendingByRequestedId(Y,Q){let X=await this.db.selectFrom("private_registry_publish_request").selectAll().where("organization_id","=",Y).where("requested_id","=",Q).where("status","=","pending").executeTakeFirst();return X?this.deserialize(X):null}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_publish_request").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async list(Y,Q={}){let X=this.db.selectFrom("private_registry_publish_request").selectAll().where("organization_id","=",Y),J=this.db.selectFrom("private_registry_publish_request").select(($)=>$.fn.countAll().as("count")).where("organization_id","=",Y);if(Q.status)X=X.where("status","=",Q.status),J=J.where("status","=",Q.status);let G=await J.executeTakeFirst(),K=Number(G?.count??0),W=Q.sortBy??"created_at",Z=Q.sortDirection??"desc";if(W==="title")X=X.orderBy("title",Z);else X=X.orderBy("created_at",Z);return{items:(await X.limit(Q.limit??24).offset(Q.offset??0).execute()).map(($)=>this.deserialize($)),totalCount:K}}async updateStatus(Y,Q,X,J){let G={status:X,updated_at:new Date().toISOString(),reviewer_notes:J??null};await this.db.updateTable("private_registry_publish_request").set(G).where("organization_id","=",Y).where("id","=",Q).execute();let K=await this.findById(Y,Q);if(!K)throw Error(`Publish request not found: ${Q}`);return K}async countPending(Y){let Q=await this.db.selectFrom("private_registry_publish_request").select((X)=>X.fn.countAll().as("count")).where("organization_id","=",Y).where("status","=","pending").executeTakeFirst();return Number(Q?.count??0)}async delete(Y,Q){let X=await this.findById(Y,Q);if(!X)return null;return await this.db.deleteFrom("private_registry_publish_request").where("organization_id","=",Y).where("id","=",Q).execute(),X}deserialize(Y){return{id:Y.id,organization_id:Y.organization_id,requested_id:Y.requested_id??null,status:Y.status,title:Y.title,description:Y.description,_meta:RS0(Y.meta_json,{}),server:RS0(Y.server_json,{name:""}),requester_name:Y.requester_name,requester_email:Y.requester_email,reviewer_notes:Y.reviewer_notes,created_at:Y.created_at,updated_at:Y.updated_at}}}var Gq1=()=>{};import{randomUUID as uE6}from"crypto";async function IS0(Y){let X=new TextEncoder().encode(Y),J=await crypto.subtle.digest("SHA-256",X);return Array.from(new Uint8Array(J)).map((K)=>K.toString(16).padStart(2,"0")).join("")}function mE6(){let Y=new Uint8Array(32);return crypto.getRandomValues(Y),`prk_${Array.from(Y).map((X)=>X.toString(16).padStart(2,"0")).join("")}`}class rS{db;constructor(Y){this.db=Y}async generate(Y,Q){let X=uE6(),J=mE6(),G=await IS0(J),K=J.slice(0,12),W=new Date().toISOString();return await this.db.insertInto("private_registry_publish_api_key").values({id:X,organization_id:Y,name:Q,key_hash:G,prefix:K,created_at:W}).execute(),{entity:{id:X,organization_id:Y,name:Q,prefix:K,created_at:W},key:J}}async list(Y){return await this.db.selectFrom("private_registry_publish_api_key").select(["id","organization_id","name","prefix","created_at"]).where("organization_id","=",Y).orderBy("created_at","desc").execute()}async revoke(Y,Q){return(await this.db.deleteFrom("private_registry_publish_api_key").where("organization_id","=",Y).where("id","=",Q).execute()).length>0}async validate(Y,Q){let X=await IS0(Q),J=await this.db.selectFrom("private_registry_publish_api_key").select(["id"]).where("organization_id","=",Y).where("key_hash","=",X).executeTakeFirst();return Boolean(J)}async hasKeys(Y){let Q=await this.db.selectFrom("private_registry_publish_api_key").select((X)=>X.fn.countAll().as("count")).where("organization_id","=",Y).executeTakeFirst();return Number(Q?.count??0)>0}}var Wq1=()=>{};import{sql as lE6}from"kysely";import{randomUUID as jS0}from"crypto";async function pE6(Y){let Q=new Date().toISOString(),X=jS0(),J=IY.SELF(Y.organizationId),G="registry.publish_request.created",K={requestId:Y.request.id,requestedId:Y.request.requested_id,title:Y.request.title,status:Y.request.status,createdAt:Y.request.created_at,requester:{name:Y.request.requester_name,email:Y.request.requester_email}};await Y.db.insertInto("events").values({id:X,organization_id:Y.organizationId,type:"registry.publish_request.created",source:J,specversion:"1.0",subject:Y.request.id,time:Q,datacontenttype:"application/json",dataschema:null,data:JSON.stringify(K),cron:null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute();let W=await Y.db.selectFrom("event_subscriptions").select(["id"]).where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=","registry.publish_request.created").where((Z)=>Z.or([Z("publisher","is",null),Z("publisher","=",J)])).execute();if(W.length>0)await Y.db.insertInto("event_deliveries").values(W.map((Z)=>({id:jS0(),event_id:X,subscription_id:Z.id,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:null,created_at:Q}))).execute();try{await lE6`SELECT pg_notify('mesh_events', ${X})`.execute(Y.db)}catch{}}async function cE6(Y,Q){let J=(await Y.selectFrom("organization").select(["id"]).where("id","=",Q).execute())[0];if(J?.id)return J.id;return(await Y.selectFrom("organization").select(["id"]).where("slug","=",Q).execute())[0]?.id??null}async function nE6(Y,Q){let X=await Y.selectFrom("project_plugin_configs").innerJoin("projects","projects.id","project_plugin_configs.project_id").select(["project_plugin_configs.settings as settings"]).where("projects.organization_id","=",Q).where("project_plugin_configs.plugin_id","=",_H).execute();for(let J of X){let G=J.settings,K=typeof G==="string"?(()=>{try{return JSON.parse(G)}catch{return{}}})():G??{};if(K.acceptPublishRequests===!0){let W=K.rateLimitWindow==="minute"?"minute":"hour",Z=K.rateLimitMax,H=typeof Z==="number"&&Number.isFinite(Z)&&Z>=1?Math.floor(Z):kS0;return{acceptPublishRequests:!0,requireApiToken:K.requireApiToken===!0,rateLimitEnabled:K.rateLimitEnabled===void 0?SS0:K.rateLimitEnabled===!0,rateLimitWindow:W,rateLimitMax:H}}}return{acceptPublishRequests:!1,requireApiToken:!1,rateLimitEnabled:SS0,rateLimitWindow:dE6,rateLimitMax:kS0}}async function iE6(Y,Q,X){let J=X==="minute"?60000:3600000,G=new Date(Date.now()-J).toISOString(),K=await Y.selectFrom("private_registry_publish_request").select((W)=>W.fn.countAll().as("count")).where("organization_id","=",Q).where("created_at",">=",G).executeTakeFirst();return Number(K?.count??0)}async function aE6(Y,Q,X,J){let G=await Y.selectFrom("private_registry_item").select(["id","title"]).where("organization_id","=",Q).where((K)=>K.or([K("id","=",X),K("title","=",J)])).executeTakeFirst();return G?{id:String(G.id),title:String(G.title)}:null}function Zq1(Y,Q){let{db:X,db:J}=Q,G=new aS(J),K=new rS(J);Y.post("/org/:orgRef/registry/publish-request",async(W)=>{let Z=W.req.param("orgRef"),H=await cE6(X,Z);if(!H)return W.json({error:"Organization not found"},404);let $=await nE6(X,H);if(!$.acceptPublishRequests)return W.json({error:"Publish requests are not enabled for this registry."},403);if($.requireApiToken){let z=W.req.header("Authorization"),D=z?.startsWith("Bearer ")?z.slice(7).trim():null;if(!D)return W.json({error:"API key required. Use Authorization: Bearer <key>"},401);if(!await K.validate(H,D))return W.json({error:"Invalid API key"},401)}if($.rateLimitEnabled){if(await iE6(J,H,$.rateLimitWindow)>=$.rateLimitMax)return W.json({error:"Too many publish requests. Please try again later.",retryAfterSeconds:$.rateLimitWindow==="minute"?60:3600},429)}let F;try{F=await W.req.json()}catch{return W.json({error:"Invalid JSON body"},400)}let V=AS0.safeParse(F);if(!V.success)return W.json({error:"Invalid publish request payload",details:B.treeifyError(V.error)},400);let q=await aE6(J,H,V.data.data.id,V.data.data.title);if(q)return W.json({error:"A registry item with the same id or title already exists. Please use a different name/id.",conflict:q},409);let U=await G.createOrUpdate({organization_id:H,requested_id:V.data.data.id,title:V.data.data.title,description:V.data.data.description??null,_meta:V.data.data._meta,server:V.data.data.server,requester_name:V.data.requester?.name??null,requester_email:V.data.requester?.email??null});try{await pE6({db:X,organizationId:H,request:U})}catch(z){console.warn("[private-registry] failed to emit publish-request event:",z)}return W.json({id:U.id,requested_id:U.requested_id,status:U.status},201)})}var SS0=!0,dE6="hour",kS0=100;var vS0=k(()=>{KY();i1();kD();Gq1();Wq1();cY()});var _S0=k(()=>{CS0();vS0()});function yS0(Y){Kq1=Y}function S4(){if(!Kq1)throw Error(`Plugin storage not initialized. Make sure the "${_H}" plugin is enabled.`);return Kq1}async function rE6(Y){if(!Y.organization)throw Error("Organization context required");return await Y.access.check(),Y}function Y6(Y,Q){return async(X,J)=>{let G=await rE6(J);return Q(X,G)}}function oE6(Y){if(!Y)return{};if(typeof Y==="string")try{return JSON.parse(Y)}catch{return{}}if(typeof Y==="object")return Y;return{}}async function oS(Y,Q){let J=(await Y.db.selectFrom("project_plugin_configs").innerJoin("projects","projects.id","project_plugin_configs.project_id").select(["project_plugin_configs.settings as settings"]).where("projects.organization_id","=",Q).where("project_plugin_configs.plugin_id","=",_H).execute()).map((K)=>oE6(K.settings)),G={acceptPublishRequests:J.some((K)=>K.acceptPublishRequests===!0),requireApiToken:J.some((K)=>K.requireApiToken===!0),storePrivateOnly:J.some((K)=>K.storePrivateOnly===!0)};if(G.acceptPublishRequests||G.requireApiToken||G.storePrivateOnly)return G;for(let K of J)if(Object.keys(K).length>0)return K;return{}}var Kq1=null;var J9=k(()=>{kD()});import{randomUUID as fS0}from"crypto";function bS0(Y,Q){if(!Y)return Q;try{return JSON.parse(Y)}catch{return Q}}class Hq1{db;constructor(Y){this.db=Y}async create(Y){let Q=fS0(),X=new Date().toISOString(),J={id:Q,organization_id:Y.organization_id,status:Y.status??"pending",config_snapshot:Y.config_snapshot?JSON.stringify(Y.config_snapshot):null,total_items:Y.total_items??0,tested_items:0,passed_items:0,failed_items:0,skipped_items:0,current_item_id:null,started_at:Y.started_at??null,finished_at:null,created_at:X};await this.db.insertInto("private_registry_monitor_run").values(J).execute();let G=await this.findById(Y.organization_id,Q);if(!G)throw Error(`Failed to create monitor run ${Q}`);return G}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_run").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserializeRun(X):null}async list(Y,Q={}){let X=this.db.selectFrom("private_registry_monitor_run").selectAll().where("organization_id","=",Y),J=this.db.selectFrom("private_registry_monitor_run").select((Z)=>Z.fn.countAll().as("count")).where("organization_id","=",Y);if(Q.status)X=X.where("status","=",Q.status),J=J.where("status","=",Q.status);let G=await J.executeTakeFirst(),K=Number(G?.count??0);return{items:(await X.orderBy("created_at","desc").limit(Q.limit??24).offset(Q.offset??0).execute()).map((Z)=>this.deserializeRun(Z)),totalCount:K}}async update(Y,Q,X){let J={};if(X.total_items!==void 0)J.total_items=X.total_items;if(X.status!==void 0)J.status=X.status;if(X.tested_items!==void 0)J.tested_items=X.tested_items;if(X.passed_items!==void 0)J.passed_items=X.passed_items;if(X.failed_items!==void 0)J.failed_items=X.failed_items;if(X.skipped_items!==void 0)J.skipped_items=X.skipped_items;if(X.current_item_id!==void 0)J.current_item_id=X.current_item_id;if(X.started_at!==void 0)J.started_at=X.started_at;if(X.finished_at!==void 0)J.finished_at=X.finished_at;await this.db.updateTable("private_registry_monitor_run").set(J).where("organization_id","=",Y).where("id","=",Q).execute();let G=await this.findById(Y,Q);if(!G)throw Error(`Monitor run not found: ${Q}`);return G}deserializeRun(Y){return{id:Y.id,organization_id:Y.organization_id,status:Y.status,config_snapshot:bS0(Y.config_snapshot,null),total_items:Number(Y.total_items??0),tested_items:Number(Y.tested_items??0),passed_items:Number(Y.passed_items??0),failed_items:Number(Y.failed_items??0),skipped_items:Number(Y.skipped_items??0),current_item_id:Y.current_item_id,started_at:Y.started_at,finished_at:Y.finished_at,created_at:Y.created_at}}}class $q1{db;constructor(Y){this.db=Y}async create(Y){let Q=fS0(),X=new Date().toISOString(),J={id:Q,run_id:Y.run_id,organization_id:Y.organization_id,item_id:Y.item_id,item_title:Y.item_title,status:Y.status,error_message:Y.error_message??null,connection_ok:Y.connection_ok?1:0,tools_listed:Y.tools_listed?1:0,tool_results:Y.tool_results?JSON.stringify(Y.tool_results):null,agent_summary:Y.agent_summary??null,duration_ms:Y.duration_ms??0,action_taken:Y.action_taken??"none",tested_at:X};await this.db.insertInto("private_registry_monitor_result").values(J).execute();let G=await this.findById(Y.organization_id,Q);if(!G)throw Error("Failed to create test result");return G}async findById(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_result").selectAll().where("organization_id","=",Y).where("id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async listByRun(Y,Q,X={}){let J=this.db.selectFrom("private_registry_monitor_result").selectAll().where("organization_id","=",Y).where("run_id","=",Q),G=this.db.selectFrom("private_registry_monitor_result").select((H)=>H.fn.countAll().as("count")).where("organization_id","=",Y).where("run_id","=",Q);if(X.status)J=J.where("status","=",X.status),G=G.where("status","=",X.status);let K=await G.executeTakeFirst(),W=Number(K?.count??0);return{items:(await J.orderBy("tested_at","desc").limit(X.limit??50).offset(X.offset??0).execute()).map((H)=>this.deserialize(H)),totalCount:W}}async update(Y,Q,X){let J={};if(X.status!==void 0)J.status=X.status;if(X.error_message!==void 0)J.error_message=X.error_message;if(X.connection_ok!==void 0)J.connection_ok=X.connection_ok?1:0;if(X.tools_listed!==void 0)J.tools_listed=X.tools_listed?1:0;if(X.tool_results!==void 0)J.tool_results=JSON.stringify(X.tool_results);if(X.agent_summary!==void 0)J.agent_summary=X.agent_summary;if(X.duration_ms!==void 0)J.duration_ms=X.duration_ms;if(X.action_taken!==void 0)J.action_taken=X.action_taken;await this.db.updateTable("private_registry_monitor_result").set(J).where("organization_id","=",Y).where("id","=",Q).execute();let G=await this.findById(Y,Q);if(!G)throw Error(`Monitor result not found: ${Q}`);return G}deserialize(Y){return{id:Y.id,run_id:Y.run_id,organization_id:Y.organization_id,item_id:Y.item_id,item_title:Y.item_title,status:Y.status,error_message:Y.error_message,connection_ok:Y.connection_ok===1,tools_listed:Y.tools_listed===1,tool_results:bS0(Y.tool_results,[]),agent_summary:Y.agent_summary,duration_ms:Number(Y.duration_ms??0),action_taken:Y.action_taken,tested_at:Y.tested_at}}}var hS0=()=>{};import{randomUUID as sE6}from"crypto";class Fq1{db;constructor(Y){this.db=Y}async findByItemId(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_connection").selectAll().where("organization_id","=",Y).where("item_id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async list(Y){return(await this.db.selectFrom("private_registry_monitor_connection").selectAll().where("organization_id","=",Y).orderBy("updated_at","desc").execute()).map((X)=>this.deserialize(X))}async findByConnectionId(Y,Q){let X=await this.db.selectFrom("private_registry_monitor_connection").selectAll().where("organization_id","=",Y).where("connection_id","=",Q).executeTakeFirst();return X?this.deserialize(X):null}async upsert(Y){let Q=await this.findByItemId(Y.organization_id,Y.item_id),X=new Date().toISOString();if(!Q){let G={id:sE6(),organization_id:Y.organization_id,item_id:Y.item_id,connection_id:Y.connection_id,auth_status:Y.auth_status??"none",created_at:X,updated_at:X};await this.db.insertInto("private_registry_monitor_connection").values(G).execute()}else{let G={connection_id:Y.connection_id,auth_status:Y.auth_status??Q.auth_status,updated_at:X};await this.db.updateTable("private_registry_monitor_connection").set(G).where("organization_id","=",Y.organization_id).where("item_id","=",Y.item_id).execute()}let J=await this.findByItemId(Y.organization_id,Y.item_id);if(!J)throw Error("Failed to save monitor connection");return J}async updateAuthStatus(Y,Q,X){return await this.db.updateTable("private_registry_monitor_connection").set({auth_status:X,updated_at:new Date().toISOString()}).where("organization_id","=",Y).where("item_id","=",Q).execute(),this.findByItemId(Y,Q)}deserialize(Y){return{id:Y.id,organization_id:Y.organization_id,item_id:Y.item_id,connection_id:Y.connection_id,auth_status:Y.auth_status,created_at:Y.created_at,updated_at:Y.updated_at}}}var xS0=()=>{};function gS0(Y){let Q=Y.db,X={items:new nS(Q),publishRequests:new aS(Q),publishApiKeys:new rS(Q),monitorRuns:new Hq1(Q),monitorResults:new $q1(Q),monitorConnections:new Fq1(Q)};return yS0(X),X}var uS0=k(()=>{J9();iV1();Gq1();Wq1();hS0();xS0()});var mS0;var lS0=k(()=>{cY();J9();mS0={name:"REGISTRY_ITEM_BULK_CREATE",description:"Create many private registry items at once",inputSchema:oV1,outputSchema:FS0,handler:Y6(oV1,async(Y,Q)=>{let X=S4(),J=[],G=0;for(let K of Y.items)try{await X.items.create({...K,organization_id:Q.organization.id,created_by:Q.auth.user?.id??null}),G+=1}catch(W){J.push({id:K.id,error:W instanceof Error?W.message:"Unknown error"})}return{created:G,errors:J}})}});function tE6(Y){return Array.from(new Set(Y.map((Q)=>Q.trim().toLowerCase()).filter((Q)=>Q.length>0)))}function eE6(Y){let X=Y.structuredContent?.content?.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text??"").join(`
1066
1066
  `).trim();if(X)return X;return Y.content?.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text??"").join(`
1067
1067
  `).trim()??""}function Y26(Y){let Q=Y.context,X=JSON.stringify({name:Q.name??"",provider:Q.provider??"",url:Q.url??"",owner:Q.owner??"",repositoryUrl:Q.repositoryUrl??"",description:Q.description??"",shortDescription:Q.shortDescription??"",tags:Q.tags??[],categories:Q.categories??[],availableTags:Q.availableTags??[],availableCategories:Q.availableCategories??[],tools:Q.tools??[]},null,2);if(Y.type==="description")return{system:"You are an assistant that writes concise MCP registry descriptions.",user:`Use the context below to write a clear English description for this MCP server.
1068
1068
  Rules:
@@ -1319,8 +1319,8 @@ ${Y.stack}`;return Q}if(typeof Y==="object"&&Y!==null){let Q=Y,X="";if(typeof Q.
1319
1319
  ${Q.stack}`;return X}try{let G=JSON.stringify(Q,null,2);if(G!=="{}"&&G.length<1000){if(typeof Q.stack==="string"&&Q.stack&&Q.stack.length<2000)return`${G}
1320
1320
 
1321
1321
  Stack trace:
1322
- ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=HO(Y,H);Z.resolve($),$.dispose()}catch($){let F=KO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=KO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HO(Y,W)}catch(K){let W=KO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Jp0=()=>{};function HD1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Yr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){HD1(Y);let K=await Promise.race([G,Nh6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Xv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}async function $D1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"input",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (input). Got ${D}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}var Nh6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Gp0=k(()=>{Xp0();Jp0()});var Qr=k(()=>{Gp0()});async function Lh6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function Wp0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Mh6(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let U=await Q.createMCPProxy(q);return{connection:q,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,U),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,U])=>{try{let D=(await U.proxy.listTools()).tools,L=X.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);D=D.filter((E)=>w.has(E.name))}return{connectionId:q,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,z),null}})),Z=new Set,H=[],$=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=q.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:z}}),$.set(L.name,U)}}let F=async(q,U)=>{let z=$.get(q);if(!z)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:U})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function $P(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await Lh6(J,Y);else X=await Wp0(Q.id,Y)}else X=await Wp0(Q.id,Y);return Mh6(X,Y)}function wh6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function Ah6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Xr(Y,Q,X){let J=wh6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:Ah6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Jr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Gr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Xv({code:Y,tools:J,timeoutMs:X})}function Jv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function GB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function KF(Y){let Q=new Set(Ph6);return Y.filter((X)=>!Q.has(X.name))}var Ph6;var $O=k(()=>{Qr();Ph6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var FD1;var Zp0=k(()=>{F4();Qv();$O();FD1=s1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:id0,outputSchema:ad0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q),J=Xr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var VD1;var Kp0=k(()=>{F4();Qv();$O();VD1=s1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:rd0,outputSchema:od0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return Jr(Y.tools,X.tools)}})});var qD1;var Hp0=k(()=>{F4();Qv();$O();qD1=s1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:sd0,outputSchema:td0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return await Gr(Y.code,X,Y.timeoutMs)}})});var $p0=k(()=>{Zp0();Kp0();Hp0();Qv()});var Th6,Ch6,BD1;var Fp0=k(()=>{KY();i1();F4();Sn();b$();Th6=B.object({data:PR.describe("Data for the new connection (id is auto-generated if not provided)")}),Ch6=B.object({item:W5.describe("The created connection entity")}),BD1=s1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Th6,outputSchema:Ch6,handler:async(Y,Q)=>{z0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=zz(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Dz($)}let K=await zA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var Rh6,Ih6,Vp0;var qp0=k(()=>{i1();MG();Rh6=bH.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Ih6=hH("assistant",Rh6),Vp0=[...Ih6]});var Gv,HF,Up0,jh6,Sh6,zp0,kh6,vh6,_h6,yh6,fh6,bh6,Dp0,hh6,xh6,gh6,uh6,mh6,lh6,dh6,ph6,ch6,nh6,CK9,ih6,RK9,Bp0,ah6,rh6,UD1,Wv;var Wr=k(()=>{i1();_D();MG();Gv=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),Gv),B.array(Gv)])),HF=B.record(B.string(),B.record(B.string(),Gv)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Up0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:HF}),jh6=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),Sh6=B.string().describe("File data as URL string"),zp0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:Sh6,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HF}),kh6=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),vh6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:HF}),_h6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),yh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HF}),fh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),bh6=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:Gv}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:Gv}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))}),B.object({type:B.literal("execution-denied"),reason:B.string().optional()}),B.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Dp0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:bh6.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:HF}),hh6=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),xh6=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),gh6=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:HF}),uh6=B.object({role:B.literal("user"),content:B.array(B.union([Up0,zp0])).describe("User message content parts (text or file)"),providerOptions:HF}),mh6=B.object({role:B.literal("assistant"),content:B.array(B.union([Up0,zp0,vh6,yh6,Dp0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HF}),lh6=B.object({role:B.literal("tool"),content:B.array(Dp0).describe("Tool message content (tool results)"),providerOptions:HF}),dh6=B.union([gh6,uh6,mh6,lh6]),ph6=B.array(dh6).describe("A list of messages forming the prompt"),ch6=B.object({prompt:ph6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),nh6=B.object({content:B.array(B.union([jh6,kh6,_h6,fh6,hh6,xh6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),CK9=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),ih6=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),RK9=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Bp0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:ch6}),ah6=bH.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),rh6=hH("llm",ah6,{readOnly:!0}),UD1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:ih6},{name:"LLM_DO_STREAM",inputSchema:Bp0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Bp0,outputSchema:nh6},...rh6],Wv=yH(UD1)});function FP(){return!1}function Zr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function VP(Y,Q){let X=B71(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:oh6,bindings:["OBJECT_STORAGE"],status:"active"}}var oh6;var Kr=k(()=>{mn();KY();i1();oh6=uS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function th6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function WB(Y){return typeof Y==="string"||typeof Y==="number"}function Hr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Hr(Y,$));case"or":return H.some(($)=>Hr(Y,$));case"not":return!H.every(($)=>Hr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=zD1(Y,K);switch(J){case"eq":return W===G;case"gt":return WB(W)&&WB(G)&&W>G;case"gte":return WB(W)&&WB(G)&&W>=G;case"lt":return WB(W)&&WB(G)&&W<G;case"lte":return WB(W)&&WB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=th6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function zD1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function eh6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=zD1(X,K),Z=zD1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var sh6,Yx6,Qx6,DD1;var Op0=k(()=>{lS();qp0();MG();Wr();mn();KY();i1();F4();Kr();b$();sh6={LLM:UD1,ASSISTANTS:Vp0,OBJECT_STORAGE:uS};Yx6=uZ.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),Qx6=x$(W5),DD1=s1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yx6,outputSchema:Qx6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=sh6[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?hn(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(FP()){let q=K7(),U=IY.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=VP(X.id,q);K.unshift(z)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((q)=>Hr(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=eh6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Xx6,OD1;var Np0=k(()=>{MG();F4();Kr();b$();Xx6=TS(W5),OD1=s1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:Xx6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),FP()&&Zr(Y.id,X.id))return{item:VP(X.id,K7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $r=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Lp0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Jx6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Gx6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function ND1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Jx6(J);if(!G)continue;let[K,W]=G,Z=$r(K,Y),H=Gx6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Mp0(Y,Q){let X=ND1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var LD1=()=>{};import{randomBytes as Wx6}from"crypto";function wp0(){if(Zv)return Zv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Zv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Zv=new Uint8Array(Wx6(32));return Zv}async function Ap0(Y,Q="5m"){let X=wp0();return await new BG(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Pp0(Y){try{let Q=wp0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Zv=null;var MD1=k(()=>{UG();Kv()});async function Ep0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class $F{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=X9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Fr=k(()=>{$7()});async function Hv(Y,Q,X){let J=Y.id,G=ND1(Y.configuration_state,Y.configuration_scopes),K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await Ap0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:process.env.MESH_URL??Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new $F(Q.db,Q.vault),q=await V.get(J);if(q){let U=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await Ep0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),F=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=q.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var wD1=k(()=>{LD1();MD1();Fr()});function Vr(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new G5({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var AD1=k(()=>{qz()});function Tp0(Y){let Q=new wS({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Cp0=k(()=>{vV1()});class $v{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Fv(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Rp0="mcp.mesh";var Ip0,PD1,FF;var Vv=k(()=>{Ip0=class Ip0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};PD1=class PD1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};FF=class FF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Ip0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new PD1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new PD1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Rp0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Zx6="mcp.mesh",qP;var jp0=k(()=>{Vv();qP=class qP extends $v{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new FF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Zx6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function kp0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function TD1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function CD1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function RD1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function Kx6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Hx6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1323
- `);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function ED1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(o3(Y.connectionId))return;let G=TD1(Y.request.params.arguments),K=CD1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map(($)=>$.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function vp0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let $=await Z(),F=Q.organization?.id;if(X&&F){let V=$.clone();(async()=>{try{let{text:q,truncated:U}=await Kx6(V,Sp0),z=Date.now()-H,D=V.headers.get("content-type")??"",L=q;if(D.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=$.status>=400,E=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof E==="string"&&E?E:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${$.status} ${$.statusText}`.trim():U?`Response body truncated to ${Sp0} bytes`:void 0,C=RD1(L),P=Hx6(q);if(P)Object.assign(C,P);await ED1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:T,durationMs:z})}catch(q){let U=Date.now()-H;await ED1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:U})}})()}return $}catch($){let F=$,V=Date.now()-H;throw await ED1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:F.message,durationMs:V}),$}}}var Sp0=262144;var ID1=k(()=>{KY()});var BP;var _p0=k(()=>{QS();ID1();BP=class BP extends $v{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,$=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let F="error"in Y,V=F?Y.error:Y.result,q=F?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record($,{"connection.id":J,"tool.name":W,status:F?"error":"success"}),F)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(F&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:q,duration:$,isError:Boolean(F)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:$}=Y;if(!$n().enabled)return;let V=Q.organization?.id;if(!V)return;let q=kp0(Z),U=RD1(Z),z=TD1(W),D=CD1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:$,errorMessage:q,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:D})}catch(L){console.error("[MonitoringTransport] Failed to log to database:",L)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var yp0=k(()=>{jp0();_p0()});async function fp0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!aK(K))throw Error("STDIO connection missing parameters");let W=Tp0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=Fv(W,(Z)=>new qP(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new BP(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),$x6(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Hv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new bV(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Hv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new SD(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var $x6;var bp0=k(()=>{b$();Rn();AR();wD1();AD1();Cp0();yp0();$x6=Vr()});function ZB(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function gp0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function qv(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var jD1,pH9,iH,hp0,xp0;var VF=k(()=>{i1();jD1=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),pH9=B.object({"tool.fn":B.string().describe("JavaScript ES module code that exports a default async function")}),iH=B.object({id:B.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description of what the tool does"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:jD1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:B.string().describe("When the virtual tool was created"),updated_at:B.string().describe("When the virtual tool was last updated")}),hp0=B.object({name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema for output"),annotations:jD1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),xp0=B.object({name:B.string().min(1).max(255).optional().describe("New tool name"),description:B.string().nullable().optional().describe("New description (null to clear)"),inputSchema:B.record(B.string(),B.unknown()).optional().describe("New input schema"),outputSchema:B.record(B.string(),B.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:jD1.nullable().optional().describe("New annotations (null to clear)"),code:B.string().optional().describe("New JavaScript code"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function FO(Y){return(Q)=>{if(Q instanceof u0&&Q.code===o0.MethodNotFound)return Y;throw Q}}var SD1=k(()=>{vQ()});class up0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function UP(Y){return new up0(Y)}function Fx6(Y,Q,X){let J=new G5({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=_5(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return VO(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,$,F)=>{return(await K()).callTool(H,$,F)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,$)=>{return(await K()).getPrompt(H,$)},J.readResource=async(H,$)=>{return(await K()).readResource(H,$)},J.callStreamableTool=async(H,$)=>{let F=await K();if("callStreamableTool"in F&&typeof F.callStreamableTool==="function")return F.callStreamableTool(H,$);let V=await F.callTool({name:H,arguments:$});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function Vx6(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,Fx6(G,Q,X));return J}async function mp0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var zP;var kD1=k(()=>{DP();SD1();qz();Qr();VF();zP=class zP extends G5{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=Vx6(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=UP(()=>this.loadToolsCache()),this._cachedResources=UP(()=>this.loadCache("resources")),this._cachedPrompts=UP(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((F)=>F.tools),$=this._selectionMap.get(W);if($?.selected_tools?.length){let F=new Set($.selected_tools);H=H.filter((V)=>F.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,F=this._connections.get(Z)?.title??"";for(let V of H){let q=V.name;if(J.has(q))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:F,...V?._meta}};X.push(U),J.set(q,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(FO({resources:[]})).then((F)=>F.resources):await W.listPrompts().catch(FO({prompts:[]})).then((F)=>F.prompts),H=this._selectionMap.get(K),$=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[$]?.length){let F=new Set(H[$]);return{connectionId:K,data:Z.filter((V)=>F.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,$=this._connections.get(W)?.title??"";for(let F of Z){let V=F.name??F.uri;if(G.has(V))continue;let q={...F,_meta:{connectionId:W,connectionTitle:$,...F?._meta}};J.push(q),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=gp0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let $=J.get(H);if(!$)continue;W[Z]=async(F)=>{let V=await $.callTool({name:Z,arguments:F});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let q=V.content;if(q?.[0]?.type==="text"&&q[0].text)try{return JSON.parse(q[0].text)}catch{return q[0].text}return V}}try{let H=`
1322
+ ${Q.stack}`;return G}}catch{}if(typeof Q.toString==="function")try{let G=Q.toString();if(G!=="[object Object]")return G}catch{}let J=Object.keys(Q);if(J.length>0)return`Object with keys: ${J.join(", ")}`;return"[object Object]"}if(typeof Y==="string")return Y;if(typeof Y==="number"||typeof Y==="boolean")return String(Y);if(typeof Y==="function")return`[Function: ${Y.name||"anon"}]`;if(typeof Y==="symbol")return Y.toString();if(typeof Y==="bigint")return Y.toString();try{return String(Y)}catch{return"Unknown value (could not convert to string)"}}function HO(Y,Q){switch(typeof Q){case"string":return Y.newString(Q);case"number":return Y.newNumber(Q);case"boolean":return Q?Y.true:Y.false;case"undefined":return Y.undefined;case"object":{if(Q===null)return Y.null;if(Array.isArray(Q)){let J=Y.newArray();return Q.forEach((G,K)=>{let W=HO(Y,G);try{Y.setProp(J,String(K),W)}finally{W.dispose?.()}}),J}let X=Y.newObject();for(let[J,G]of Object.entries(Q)){let K=HO(Y,G);try{Y.setProp(X,J,K)}finally{K.dispose?.()}}return X}case"function":{let X=`__hostFn_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return Y.newFunction(X,(...G)=>{try{let K=G.map((Z)=>Y.dump(Z)),W=Q(...K);if(W&&typeof W.then==="function"){let Z=Y.newPromise();return W.then((H)=>{try{let $=HO(Y,H);Z.resolve($),$.dispose()}catch($){let F=KO($),V=Y.newString(`Promise resolution error: ${F}`);Z.reject(V),V.dispose()}finally{Y.runtime.executePendingJobs()}}).catch((H)=>{let $=KO(H),F=Y.newString(`Promise rejection: ${$}`);Z.reject(F),F.dispose(),Y.runtime.executePendingJobs()}),Z.handle}return HO(Y,W)}catch(K){let W=KO(K);return Y.newString(`HostFunctionError: ${W}`)}finally{G.forEach((K)=>K.dispose())}})}case"bigint":return Y.newString(Q.toString());case"symbol":return Y.newString(Q.toString());default:try{return Y.newString(String(Q))}catch{return Y.undefined}}}var Jp0=()=>{};function HD1(Y){let Q=Y.runtime.executePendingJobs(100);try{if("unwrap"in Q&&typeof Q.unwrap==="function")Q.unwrap()}finally{if("dispose"in Q&&typeof Q.dispose==="function")Q.dispose()}}async function Yr(Y,Q,X){let J=Date.now(),G=Y.resolvePromise(Q);while(!0){HD1(Y);let K=await Promise.race([G,Nh6(0).then(()=>null)]);if(K!==null)return K;if(Date.now()-J>X)throw Error(`Timed out after ${X}ms while awaiting a QuickJS promise`)}}async function Xv({tools:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"tools",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (tools). Got ${D}. Example: export default async (tools) => { /* ... */ }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}async function $D1({input:Y,code:Q,timeoutMs:X}){let W=[];try{const J=PB(W,await KD1({memoryLimitBytes:33554432,stackSizeBytes:524288}),0);const G=PB(W,J.newContext({interruptAfterMs:X}),0);const K=PB(W,ZD1(G),0);try{let F=G.evalCode(Q,"index.mjs",{strip:!0,strict:!0,type:"module"}),V=G.unwrapResult(F),q=HO(G,Y);G.setProp(G.global,"input",q);let U=G.runtime.hasPendingJob()?G.unwrapResult(await Yr(G,V,X)):V;if(U!==V)V.dispose();let z=G.getProp(U,"default"),D=G.typeof(z);if(D!=="function")return z.dispose(),U.dispose(),q.dispose(),{error:`Code must export default a function (input). Got ${D}. Example: export default (input) => { return input.items.map(i => i.name); }`,consoleLogs:K.logs};let L=G.callFunction(z,G.undefined,q);q.dispose(),z.dispose(),U.dispose();let w=G.unwrapResult(L),E=await Yr(G,w,X);w.dispose();let T=G.unwrapResult(E);if(G.runtime.hasPendingJob())HD1(G);let C=G.dump(T);return T.dispose(),{returnValue:C,consoleLogs:K.logs}}catch(F){return console.log(F),{error:KO(F),consoleLogs:K.logs}}}catch(Z){var H=Z,$=1}finally{go(W,H,$)}}var Nh6=(Y)=>new Promise((Q)=>setTimeout(Q,Y));var Gp0=k(()=>{Xp0();Jp0()});var Qr=k(()=>{Gp0()});async function Lh6(Y,Q){let X=Y.connections.map((K)=>K.connection_id),J=[];for(let K of X){let W=await Q.storage.connections.findById(K);if(W&&W.status==="active")J.push(W)}return J.map((K)=>{let W=Y.connections.find((Z)=>Z.connection_id===K.id);return{connection:K,selectedTools:W?.selected_tools??null,selectedResources:W?.selected_resources??null,selectedPrompts:W?.selected_prompts??null}})}async function Wp0(Y,Q){return(await Q.storage.connections.list(Y)).filter((J)=>J.status==="active").map((J)=>({connection:J,selectedTools:null,selectedResources:null,selectedPrompts:null}))}async function Mh6(Y,Q){let X=new Map;for(let q of Y)X.set(q.connection.id,q);let J=Y.map((q)=>q.connection),G=new Map,K=await Promise.allSettled(J.map(async(q)=>{try{let U=await Q.createMCPProxy(q);return{connection:q,proxy:U}}catch(U){return console.warn(`[code-execution] Failed to create proxy for connection ${q.id}:`,U),null}}));for(let q of K)if(q.status==="fulfilled"&&q.value)G.set(q.value.connection.id,q.value);let W=await Promise.allSettled(Array.from(G.entries()).map(async([q,U])=>{try{let D=(await U.proxy.listTools()).tools,L=X.get(q);if(L?.selectedTools&&L.selectedTools.length>0){let w=new Set(L.selectedTools);D=D.filter((E)=>w.has(E.name))}return{connectionId:q,connectionTitle:U.connection.title,tools:D}}catch(z){return console.error(`[code-execution] Failed to list tools for connection ${q}:`,z),null}})),Z=new Set,H=[],$=new Map;for(let q of W){if(q.status!=="fulfilled"||!q.value)continue;let{connectionId:U,connectionTitle:z,tools:D}=q.value;for(let L of D){if(Z.has(L.name))continue;Z.add(L.name),H.push({...L,_meta:{connectionId:U,connectionTitle:z}}),$.set(L.name,U)}}let F=async(q,U)=>{let z=$.get(q);if(!z)return{content:[{type:"text",text:`Tool not found: ${q}`}],isError:!0};let D=G.get(z);if(!D)return{content:[{type:"text",text:`Connection not found for tool: ${q}`}],isError:!0};return await D.proxy.callTool({name:q,arguments:U})},V=[];for(let[,q]of G)V.push(q.proxy.close().catch(()=>{}));return await Promise.all(V),{tools:H,callTool:F}}async function $P(Y){let Q=v0(Y),X;if(Y.connectionId){let J=await Y.storage.virtualMcps.findById(Y.connectionId,Y.organization?.id);if(J)X=await Lh6(J,Y);else X=await Wp0(Q.id,Y)}else X=await Wp0(Q.id,Y);return Mh6(X,Y)}function wh6(Y){return Y.toLowerCase().split(/[\s_\-./]+/).filter((Q)=>Q.length>=2)}function Ah6(Y,Q){let X=0,J=Q.name.toLowerCase(),G=(Q.description??"").toLowerCase(),K=(Q._meta?.connectionTitle??"").toLowerCase();for(let W of Y){if(J===W)X+=10;else if(J.includes(W))X+=3;if(G.includes(W))X+=2;if(K.includes(W))X+=1}return X}function Xr(Y,Q,X){let J=wh6(Y);if(J.length===0)return Q.slice(0,X);return Q.map((G)=>({tool:G,score:Ah6(J,G)})).filter((G)=>G.score>0).sort((G,K)=>K.score-G.score).slice(0,X).map((G)=>G.tool)}function Jr(Y,Q){let X=new Map(Q.map((G)=>[G.name,G]));return{tools:Y.map((G)=>X.get(G)).filter((G)=>G!==void 0).map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??"",inputSchema:G.inputSchema,outputSchema:G.outputSchema})),notFound:Y.filter((G)=>!X.has(G))}}async function Gr(Y,Q,X){let J=Object.fromEntries(Q.tools.map((G)=>[G.name,async(K)=>{let W=await Q.callTool(G.name,K??{});if(W.structuredContent&&typeof W.structuredContent==="object")return W.structuredContent;let Z=W.content;if(Z?.[0]?.type==="text"&&Z[0].text)try{return JSON.parse(Z[0].text)}catch{return Z[0].text}return W}]));return Xv({code:Y,tools:J,timeoutMs:X})}function Jv(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}function GB(Y){return{content:[{type:"text",text:JSON.stringify(Y,null,2)}],isError:!0}}function KF(Y){let Q=new Set(Ph6);return Y.filter((X)=>!Q.has(X.name))}var Ph6;var $O=k(()=>{Qr();Ph6=["CODE_EXECUTION_SEARCH_TOOLS","CODE_EXECUTION_DESCRIBE_TOOLS","CODE_EXECUTION_RUN_CODE"]});var FD1;var Zp0=k(()=>{F4();Qv();$O();FD1=s1({name:"CODE_EXECUTION_SEARCH_TOOLS",description:"Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling CODE_EXECUTION_DESCRIBE_TOOLS for detailed schemas.",annotations:{title:"Search Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:id0,outputSchema:ad0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q),J=Xr(Y.query,X.tools,Y.limit);return{query:Y.query,results:J.map((G)=>({name:G.name,description:G.description,connection:G._meta?.connectionTitle??""})),totalAvailable:X.tools.length}}})});var VD1;var Kp0=k(()=>{F4();Qv();$O();VD1=s1({name:"CODE_EXECUTION_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after CODE_EXECUTION_SEARCH_TOOLS to get full input/output schemas before executing code.",annotations:{title:"Describe Tools",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:rd0,outputSchema:od0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return Jr(Y.tools,X.tools)}})});var qD1;var Hp0=k(()=>{F4();Qv();$O();qD1=s1({name:"CODE_EXECUTION_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use CODE_EXECUTION_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',annotations:{title:"Run Code",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:sd0,outputSchema:td0,handler:async(Y,Q)=>{z0(Q),v0(Q),await Q.access.check();let X=await $P(Q);return await Gr(Y.code,X,Y.timeoutMs)}})});var $p0=k(()=>{Zp0();Kp0();Hp0();Qv()});var Th6,Ch6,BD1;var Fp0=k(()=>{KY();i1();F4();Sn();b$();Th6=B.object({data:PR.describe("Data for the new connection (id is auto-generated if not provided)")}),Ch6=B.object({item:W5.describe("The created connection entity")}),BD1=s1({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection in the organization",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Th6,outputSchema:Ch6,handler:async(Y,Q)=>{z0(Q);let X=v0(Q);await Q.access.check();let J=EY(Q);if(!J)throw Error("User ID required to create connection");let G={...Y.data,organization_id:X.id,created_by:J};if(G.connection_type==="VIRTUAL"){let $=zz(G.connection_url);if(!$)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let F=await Q.storage.virtualMcps.findById($);if(!F)throw Error(`Virtual MCP not found: ${$}`);if(F.organization_id!==X.id)throw Error("Virtual MCP does not belong to the current organization");G.connection_url=Dz($)}let K=await zA({id:`pending-${Date.now()}`,title:G.title,connection_type:G.connection_type,connection_url:G.connection_url,connection_token:G.connection_token,connection_headers:G.connection_headers}).catch(()=>null),W=K?.tools?.length?K.tools:null,Z=K?.scopes?.length?K.scopes:null,H=await Q.storage.connections.create({...G,tools:W,configuration_scopes:Z});return await Q.eventBus.publish(X.id,IY.SELF(X.id),{type:"connection.created",data:H}),{item:H}}})});var Rh6,Ih6,Vp0;var qp0=k(()=>{i1();MG();Rh6=bH.extend({avatar:B.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:B.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:B.string().describe("Virtual MCP ID to use for this assistant"),model:B.object({id:B.string().describe("Model ID"),connectionId:B.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),Ih6=hH("assistant",Rh6),Vp0=[...Ih6]});var Gv,HF,Up0,jh6,Sh6,zp0,kh6,vh6,_h6,yh6,fh6,bh6,Dp0,hh6,xh6,gh6,uh6,mh6,lh6,dh6,ph6,ch6,nh6,CK9,ih6,RK9,Bp0,ah6,rh6,UD1,Wv;var Wr=k(()=>{i1();_D();MG();Gv=B.lazy(()=>B.union([B.null(),B.string(),B.number(),B.boolean(),B.record(B.string(),Gv),B.array(Gv)])),HF=B.record(B.string(),B.record(B.string(),Gv)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Up0=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerOptions:HF}),jh6=B.object({type:B.literal("text"),text:B.string().describe("The text content"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),Sh6=B.string().describe("File data as URL string"),zp0=B.object({type:B.literal("file"),filename:B.string().optional().describe("Optional filename of the file"),data:Sh6,mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:HF}),kh6=B.object({type:B.literal("file"),mediaType:B.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:B.string().describe("Generated file data as base64 encoded string")}),vh6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerOptions:HF}),_h6=B.object({type:B.literal("reasoning"),text:B.string().describe("The reasoning text"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),yh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call, used to match with tool result"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:HF}),fh6=B.object({type:B.literal("tool-call"),toolCallId:B.string().describe("ID of the tool call"),toolName:B.string().describe("Name of the tool being called"),input:B.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:B.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),bh6=B.union([B.object({type:B.literal("text"),value:B.string()}),B.object({type:B.literal("json"),value:Gv}),B.object({type:B.literal("error-text"),value:B.string()}),B.object({type:B.literal("error-json"),value:Gv}),B.object({type:B.literal("content"),value:B.array(B.union([B.object({type:B.literal("text"),text:B.string().describe("Text content")}),B.object({type:B.literal("media"),data:B.string().describe("Base-64 encoded media data"),mediaType:B.string().describe("IANA media type")})]))}),B.object({type:B.literal("execution-denied"),reason:B.string().optional()}),B.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Dp0=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),output:bh6.describe("Result of the tool call"),result:B.unknown().describe("Unknown result of the tool call"),providerOptions:HF}),hh6=B.object({type:B.literal("tool-result"),toolCallId:B.string().describe("ID of the tool call that this result is associated with"),toolName:B.string().describe("Name of the tool that generated this result"),result:B.any().describe("Result of the tool call (JSON-serializable)"),isError:B.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:B.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),xh6=B.union([B.object({type:B.literal("source"),sourceType:B.literal("url"),id:B.string().describe("The ID of the source"),url:B.string().describe("The URL of the source"),title:B.string().optional().describe("The title of the source"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")}),B.object({type:B.literal("source"),sourceType:B.literal("document"),id:B.string().describe("The ID of the source"),mediaType:B.string().describe("IANA media type of the document (e.g., application/pdf)"),title:B.string().describe("The title of the document"),filename:B.string().optional().describe("Optional filename of the document"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata")})]),gh6=B.object({role:B.literal("system"),content:B.string().describe("System message content"),providerOptions:HF}),uh6=B.object({role:B.literal("user"),content:B.array(B.union([Up0,zp0])).describe("User message content parts (text or file)"),providerOptions:HF}),mh6=B.object({role:B.literal("assistant"),content:B.array(B.union([Up0,zp0,vh6,yh6,Dp0])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:HF}),lh6=B.object({role:B.literal("tool"),content:B.array(Dp0).describe("Tool message content (tool results)"),providerOptions:HF}),dh6=B.union([gh6,uh6,mh6,lh6]),ph6=B.array(dh6).describe("A list of messages forming the prompt"),ch6=B.object({prompt:ph6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:B.number().optional().describe("Maximum number of tokens to generate"),temperature:B.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:B.number().optional().describe("Nucleus sampling parameter"),topK:B.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:B.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:B.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:B.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:B.array(B.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:B.union([B.object({type:B.literal("text")}),B.object({type:B.literal("json"),schema:B.any().optional().describe("JSON schema that the generated output should conform to"),name:B.string().optional().describe("Name of output that should be generated"),description:B.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:B.array(B.any()).optional().describe("The tools that are available for the model"),toolChoice:B.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:B.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:B.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:B.any().optional().describe("Additional provider-specific options")}),nh6=B.object({content:B.array(B.union([jh6,kh6,_h6,fh6,hh6,xh6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:B.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:B.looseObject({inputTokens:B.number().optional(),outputTokens:B.number().optional(),totalTokens:B.number().optional(),reasoningTokens:B.number().optional()}).describe("Usage information for the language model call"),providerMetadata:B.any().optional().describe("Additional provider-specific metadata"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({id:B.string().optional().describe("ID for the generated response"),timestamp:B.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:B.string().optional().describe("The ID of the response model that was used"),headers:B.record(B.string(),B.string()).optional().describe("Response headers"),body:B.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:B.array(B.any()).describe("Warnings for the call, e.g. unsupported settings")}),CK9=B.object({stream:B.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:B.object({body:B.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:B.object({headers:B.record(B.string(),B.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),ih6=B.object({supportedUrls:B.record(B.string(),B.array(B.string())).describe("Supported URL patterns by media type for the provider")}),RK9=B.object({modelId:B.string().describe("The ID of the model"),logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Bp0=B.object({modelId:B.string().describe("The ID of the model"),callOptions:ch6}),ah6=bH.extend({logo:B.string().nullable(),description:B.string().nullable(),capabilities:B.array(B.string()),limits:B.object({contextWindow:B.number(),maxOutputTokens:B.number()}).nullable(),costs:B.object({input:B.number(),output:B.number()}).nullable(),provider:B.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),rh6=hH("llm",ah6,{readOnly:!0}),UD1=[{name:"LLM_METADATA",inputSchema:B.object({modelId:B.string().describe("The ID of the model")}),outputSchema:ih6},{name:"LLM_DO_STREAM",inputSchema:Bp0,streamable:!0},{name:"LLM_DO_GENERATE",inputSchema:Bp0,outputSchema:nh6},...rh6],Wv=yH(UD1)});function FP(){return!1}function Zr(Y,Q){return Y===IY.DEV_ASSETS(Q)}function VP(Y,Q){let X=B71(Q,Y),J=new Date().toISOString();return{id:X.id??IY.DEV_ASSETS(Y),title:X.title,description:X.description??null,icon:X.icon??null,app_name:X.app_name??null,app_id:X.app_id??null,organization_id:Y,created_by:"system",created_at:J,updated_at:J,connection_type:X.connection_type,connection_url:X.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata??null,tools:oh6,bindings:["OBJECT_STORAGE"],status:"active"}}var oh6;var Kr=k(()=>{mn();KY();i1();oh6=uS.map((Y)=>({name:Y.name,description:`${Y.name} operation for local file storage`,inputSchema:B.toJSONSchema(Y.inputSchema),outputSchema:B.toJSONSchema(Y.outputSchema)}))});function th6(Y){let Q=[],X=0;while(X<Y.length){let J=Y[X];if(J==="%")Q.push(".*");else if(J==="_")Q.push(".");else if(/[.*+?^${}()|[\]\\]/.test(J))Q.push("\\"+J);else Q.push(J);X++}return Q.join("")}function WB(Y){return typeof Y==="string"||typeof Y==="number"}function Hr(Y,Q){if("conditions"in Q){let{operator:Z,conditions:H}=Q;switch(Z){case"and":return H.every(($)=>Hr(Y,$));case"or":return H.some(($)=>Hr(Y,$));case"not":return!H.every(($)=>Hr(Y,$));default:return!0}}let{field:X,operator:J,value:G}=Q,K=X.join("."),W=zD1(Y,K);switch(J){case"eq":return W===G;case"gt":return WB(W)&&WB(G)&&W>G;case"gte":return WB(W)&&WB(G)&&W>=G;case"lt":return WB(W)&&WB(G)&&W<G;case"lte":return WB(W)&&WB(G)&&W<=G;case"in":return Array.isArray(G)&&G.includes(W);case"like":if(typeof W!=="string"||typeof G!=="string")return!1;if(G.length>100)return!1;let Z=th6(G);return new RegExp(`^${Z}$`,"i").test(W);case"contains":if(typeof W!=="string"||typeof G!=="string")return!1;return W.toLowerCase().includes(G.toLowerCase());default:return!0}}function zD1(Y,Q){let X=Q.split("."),J=Y;for(let G of X){if(J==null||typeof J!=="object")return;J=J[G]}return J}function eh6(Y,Q){return[...Y].sort((X,J)=>{for(let G of Q){let K=G.field.join("."),W=zD1(X,K),Z=zD1(J,K),H=0;if(W==null&&Z==null)continue;if(W==null)H=G.nulls==="first"?-1:1;else if(Z==null)H=G.nulls==="first"?1:-1;else if(typeof W==="string"&&typeof Z==="string")H=W.localeCompare(Z);else if(typeof W==="number"&&typeof Z==="number")H=W-Z;else H=String(W).localeCompare(String(Z));if(H!==0)return G.direction==="desc"?-H:H}return 0})}var sh6,Yx6,Qx6,DD1;var Op0=k(()=>{lS();qp0();MG();Wr();mn();KY();i1();F4();Kr();b$();sh6={LLM:UD1,ASSISTANTS:Vp0,OBJECT_STORAGE:uS};Yx6=uZ.extend({binding:B.union([B.object({}).passthrough(),B.string()]).optional(),include_virtual:B.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false.")}),Qx6=x$(W5),DD1=s1({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Yx6,outputSchema:Qx6,handler:async(Y,Q)=>{await Q.access.check();let X=v0(Q),J=Y.binding?typeof Y.binding==="string"?(()=>{let q=sh6[Y.binding.toUpperCase()];if(!q)throw Error(`Unknown binding: ${Y.binding}`);return q})():Y.binding:void 0,G=J?hn(J):void 0,K=await Q.storage.connections.list(X.id,{includeVirtual:Y.include_virtual??!1});if(FP()){let q=K7(),U=IY.DEV_ASSETS(X.id);if(!K.some((z)=>z.id===U)){let z=VP(X.id,q);K.unshift(z)}}let W=G?await Promise.all(K.map(async(q)=>{if(!q.tools||q.tools.length===0)return null;return G.isImplementedBy(q.tools.map((z)=>({name:z.name,inputSchema:z.inputSchema,outputSchema:z.outputSchema})))?q:null})).then((q)=>q.filter((U)=>U!==null)):K;if(Y.where)W=W.filter((q)=>Hr(q,Y.where));if(Y.orderBy&&Y.orderBy.length>0)W=eh6(W,Y.orderBy);let Z=W.length,H=Y.offset??0,$=Y.limit??100,F=W.slice(H,H+$),V=H+$<Z;return{items:F,totalCount:Z,hasMore:V}}})});var Xx6,OD1;var Np0=k(()=>{MG();F4();Kr();b$();Xx6=TS(W5),OD1=s1({name:"COLLECTION_CONNECTIONS_GET",description:"Get connection details by ID",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:ES,outputSchema:Xx6,handler:async(Y,Q)=>{let X=v0(Q);if(await Q.access.check(),FP()&&Zr(Y.id,X.id))return{item:VP(X.id,K7())};let J=await Q.storage.connections.findById(Y.id);if(!J||J.organization_id!==X.id)return{item:null};return{item:J}}})});var $r=(Y,Q)=>{if(Q===null||Q===void 0)return;let X=Y.replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),J=Q;for(let G of X){if(J===null||J===void 0||typeof J!=="object")return;J=J[G]}return J};function Lp0(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])throw Error(`Invalid scope format: ${Y}. Expected format: "KEY::SCOPE"`);return Q}function Jx6(Y){let Q=Y.split("::");if(Q.length!==2||!Q[0]||!Q[1])return null;return Q}function Gx6(Y){if(typeof Y==="object"&&Y!==null&&"value"in Y){let Q=Y.value;if(typeof Q==="string")return Q}return null}function ND1(Y,Q){let X={};if(!Y||!Q)return X;for(let J of Q){if(J==="*"){X["*"]=["*"];continue}let G=Jx6(J);if(!G)continue;let[K,W]=G,Z=$r(K,Y),H=Gx6(Z);if(H){if(!X[H])X[H]=[];X[H].push(W)}}return X}function Mp0(Y,Q){let X=ND1(Y,Q);return new Set(Object.keys(X).filter((J)=>J!=="*"))}var LD1=()=>{};import{randomBytes as Wx6}from"crypto";function wp0(){if(Zv)return Zv;let Y=process.env.MESH_JWT_SECRET??p9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(Y)Zv=new TextEncoder().encode(Y);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),Zv=new Uint8Array(Wx6(32));return Zv}async function Ap0(Y,Q="5m"){let X=wp0();return await new BG(Y).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Q).sign(X)}async function Pp0(Y){try{let Q=wp0(),{payload:X}=await JY(Y,Q);return X}catch{return}}var Zv=null;var MD1=k(()=>{UG();Kv()});async function Ep0(Y){if(!Y.refreshToken)return{success:!1,error:"No refresh token available"};if(!Y.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!Y.clientId)return{success:!1,error:"No client ID available"};try{let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y.refreshToken,client_id:Y.clientId});if(Y.clientSecret)Q.set("client_secret",Y.clientSecret);if(Y.scope)Q.set("scope",Y.scope);let X=await fetch(Y.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let G=await X.text();console.error(`[TokenRefresh] Failed to refresh token: ${X.status}`,G);try{let K=JSON.parse(G);return{success:!1,error:K.error_description||K.error||`Token refresh failed: ${X.status}`}}catch{return{success:!1,error:`Token refresh failed: ${X.status}`}}}let J=await X.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||Y.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Q){return console.error("[TokenRefresh] Error refreshing token:",Q),{success:!1,error:Q instanceof Error?Q.message:"Token refresh failed"}}}class $F{db;vault;constructor(Y,Q){this.db=Y;this.vault=Q}async get(Y){let Q=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",Y).executeTakeFirst();if(!Q)return null;return this.decryptToken(Q)}async upsert(Y){let Q=new Date().toISOString(),X=await this.vault.encrypt(Y.accessToken),J=Y.refreshToken?await this.vault.encrypt(Y.refreshToken):null,G=Y.clientSecret?await this.vault.encrypt(Y.clientSecret):null;return await this.db.transaction().execute(async(K)=>{let W=await K.selectFrom("downstream_tokens").select(["id","createdAt"]).where("connectionId","=",Y.connectionId).executeTakeFirst();if(W)return await K.updateTable("downstream_tokens").set({accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,updatedAt:Q}).where("id","=",W.id).execute(),{id:W.id,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:W.createdAt,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint};let Z=X9("dtok");return await K.insertInto("downstream_tokens").values({id:Z,connectionId:Y.connectionId,accessToken:X,refreshToken:J,scope:Y.scope,expiresAt:Y.expiresAt?.toISOString()??null,clientId:Y.clientId,clientSecret:G,tokenEndpoint:Y.tokenEndpoint,createdAt:Q,updatedAt:Q}).execute(),{id:Z,connectionId:Y.connectionId,accessToken:Y.accessToken,refreshToken:Y.refreshToken,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Q,updatedAt:Q,clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpoint:Y.tokenEndpoint}})}async delete(Y){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",Y).execute()}isExpired(Y,Q=0){if(!Y.expiresAt)return!1;let J=(Y.expiresAt instanceof Date?Y.expiresAt:new Date(Y.expiresAt)).getTime();if(Number.isNaN(J))return!0;return J-Q<Date.now()}async decryptToken(Y){let Q=await this.vault.decrypt(Y.accessToken),X=Y.refreshToken?await this.vault.decrypt(Y.refreshToken):null,J=Y.clientSecret?await this.vault.decrypt(Y.clientSecret):null;return{id:Y.id,connectionId:Y.connectionId,accessToken:Q,refreshToken:X,scope:Y.scope,expiresAt:Y.expiresAt,createdAt:Y.createdAt,updatedAt:Y.updatedAt,clientId:Y.clientId,clientSecret:J,tokenEndpoint:Y.tokenEndpoint}}}var Fr=k(()=>{$7()});async function Hv(Y,Q,X){let J=Y.id,G=ND1(Y.configuration_state,Y.configuration_scopes);console.log("[EventBus:Debug] buildRequestHeaders",{connectionId:J,superUser:X,ctxUserId:Q.auth.user?.id?.slice(0,8)??"NONE",orgId:Q.organization?.id??"NONE",createdBy:Y.created_by?.slice(0,8)??"NONE",permissionKeys:Object.keys(G),permissionDetail:Object.entries(G).map(([U,z])=>`${U}:[${z.join(",")}]`)});let K=Q.auth.user?.id??Q.auth.apiKey?.userId??(X?Y.created_by:void 0),[W,Z]=K?await Ap0({sub:K,user:{id:K},metadata:{state:Y.configuration_state??void 0,meshUrl:Q.baseUrl,connectionId:J,organizationId:Q.organization?.id},permissions:G}).then((U)=>[U,null]).catch((U)=>[null,U]):[null,Error("User ID required to issue configuration token")];if(console.log("[EventBus:Debug] token issued",{connectionId:J,hasToken:!!W,error:Z instanceof Error?Z.message:void 0,userId:K?.slice(0,8)??"NONE",orgInMetadata:Q.organization?.id??"NONE"}),Z)console.error("Failed to issue configuration token:",W);let H=Q.auth.user?.connectionId,$={...H?{"x-caller-id":H}:{},...Q.metadata.wellKnownForwardableHeaders??{},"x-request-id":Q.metadata.requestId},F=null,V=new $F(Q.db,Q.vault),q=await V.get(J);if(console.log("[EventBus:Debug] downstream token",{connectionId:J,hasCachedToken:!!q,hasRefresh:!!q?.refreshToken,expiresAt:q?.expiresAt??"NONE",hasConnectionToken:!!Y.connection_token}),q){let U=!!q.refreshToken&&!!q.tokenEndpoint;if(V.isExpired(q,U?300000:0))if(U){console.log(`[Proxy] Token expired for ${J}, attempting refresh`);let D=await Ep0(q);if(D.success&&D.accessToken)await V.upsert({connectionId:J,accessToken:D.accessToken,refreshToken:D.refreshToken??q.refreshToken,scope:D.scope??q.scope,expiresAt:D.expiresIn?new Date(Date.now()+D.expiresIn*1000):null,clientId:q.clientId,clientSecret:q.clientSecret,tokenEndpoint:q.tokenEndpoint}),F=D.accessToken,console.log(`[Proxy] Token refreshed for ${J}`);else await V.delete(J),console.error(`[Proxy] Token refresh failed for ${J}: ${D.error}`)}else await V.delete(J),console.log(`[Proxy] Token expired without refresh capability for ${J}`);else F=q.accessToken}if(!F&&Y.connection_token)F=Y.connection_token;if(F)$.Authorization=`Bearer ${F}`;if(W)$["x-mesh-token"]=W;return $}var wD1=k(()=>{LD1();MD1();Fr()});function Vr(){let Y=new Map;function Q(J,G){let K=Y.get(G);if(K)return console.log(`[ClientPool] Reusing cached client for ${G}`),K;console.log(`[ClientPool] Creating new client for ${G}`);let W=new G5({name:`outbound-client-${G}`,version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});W.onclose=()=>{Y.delete(G)};let Z=W.connect(J,{timeout:30000}).then(()=>W).catch((H)=>{throw Y.delete(G),H});return Y.set(G,Z),Z}return Object.assign(Q,{[Symbol.asyncDispose]:async()=>{let J=[];for(let[G,K]of Y)J.push(K.then((W)=>W.close()).catch((W)=>console.error(`[ClientPool] Error closing client ${G}:`,W)));await Promise.all(J),Y.clear()}})}var AD1=k(()=>{qz()});function Tp0(Y){let Q=new wS({command:Y.command,args:Y.args,env:Y.env,cwd:Y.cwd,stderr:"pipe"}),X=Y.name||Y.id,J="\x1B[2m",G="\x1B[0m";return Q.stderr?.on("data",(K)=>{let W=K.toString().trimEnd();if(W)console.error(`${W} \x1B[2m[${X}]\x1B[0m`)}),Q}var Cp0=k(()=>{vV1()});class $v{innerTransport;constructor(Y){this.innerTransport=Y}async start(){return this.innerTransport.onmessage=(Y)=>{this.handleIncomingMessage(Y)},this.innerTransport.onerror=(Y)=>{this.onerror?.(Y)},this.innerTransport.onclose=()=>{this.onclose?.()},this.innerTransport.start()}async send(Y){return this.handleOutgoingMessage(Y)}async close(){return this.innerTransport.close()}async handleOutgoingMessage(Y){return this.innerTransport.send(Y)}handleIncomingMessage(Y){this.onmessage?.(Y)}isRequest(Y){return"method"in Y&&Y.method!==void 0}isResponse(Y){return"result"in Y||"error"in Y&&!("method"in Y)}onmessage;onerror;onclose}function Fv(Y,...Q){return Q.reduce((X,J)=>J(X),Y)}var Rp0="mcp.mesh";var Ip0,PD1,FF;var Vv=k(()=>{Ip0=class Ip0 extends Error{constructor(Y){super(Y);this.name="UnauthorizedError"}};PD1=class PD1 extends Error{constructor(Y){super(Y);this.name="ForbiddenError"}};FF=class FF{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(Y,Q,X,J,G,K="self",W){this.userId=Q;this.toolName=X;this.boundAuth=J;this.role=G;this.connectionId=K;this.getToolMeta=W}[Symbol.dispose](){this._granted=!1}setToolName(Y){this.toolName=Y}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...Y){if(this._granted)return;if(this.toolName?.startsWith("MESH_PUBLIC_")){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new Ip0("Authentication required. Please provide a valid OAuth token or API key.")}let Q=Y.length>0?Y:this.toolName?[this.toolName]:[];if(Q.length===0)throw new PD1("No resources specified for access check");for(let X of Q)if(await this.checkResource(X)){this.grant();return}throw new PD1(`Access denied to: ${Q.join(", ")}`)}async checkResource(Y){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Q={};if(this.connectionId)Q[this.connectionId]=[Y];return this.boundAuth.hasPermission(Q)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let Y=await this.getToolMeta();if(!Y)return!1;let X=Y[Rp0]?.public_tool;return X===!0||X==="true"}catch{return!1}}granted(){return this._granted}}});var Zx6="mcp.mesh",qP;var jp0=k(()=>{Vv();qP=class qP extends $v{options;cachedToolsMap=null;constructor(Y,Q){super(Y);this.options=Q;if(Q.connection.tools)this.cachedToolsMap=new Map(Q.connection.tools.map((X)=>[X.name,X]))}async handleOutgoingMessage(Y){if(!this.isRequest(Y))return this.innerTransport.send(Y);let Q=Y;if(Q.method==="tools/call")await this.authorizeToolCall(Q),this.stripMetaFromArguments(Q);return this.innerTransport.send(Y)}async authorizeToolCall(Y){if(this.options.superUser)return;let X=Y.params.name,{ctx:J,connection:G}=this.options;if(this.isPublicTool(X))return;if(!J.auth.user?.id&&!J.auth.apiKey?.id)throw Error("Authentication required. Please provide a valid OAuth token or API key.");let K=async()=>{return this.cachedToolsMap?.get(X)?._meta};await new FF(J.authInstance,J.auth.user?.id??J.auth.apiKey?.userId,X,J.boundAuth,J.auth.user?.role,G.id,K).check(X)}isPublicTool(Y){if(Y.startsWith("MESH_PUBLIC_"))return!0;if(!this.cachedToolsMap)return!1;let Q=this.cachedToolsMap.get(Y);if(!Q?._meta)return!1;return Q._meta[Zx6]?.public_tool===!0}stripMetaFromArguments(Y){let Q=Y.params;if(Q.arguments&&"_meta"in Q.arguments){let{_meta:X,...J}=Q.arguments;Q.arguments=J}}}});function kp0(Y){if(!Y.isError)return;let Q=Y.content;if(!Array.isArray(Q))return;for(let X of Q)if(X&&typeof X==="object"&&"type"in X&&X.type==="text"&&"text"in X&&typeof X.text==="string")return X.text;return}function TD1(Y){if(!Y)return;let Q=Y._meta;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let X=Q.properties;if(!X||typeof X!=="object"||Array.isArray(X))return;let J={};for(let[G,K]of Object.entries(X))if(typeof K==="string")J[G]=K;return Object.keys(J).length>0?J:void 0}function CD1(Y,Q){if(!Y&&!Q)return;if(!Y)return Q;if(!Q)return Y;return{...Q,...Y}}function RD1(Y){if(Y&&typeof Y==="object"&&!Array.isArray(Y)){let Q=Y,X=Q.structuredContent;if(X&&typeof X==="object"&&!Array.isArray(X))return X;return Q}return{value:Y}}async function Kx6(Y,Q){let X=Y.body;if(!X)return{text:"",truncated:!1};let J=X.getReader(),G=new TextDecoder,K=!1,W=0,Z=[];try{while(!0){let{value:H,done:$}=await J.read();if($)break;if(H){if(W+=H.byteLength,W>Q){K=!0;let F=Q-(W-H.byteLength);if(F>0)Z.push(G.decode(H.slice(0,F),{stream:!0}));break}Z.push(G.decode(H,{stream:!0}))}}}finally{J.releaseLock()}return Z.push(G.decode()),{text:Z.join(""),truncated:K}}function Hx6(Y){if(!Y)return;let Q=Y.trimEnd().split(`
1323
+ `);for(let X=Q.length-1;X>=0&&X>=Q.length-5;X--){let J=Q[X]?.trim();if(!J)continue;try{let G=JSON.parse(J);if(G&&typeof G==="object"&&G.type==="finish"){let K={};if(G.usage)K.usage=G.usage;if(G.providerMetadata)K.providerMetadata=G.providerMetadata;if(G.finishReason)K.finishReason=G.finishReason;return Object.keys(K).length>0?K:void 0}}catch{}}return}async function ED1(Y){let{ctx:Q,enabled:X}=Y,J=Y.organizationId??Q.organization?.id;if(!X||!J)return;if(o3(Y.connectionId))return;let G=TD1(Y.request.params.arguments),K=CD1(Q.metadata.properties,G),W=Q.auth.user?.id||Q.auth.apiKey?.userId;if(W)try{let Z=await Q.storage.tags.getUserTagsInOrg(W,J);if(Z.length>0){let H=Z.map(($)=>$.name).join(",");K={...K,user_tags:H}}}catch{}await Q.storage.monitoring.log({organizationId:J,connectionId:Y.connectionId,connectionTitle:Y.connectionTitle,toolName:Y.request.params.name,input:Y.request.params.arguments??{},output:Y.output,isError:Y.isError,errorMessage:Y.errorMessage,durationMs:Y.durationMs,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:K})}function vp0(Y){let{ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K}=Y;return async(W,Z)=>{let H=Date.now();try{let $=await Z(),F=Q.organization?.id;if(X&&F){let V=$.clone();(async()=>{try{let{text:q,truncated:U}=await Kx6(V,Sp0),z=Date.now()-H,D=V.headers.get("content-type")??"",L=q;if(D.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=$.status>=400,E=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof E==="string"&&E?E:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${$.status} ${$.statusText}`.trim():U?`Response body truncated to ${Sp0} bytes`:void 0,C=RD1(L),P=Hx6(q);if(P)Object.assign(C,P);await ED1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:C,isError:w,errorMessage:T,durationMs:z})}catch(q){let U=Date.now()-H;await ED1({ctx:Q,enabled:X,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:U})}})()}return $}catch($){let F=$,V=Date.now()-H;throw await ED1({ctx:Q,enabled:X,connectionId:J,connectionTitle:G,virtualMcpId:K,request:W,output:{},isError:!0,errorMessage:F.message,durationMs:V}),$}}}var Sp0=262144;var ID1=k(()=>{KY()});var BP;var _p0=k(()=>{QS();ID1();BP=class BP extends $v{options;inflightRequests=new Map;constructor(Y,Q){super(Y);this.options=Q}async handleOutgoingMessage(Y){if(this.isRequest(Y)){let Q=Y;this.onRequestStart(Q)}return this.innerTransport.send(Y)}handleIncomingMessage(Y){if(this.isResponse(Y)){let Q=Y;this.onResponseEnd(Q)}this.onmessage?.(Y)}onRequestStart(Y){let{ctx:Q,connectionId:X}=this.options,J,G;if(Y.method==="tools/call"&&Y.params){let W=Y.params;J=W.name,G=W.arguments}let K;if(Y.method==="tools/call"&&J)K=Q.tracer.startSpan("mcp.proxy.callTool",{attributes:{"connection.id":X,"tool.name":J,"request.id":Q.metadata.requestId,"jsonrpc.id":Y.id,"jsonrpc.method":Y.method}});if(Y.id!==null&&Y.id!==void 0)this.inflightRequests.set(Y.id,{startTime:Date.now(),method:Y.method,toolName:J,toolArguments:G,span:K})}onResponseEnd(Y){if(Y.id===null||Y.id===void 0)return;let Q=this.inflightRequests.get(Y.id);if(!Q)return;let{ctx:X,connectionId:J}=this.options,{startTime:G,method:K,toolName:W,toolArguments:Z,span:H}=Q,$=Date.now()-G;if(this.inflightRequests.delete(Y.id),K!=="tools/call"||!W)return;let F="error"in Y,V=F?Y.error:Y.result,q=F?{content:[{type:"text",text:Y.error?.message||"Unknown error"}],isError:!0}:V;if(X.meter.createHistogram("connection.proxy.duration").record($,{"connection.id":J,"tool.name":W,status:F?"error":"success"}),F)X.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":J,"tool.name":W,error:Y.error?.message});else X.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":J,"tool.name":W,status:"success"});if(H){if(F&&Y.error)H.recordException(Error(Y.error.message)),H.setAttributes({error:!0,"error.code":Y.error.code,"error.message":Y.error.message});H.end()}this.logToDatabase({toolName:W,toolArguments:Z,result:q,duration:$,isError:Boolean(F)})}async logToDatabase(Y){let{ctx:Q,connectionId:X,connectionTitle:J,virtualMcpId:G}=this.options,{toolName:K,toolArguments:W,result:Z,duration:H,isError:$}=Y;if(!$n().enabled)return;let V=Q.organization?.id;if(!V)return;let q=kp0(Z),U=RD1(Z),z=TD1(W),D=CD1(Q.metadata.properties,z);try{await Q.storage.monitoring.log({organizationId:V,connectionId:X,connectionTitle:J,toolName:K,input:W??{},output:U,isError:$,errorMessage:q,durationMs:H,timestamp:new Date,userId:Q.auth.user?.id||Q.auth.apiKey?.userId||null,requestId:Q.metadata.requestId,userAgent:Q.metadata.userAgent,virtualMcpId:G,properties:D})}catch(L){console.error("[MonitoringTransport] Failed to log to database:",L)}}async close(){for(let Y of this.inflightRequests.values())if(Y.span)Y.span.setAttributes({"transport.closed":!0}),Y.span.end();return this.inflightRequests.clear(),super.close()}}});var yp0=k(()=>{jp0();_p0()});async function fp0(Y,Q,X=!1){let J=Y.id,G=Q.connectionId&&Q.connectionId!==J?Q.connectionId:void 0;switch(Y.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");let K=Y.connection_headers;if(!aK(K))throw Error("STDIO connection missing parameters");let W=Tp0({id:J,name:Y.title,command:K.command,args:K.args,env:K.envVars,cwd:K.cwd});return W=Fv(W,(Z)=>new qP(Z,{ctx:Q,connection:Y,superUser:X}),(Z)=>new BP(Z,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),$x6(W,J)}case"HTTP":case"Websocket":{if(!Y.connection_url)throw Error(`${Y.connection_type} connection missing URL`);let K=await Hv(Y,Q,X);console.log("[EventBus:Debug] outbound HTTP client",{connectionId:J,url:Y.connection_url,superUser:X,headerKeys:Object.keys(K)});let W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new bV(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}case"SSE":{if(!Y.connection_url)throw Error("SSE connection missing URL");let K=await Hv(Y,Q,X),W=Y.connection_headers;if(W&&"headers"in W)Object.assign(K,W.headers);let Z=new SD(new URL(Y.connection_url),{requestInit:{headers:K}});return Z=Fv(Z,(H)=>new qP(H,{ctx:Q,connection:Y,superUser:X}),(H)=>new BP(H,{ctx:Q,connectionId:J,connectionTitle:Y.title,virtualMcpId:G})),Q.getOrCreateClient(Z,J)}default:throw Error(`Unknown connection type: ${Y.connection_type}`)}}var $x6;var bp0=k(()=>{b$();Rn();AR();wD1();AD1();Cp0();yp0();$x6=Vr()});function ZB(Y){if(!Y?._meta)return!1;return typeof Y._meta["mcp.mesh"]?.["tool.fn"]==="string"}function gp0(Y){return Y._meta["mcp.mesh"]["tool.fn"]}function qv(Y,Q,X,J){return{id:Y,name:Q.name,description:Q.description,inputSchema:Q.inputSchema,outputSchema:Q.outputSchema,annotations:Q.annotations,code:Q._meta["mcp.mesh"]["tool.fn"],connection_dependencies:Q._meta.connectionDependencies??[],created_at:X,updated_at:J}}var jD1,pH9,iH,hp0,xp0;var VF=k(()=>{i1();jD1=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),pH9=B.object({"tool.fn":B.string().describe("JavaScript ES module code that exports a default async function")}),iH=B.object({id:B.string().describe("Unique identifier for the virtual tool (auto-generated)"),name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description of what the tool does"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema defining the tool's output (optional)"),annotations:jD1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).describe("Connection IDs that this tool depends on (specified by the creator)"),created_at:B.string().describe("When the virtual tool was created"),updated_at:B.string().describe("When the virtual tool was last updated")}),hp0=B.object({name:B.string().min(1).max(255).describe("Tool name (must be unique within the Virtual MCP)"),description:B.string().optional().describe("Human-readable description"),inputSchema:B.record(B.string(),B.unknown()).describe("JSON Schema defining the tool's input parameters"),outputSchema:B.record(B.string(),B.unknown()).optional().describe("JSON Schema for output"),annotations:jD1.optional().describe("MCP tool annotations"),code:B.string().describe("JavaScript ES module code. Must export default an async function: export default async (tools, args) => { ... }"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Creates indirect aggregations to prevent deletion of referenced connections.")}),xp0=B.object({name:B.string().min(1).max(255).optional().describe("New tool name"),description:B.string().nullable().optional().describe("New description (null to clear)"),inputSchema:B.record(B.string(),B.unknown()).optional().describe("New input schema"),outputSchema:B.record(B.string(),B.unknown()).nullable().optional().describe("New output schema (null to clear)"),annotations:jD1.nullable().optional().describe("New annotations (null to clear)"),code:B.string().optional().describe("New JavaScript code"),connection_dependencies:B.array(B.string()).optional().describe("Connection IDs that this tool depends on. Replaces existing dependencies if provided.")})});function FO(Y){return(Q)=>{if(Q instanceof u0&&Q.code===o0.MethodNotFound)return Y;throw Q}}var SD1=k(()=>{vQ()});class up0{factory;promise=null;constructor(Y){this.factory=Y}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(Y,Q){return this.getOrCreatePromise().then(Y,Q)}catch(Y){return this.getOrCreatePromise().catch(Y)}finally(Y){return this.getOrCreatePromise().finally(Y)}}function UP(Y){return new up0(Y)}function Fx6(Y,Q,X){let J=new G5({name:`lazy-${Y.id}`,version:"1.0.0"},{capabilities:{}}),G=null;function K(){if(!G)G=_5(Y,Q,X).then((H)=>{if(Y.connection_type==="HTTP"||Y.connection_type==="SSE"||Y.connection_type==="Websocket")return VO(H,Y.id,Y,Q,{superUser:X});return H});return G}if(Y.connection_type!=="VIRTUAL"&&Array.isArray(Y.tools)&&Y.tools.length>0)J.listTools=async()=>({tools:Y.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,outputSchema:H.outputSchema,annotations:H.annotations,_meta:H._meta}))});else J.listTools=async()=>{return(await K()).listTools()};J.callTool=async(H,$,F)=>{return(await K()).callTool(H,$,F)},J.listResources=async()=>{return(await K()).listResources()},J.listPrompts=async()=>{return(await K()).listPrompts()},J.getPrompt=async(H,$)=>{return(await K()).getPrompt(H,$)},J.readResource=async(H,$)=>{return(await K()).readResource(H,$)},J.callStreamableTool=async(H,$)=>{let F=await K();if("callStreamableTool"in F&&typeof F.callStreamableTool==="function")return F.callStreamableTool(H,$);let V=await F.callTool({name:H,arguments:$});return new Response(JSON.stringify(V),{headers:{"Content-Type":"application/json"}})};let Z=J.close.bind(J);return J.close=async()=>{if(G){let H=await G.catch(()=>null);if(H)await H.close().catch(()=>{})}await Z()},J}function Vx6(Y,Q,X=!1){let J=new Map;for(let G of Y)J.set(G.id,Fx6(G,Q,X));return J}async function mp0(Y){let Q=[];for(let[,X]of Y)Q.push(X.close().catch(()=>{}));await Promise.all(Q)}var zP;var kD1=k(()=>{DP();SD1();qz();Qr();VF();zP=class zP extends G5{options;ctx;_cachedTools;_cachedResources;_cachedPrompts;_clients;_connections;_selectionMap;constructor(Y,Q){super({name:"virtual-mcp-passthrough",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});this.options=Y;this.ctx=Q;this._selectionMap=new Map;for(let X of Y.virtualMcp.connections)this._selectionMap.set(X.connection_id,X);this._connections=new Map;for(let X of Y.connections)this._connections.set(X.id,X);this._clients=Vx6(this.options.connections,this.ctx,this.options.superUser),this._cachedTools=UP(()=>this.loadToolsCache()),this._cachedResources=UP(()=>this.loadCache("resources")),this._cachedPrompts=UP(()=>this.loadCache("prompts"))}async loadToolsCache(){let Y=this._clients,Q=await Promise.all(Array.from(Y.entries()).map(async([W,Z])=>{try{let H=await Z.listTools().then((F)=>F.tools),$=this._selectionMap.get(W);if($?.selected_tools?.length){let F=new Set($.selected_tools);H=H.filter((V)=>F.has(V.name))}return{connectionId:W,data:H}}catch(H){return console.error(`[PassthroughClient] Failed to load tools for connection ${W}:`,H),null}})),X=[],J=new Map,G=new Map,K=this.options.virtualTools??[];for(let W of K){if(J.has(W.name))continue;let Z={name:W.name,description:W.description,inputSchema:W.inputSchema,outputSchema:W.outputSchema,annotations:W.annotations,_meta:{connectionId:this.options.virtualMcp.id??"__VIRTUAL__",connectionTitle:this.options.virtualMcp.title}};X.push(Z),J.set(W.name,"__VIRTUAL__"),G.set(W.name,W)}for(let W of Q){if(!W)continue;let{connectionId:Z,data:H}=W,F=this._connections.get(Z)?.title??"";for(let V of H){let q=V.name;if(J.has(q))continue;let U={...V,_meta:{connectionId:Z,connectionTitle:F,...V?._meta}};X.push(U),J.set(q,Z)}}return{data:X,mappings:J,virtualTools:G}}async loadCache(Y){let Q=this._clients,X=await Promise.all(Array.from(Q.entries()).map(async([K,W])=>{try{let Z=Y==="resources"?await W.listResources().catch(FO({resources:[]})).then((F)=>F.resources):await W.listPrompts().catch(FO({prompts:[]})).then((F)=>F.prompts),H=this._selectionMap.get(K),$=Y==="resources"?"selected_resources":"selected_prompts";if(H?.[$]?.length){let F=new Set(H[$]);return{connectionId:K,data:Z.filter((V)=>F.has(V.name))}}return{connectionId:K,data:Z}}catch(Z){return console.error(`[PassthroughClient] Failed to load cache for connection ${K}:`,Z),null}})),J=[],G=new Map;for(let K of X){if(!K)continue;let{connectionId:W,data:Z}=K,$=this._connections.get(W)?.title??"";for(let F of Z){let V=F.name??F.uri;if(G.has(V))continue;let q={...F,_meta:{connectionId:W,connectionTitle:$,...F?._meta}};J.push(q),G.set(V,W)}}return{data:J,mappings:G}}async listTools(){return{tools:(await this._cachedTools).data}}async callTool(Y){let Q=await this._cachedTools,X=this._clients,J=Q.mappings.get(Y.name);if(!J)return{content:[{type:"text",text:`Tool not found: ${Y.name}`}],isError:!0};if(J==="__VIRTUAL__")return this.executeVirtualTool(Y.name,Y.arguments??{},Q,X);let G=X.get(J);if(!G)return{content:[{type:"text",text:`Connection not found for tool: ${Y.name}`}],isError:!0};return await G.callTool({name:Y.name,arguments:Y.arguments??{}})}async executeVirtualTool(Y,Q,X,J){let G=X.virtualTools.get(Y);if(!G)return{content:[{type:"text",text:`Virtual tool not found: ${Y}`}],isError:!0};let K=gp0(G),W={};for(let[Z,H]of X.mappings){if(H==="__VIRTUAL__")continue;let $=J.get(H);if(!$)continue;W[Z]=async(F)=>{let V=await $.callTool({name:Z,arguments:F});if(V.structuredContent&&typeof V.structuredContent==="object")return V.structuredContent;let q=V.content;if(q?.[0]?.type==="text"&&q[0].text)try{return JSON.parse(q[0].text)}catch{return q[0].text}return V}}try{let H=`
1324
1324
  const __virtualToolFn = ${K.replace(/^\s*export\s+default\s+/,"").trim()};
1325
1325
  export default async (tools) => {
1326
1326
  const args = ${JSON.stringify(Q)};
@@ -1387,7 +1387,7 @@ Example input: "How do I connect to a database?"
1387
1387
  Example output: Database Connection Setup
1388
1388
 
1389
1389
  Example input: "What tools are available?"
1390
- Example output: Available Tools Overview`;function Tr(Y){return typeof Y==="string"?Y:Y.toISOString()}class Nv{db;constructor(Y){this.db=Y}async create(Y){let Q=Y.id??X9("thrd"),X=new Date().toISOString();if(!Y.organization_id)throw Error("organization_id is required");if(!Y.created_by)throw Error("created_by is required");if(!Y.title)Y.title=Er;let J={id:Q,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,status:Y.status??"completed",created_at:X,updated_at:X,created_by:Y.created_by,updated_by:Y.updated_by??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let Q=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return Q?this.threadFromDbRow(Q):null}async update(Y,Q){let J={updated_at:new Date().toISOString()};if(Q.title!==void 0)J.title=Q.title;if(Q.description!==void 0)J.description=Q.description;if(Q.updated_by!==void 0)J.updated_by=Q.updated_by;if(Q.hidden!==void 0)J.hidden=Q.hidden;if(Q.status!==void 0)J.status=Q.status;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,Q,X){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(Q)J=J.where("created_by","=",Q);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(Q)G=G.where("created_by","=",Q);if(X?.limit)J=J.limit(X.limit);if(X?.offset)J=J.offset(X.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let Q=new Date().toISOString(),X=Y[0]?.thread_id;if(!X)throw Error("thread_id is required when creating multiple messages");let J=new Map;for(let Z of Y){let H=J.get(Z.id);if(H&&H.thread_id!==Z.thread_id)throw Error(`Duplicate message id "${Z.id}" with conflicting thread_ids: "${H.thread_id}" vs "${Z.thread_id}"`);J.set(Z.id,Z)}let G=[...J.values()],K=G.find((Z)=>Z.thread_id!==X);if(K)throw Error(`All messages must target the same thread. Expected thread_id "${X}", but message "${K.id}" has thread_id "${K.thread_id}"`);let W=G.map((Z)=>({id:Z.id,thread_id:X,metadata:Z.metadata?JSON.stringify(Z.metadata):null,parts:JSON.stringify(Z.parts),role:Z.role,created_at:Z.created_at??Q,updated_at:Q}));await this.db.transaction().execute(async(Z)=>{await Z.insertInto("thread_messages").values(W).onConflict((H)=>H.column("id").doUpdateSet(($)=>({metadata:$.ref("excluded.metadata"),parts:$.ref("excluded.parts"),role:$.ref("excluded.role"),updated_at:$.ref("excluded.updated_at")}))).execute(),await Z.updateTable("threads").set({updated_at:Q}).where("id","=",X).execute()})}async listMessages(Y,Q){let X=Q?.sort??"asc",J=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at",X).orderBy("id",X),G=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{messages:K.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,status:Y.status,created_at:Tr(Y.created_at),updated_at:Tr(Y.updated_at),created_by:Y.created_by,updated_by:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let Q,X;try{Q=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),Q=void 0}try{X=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),X=[]}return{id:Y.id,thread_id:Y.thread_id,metadata:Q,parts:X,role:Y.role,created_at:Tr(Y.created_at),updated_at:Tr(Y.updated_at)}}}AD1();function og6(Y){if(!Y)return;try{let Q=JSON.parse(Y);if(typeof Q!=="object"||Q===null||Array.isArray(Q))return;let X={};for(let[J,G]of Object.entries(Q))if(typeof G==="string")X[J]=G;return Object.keys(X).length>0?X:void 0}catch{return}}function sg6(Y,Q){for(let[X,J]of Object.entries(Q)){let G=Y[X];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function tg6(Y){let{auth:Q,headers:X,role:J,permissions:G,userId:K}=Y,W=Q.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&aO1.includes(J))return!0;if(G)return sg6(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:X,body:{permission:Z}}))?.success===!0)return!0;let $={};for(let V of Object.keys(Z))$[V]=["*"];return(await W({headers:X,body:{permission:$}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return Q.api.createOrganization({headers:X,body:Z})},update:async(Z)=>{return Q.api.updateOrganization({headers:X,body:Z})},delete:async(Z)=>{await Q.api.deleteOrganization({headers:X,body:{organizationId:Z}})},get:async(Z)=>{return Q.api.getFullOrganization({headers:X,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return Q.api.listOrganizations({headers:X,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return Q.api.addMember({headers:X,body:Z})},removeMember:async(Z)=>{await Q.api.removeMember({headers:X,body:Z})},listMembers:async(Z)=>{return Q.api.listMembers({headers:X,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return Q.api.updateMemberRole({headers:X,body:Z})}},apiKey:{create:async(Z)=>{return Q.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return Q.api.listApiKeys({headers:X})},update:async(Z)=>{return Q.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await Q.api.deleteApiKey({headers:X,body:{keyId:Z}})}}}}async function eg6(Y,Q,X){if(aO1.includes(X))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Q).where("role","=",X).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function Yu6(Y,Q,X,J=Ji0){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>Q.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>X.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),$=H?.role,F=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,V;if(H&&$)V=await J.measure("auth_fetch_role_permissions",()=>eg6(X,H.organizationId,$));return{user:{id:Z,role:$},role:$,permissions:V,organization:F}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>Pp0(K));if(W){let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role;return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>Q.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,$,F=W.key.userId;if(F&&Z?.id)$=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:$},role:$,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=new Headers(Y.headers);K.delete("Authorization");let W=await J.measure("auth_get_session",()=>Q.api.getSession({headers:K}));if(W){let Z,H;if(W.session.activeOrganizationId){let $=await J.measure("auth_get_full_organization",()=>Q.api.getFullOrganization({headers:K}).catch(()=>null));if($)Z={id:$.id,slug:$.slug,name:$.name},H=$.members?.find((V)=>V.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:H},role:H,organization:Z}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}var Xi0,UF={set:(Y)=>{Xi0=Y},create:async(Y,Q)=>{return await Xi0(Y,Q)}},Ji0={measure:async(Y,Q)=>{return await Q()}},Qu6=["x-hub-signature-256"];async function Gi0(Y){let Q=new RD(Y.encryption.key),X={connections:new zS(Y.db,Q),organizationSettings:new QN1(Y.db),monitoring:new eO1(Y.db,Y.databaseType),monitoringDashboards:new YN1(Y.db),virtualMcps:new sO1(Y.db),users:new GN1(Y.db),threads:new Nv(Y.db),tags:new JN1(Y.db),projects:new DS(Y.db),projectPluginConfigs:new XN1(Y.db)};return async(J,G)=>{let K=G?.timings??Ji0,W=Vr(),Z=J?.headers.get("x-caller-id")??void 0,H=J?await Yu6(J,Y.auth,Y.db,K):{user:void 0},$=tg6({auth:Y.auth,headers:J?.headers??new Headers,role:H.role,permissions:H.permissions,userId:H.user?.id}),F={user:H.user};if(H.apiKeyId)F.apiKey={id:H.apiKeyId,name:"",userId:""};let V=H.organization,q=J?process.env.BASE_URL??`${new URL(J.url).origin}`:K7(),U=new FF(Y.auth,F.user?.id,void 0,$,H.role,"self"),z={timings:K,auth:F,connectionId:Z,organization:V,storage:X,vault:Q,authInstance:Y.auth,boundAuth:$,access:U,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(Qu6.map((D)=>[D,J?.headers.get(D)??null]).filter(([D,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:og6(J?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(D)=>{return await an0(D,z)},getOrCreateClient:W};return z}}Pn();class Wi0{db;constructor(Y){this.db=Y}async publishEvent(Y){let Q=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Q,updatedAt:Q}}async subscribe(Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)Q=Q.where("publisher","=",Y.publisher);else Q=Q.where("publisher","is",null);if(Y.filter)Q=Q.where("filter","=",Y.filter);else Q=Q.where("filter","is",null);let X=await Q.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,Q){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(Q)X=X.where("connection_id","=",Q);return(await X.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,Q){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((X)=>X.or([X("publisher","is",null),X("publisher","=",Y.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Y,Q,X){if(Q.length===0)return;let J=new Date().toISOString(),G=X??null,K=Q.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let Q=new Date().toISOString(),X;try{X=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];X=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",X).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let Q=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Q}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,Q,X=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=X)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),$=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"pending",next_retry_at:$}).where("id","=",K).execute()}}}async updateEventStatus(Y){let Q=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(Q.length===0)return;let X=Q.every((K)=>K.status==="delivered"),J=Q.some((K)=>K.status==="failed"),G=Q.some((K)=>K.status==="pending"||K.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,Q){let X=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async findActiveCronEvent(Y,Q,X,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",Q).where("source","=",X).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,Q,X){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",Q).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,Q){if(Y.length===0)return;let X=new Date(Date.now()+Q).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Y).execute()}async ackDelivery(Y,Q,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",Q).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",Q))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:Q,connectionId:X,subscriptions:J}=Y,G=(w,E)=>{return`${w}::${E??""}`},K=await this.listSubscriptions(Q,X),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),$=[],F=[],V=[],q=0;for(let[w,E]of Z){let T=W.get(w);if(!T)$.push({id:crypto.randomUUID(),organization_id:Q,connection_id:X,event_type:E.eventType,publisher:E.publisher??null,filter:E.filter??null,enabled:1,created_at:H,updated_at:H});else{let C=T.filter??null,P=E.filter??null;if(C!==P)F.push({id:T.id,filter:P});else q++}}for(let[w,E]of W)if(!Z.has(w))V.push(E.id);if($.length>0)await this.db.insertInto("event_subscriptions").values($).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let U=$.length,z=F.length,D=V.length,L=await this.listSubscriptions(Q,X);return{created:U,updated:z,deleted:D,unchanged:q,subscriptions:L}}}function Zi0(Y){return new Wi0(Y)}function hJ(Y,Q,X,J,G,K,W,Z){return hJ.fromTZ(hJ.tp(Y,Q,X,J,G,K,W),Z)}hJ.fromTZISO=(Y,Q,X)=>hJ.fromTZ(Xu6(Y,Q),X);hJ.fromTZ=function(Y,Q){let X=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=FN1(Y.tz,X),G=new Date(X.getTime()-J),K=FN1(Y.tz,G);if(K-J===0)return G;{let W=new Date(X.getTime()-K),Z=FN1(Y.tz,W);if(Z-K===0)return W;if(!Q&&Z-K>0)return W;if(Q)throw Error("Invalid date passed to fromTZ()");return G}};hJ.toTZ=function(Y,Q){let X=Y.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),J=new Date(X);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Q}};hJ.tp=(Y,Q,X,J,G,K,W)=>({y:Y,m:Q,d:X,h:J,i:G,s:K,tz:W});function FN1(Y,Q=new Date){let X=Q.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${X}`)}function Xu6(Y,Q){let X=new Date(Date.parse(Y));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?hJ.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):hJ.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),Q)}hJ.minitz=hJ;var VN1=32,Mv=31|VN1,Fi0=[1,2,4,8,16],Ki0=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,Q){this.pattern=Y,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new fW(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",Q.getSeconds().toString()),Y[1]=Y[1].replace("?",Q.getMinutes().toString()),Y[2]=Y[2].replace("?",Q.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",Q.getDate().toString())),Y[4]=Y[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,Mv),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,Q,X,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(Q===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return G.fill(J);let W=Q.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],X,J);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,Y,X,J):Q.indexOf("-")!==-1?this.handleRange(Q,Y,X,J):Q.indexOf("/")!==-1?this.handleStepping(Q,Y,X,J):Q!==""&&this.handleNumber(Q,Y,X,J)}throwAtIllegalCharacters(Y){for(let Q=0;Q<Y.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+Y[Q]+") contains illegal characters.")}handleNumber(Y,Q,X,J){let G=this.extractNth(Y,Q),K=parseInt(G[0],10)+X;if(isNaN(K))throw TypeError("CronPattern: "+Q+" is not a number: '"+Y+"'");this.setPart(Q,K,G[1]||J)}setPart(Y,Q,X){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,X);return}if(Y==="second"||Y==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+Q);this[Y][Q]=X}handleRangeWithStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,$=parseInt(W,10)+X,F=parseInt(Z,10)+X,V=parseInt(H,10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if($>F)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let q=$;q<=F;q+=V)this.setPart(Q,q,G[1]||J)}extractNth(Y,Q){let X=Y,J;if(X.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=X.split("#")[1],X=X.split("#")[0]}return[X,J]}handleRange(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+X,Z=parseInt(K[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(Q,H,G[1]||J)}handleStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+X);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=W;H<this[Q].length;H+=Z)this.setPart(Q,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let Q=Y.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|VN1;else if(Q===Mv)this.dayOfWeek[Y]=Mv;else if(Q<6&&Q>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|Fi0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Hi0=[31,28,31,30,31,30,31,31,30,31,30,31],zF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],fW=class Y{tz;ms;second;minute;hour;day;month;year;constructor(Q,X){if(this.tz=X,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof Y)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,X,J,G){let K=new Date(Date.UTC(Q,X,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(Q,X,Z)).getUTCDay()===K&&W++;if(G&Mv&&Fi0[W-1]&G)return!0;if(G&VN1){let Z=new Date(Date.UTC(Q,X+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(Q,X,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let X=hJ.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>Hi0[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let X=hJ.fromTZISO(Q);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(hJ.fromTZISO(Q,this.tz))}findNext(Q,X,J,G){let K=this[X],W;J.lastDayOfMonth&&(this.month!==1?W=Hi0[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[X]+G;H<J[X].length;H++){let $=J[X][H];if(X==="day"&&J.lastDayOfMonth&&H-G==W&&($=1),X==="day"&&!J.starDOW){let F=J.dayOfWeek[(Z+(H-G-1))%7];if(F&&F&Mv)F=this.isNthWeekdayOfMonth(this.year,this.month,H-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Q.legacyMode&&!J.starDOM?$=$||F:$=$&&F}if($)return this[X]=H-G,K!==this[X]?2:1}return 3}recurse(Q,X,J){let G=this.findNext(X,zF[J][0],Q,zF[J][2]);if(G>1){let K=J+1;for(;K<zF.length;)this[zF[K][0]]=-zF[K][2],K++;if(G===3)return this[zF[J][1]]++,this[zF[J][0]]=-zF[J][2],this.apply(),this.recurse(Q,X,0);if(this.apply())return this.recurse(Q,X,J-1)}return J+=1,J>=zF.length?this:this.year>=3000?null:this.recurse(Q,X,J)}increment(Q,X,J){return this.second+=X.interval!==void 0&&X.interval>1&&J?X.interval:1,this.ms=0,this.apply(),this.recurse(Q,X,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):hJ.fromTZ(hJ.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Ju6(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new fW(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new fW(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function Lv(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function Gu6(Y){return Lv(Y)}function Wu6(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var $i0=30000,Cr=[],Rr=class{name;options;_states;fn;constructor(Y,Q,X){let J,G;if(Lv(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(Lv(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Ju6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Ki0("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new fW(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Ki0(Y,this.options.timezone),this.name){if(Cr.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Cr.push(this)}return G!==void 0&&Gu6(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let Q=this._next(Y);return Q?Q.getDate(!1):null}nextRuns(Y,Q){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let X=[],J=Q||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)X.push(J);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),Q=!this._states.paused,X=this.fn!==void 0,J=!this._states.kill;return Q&&X&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let Q=this._next(Y);return Q?Y instanceof fW||Y instanceof Date?Q.getTime()-Y.getTime():Q.getTime()-new fW(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Cr.indexOf(this);Y>=0&&Cr.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let Q=this.msToNext(),X=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||X===null?this:(Q>$i0&&(Q=$i0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),Q),this._states.currentTimeout&&this.options.unref&&Wu6(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new fW(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){Lv(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new fW(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let Q=new Date,X=!this._states.paused&&Q.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;X&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&J&&Lv(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let Q=!!(Y||this._states.currentRun),X=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,Q]=this._calculatePreviousRun(Y,Q),X=!Y),Y=new fW(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new fW(Y,this.options.timezone||this.options.utcOffset);return!X&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,Q){let X=new fW(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=X.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=X.getTime();)J=new fW(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Q=!0}return J===null&&(J=void 0),[J,Q]}};class wv{localEmit=null;async start(Y){this.localEmit=Y}broadcast(Y,Q){this.localEmit?.(Y,Q)}async stop(){this.localEmit=null}}var Vi0=50,qi0=500;class Bi0{listeners=new Map;totalCount=0;strategy=new wv;started=!1;async start(Y){if(this.started){if(!Y)return;await this.stop()}if(Y)this.strategy=Y;await this.strategy.start((Q,X)=>this.localEmit(Q,X)),this.started=!0}async stop(){if(!this.started)return;await this.strategy.stop(),this.started=!1}add(Y){if(this.totalCount>=qi0)return console.warn(`[SSEHub] Total connection limit reached (${qi0})`),null;let Q=this.listeners.get(Y.organizationId);if(!Q)Q=new Map,this.listeners.set(Y.organizationId,Q);if(Q.size>=Vi0)return console.warn(`[SSEHub] Per-org connection limit reached for ${Y.organizationId} (${Vi0})`),null;return Q.set(Y.id,Y),this.totalCount++,Y.id}remove(Y,Q){let X=this.listeners.get(Y);if(!X)return;if(X.delete(Q)){if(this.totalCount--,X.size===0)this.listeners.delete(Y)}}emit(Y,Q){this.strategy.broadcast(Y,Q)}countForOrg(Y){return this.listeners.get(Y)?.size??0}get count(){return this.totalCount}localEmit(Y,Q){let X=this.listeners.get(Y);if(!X||X.size===0)return;for(let J of X.values()){if(J.typePatterns&&!Zu6(Q.type,J.typePatterns))continue;try{J.push(Q)}catch{this.remove(Y,J.id)}}}}function Zu6(Y,Q){for(let X of Q){if(X===Y)return!0;if(X.endsWith(".*")){let J=X.slice(0,-1);if(Y.startsWith(J))return!0}}return!1}var xJ=new Bi0;function Ui0(Y){return{id:Y.id,type:Y.type,source:Y.source,subject:Y.subject,data:Y.data?Ku6(Y.data):void 0,time:Y.time}}function Ku6(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}var Ir={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};ta();lS();function Hu6(Y){return Y.endsWith("_self")}function $u6(Y){return Y.slice(0,-5)}function zi0(){return async(Y,Q)=>{try{if(Hu6(Y)&&YD1()){let W=$u6(Y),Z=await UF.create();if(await kd0(Q,{organizationId:W,connectionId:Y,publish:async(F,V,q,U)=>{await Z.eventBus.publish(W,Y,{type:F,subject:V,data:q,deliverAt:U?.deliverAt})},createMCPProxy:async(F)=>{let V=await HN1(F,Z);return{callTool:async(q,U,z)=>{let D=await V.callTool(q,U,z);return{content:D.content,structuredContent:D.structuredContent,isError:D.isError}},close:()=>V.close()}}}))return{success:!0}}let X=await UF.create(),J=await HN1(Y,X),K=await mV1.forClient(zO(J)).ON_EVENTS({events:Q});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(X){let J=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}function Di0(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function Fu6(Y){let Q=new Map;for(let J of Y){let G=J.subscription.connectionId,K=Q.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(Di0(J.event))}else Q.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[Di0(J.event)],seenEventIds:new Set([J.event.id])})}let X=new Map;for(let[J,G]of Q)X.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return X}class qN1{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;constructor(Y,Q){this.storage=Y;this.notifySubscriber=zi0(),this.config={...Ir,...Q}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let Q=Fu6(Y),X=new Set;await Promise.allSettled(Array.from(Q.entries()).map(async([J,G])=>{try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))X.add(K.event.id)}));for(let J of X)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,Q){let X=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=Q.results?.[W.id];if(H)if(H.success)X.push(Z);else if(H.retryAfter&&H.retryAfter>0){let $=J.get(H.retryAfter)||[];$.push(Z),J.set(H.retryAfter,$)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(Q.success)X.push(Z);else if(Q.retryAfter&&Q.retryAfter>0){let $=J.get(Q.retryAfter)||[];$.push(Z),J.set(Q.retryAfter,$)}else G.push({deliveryId:Z,error:Q.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let $=W.get(H)||[];$.push(Z),W.set(H,$)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let X=new Rr(Y.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=X.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(Q){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,Q)}}}class BN1{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new qN1(this.storage,Y.config)}async publish(Y,Q,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(X.cron){try{let F=new Rr(X.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch($){throw Error(`Invalid cron expression: ${$ instanceof Error?$.message:String($)}`)}let H=await this.storage.findActiveCronEvent(Y,X.type,Q,X.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:X.type,source:Q,subject:X.subject,time:K,data:X.data,cron:X.cron});xJ.emit(Y,Ui0(W));let Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=X.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map(($)=>$.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch(($)=>{console.warn("[EventBus] Notify failed (non-critical):",$)})}return W}async subscribe(Y,Q){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:Q.connectionId,publisher:Q.publisher,eventType:Q.eventType,filter:Q.filter})}async unsubscribe(Y,Q){return this.storage.unsubscribe(Q,Y)}async listSubscriptions(Y,Q){return this.storage.listSubscriptions(Y,Q)}async getSubscription(Y,Q){return this.storage.getSubscription(Q,Y)}async getEvent(Y,Q){return this.storage.getEvent(Q,Y)}async cancelEvent(Y,Q,X){return this.storage.cancelEvent(Q,Y,X)}async ackEvent(Y,Q,X){return this.storage.ackDelivery(Q,Y,X)}async syncSubscriptions(Y,Q){return this.storage.syncSubscriptions({organizationId:Y,...Q})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}class UN1{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){let Q=this.options.getConnection();if(!Q||this.sub)return;this.onNotify=Y,this.sub=Q.subscribe("mesh.events.notify"),(async()=>{for await(let X of this.sub)this.onNotify?.()})().catch((X)=>{console.error("[NatsNotify] Subscription error:",X)}),console.log("[NatsNotify] Started, subscribed to","mesh.events.notify")}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null,console.log("[NatsNotify] Stopped")}async notify(Y){let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.events.notify",this.encoder.encode(Y))}catch(X){console.warn("[NatsNotify] Publish failed (non-critical):",X)}}}class zN1{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){this.localEmit=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.sse.broadcast");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(typeof G?.originId!=="string"||typeof G?.organizationId!=="string"||typeof G?.event?.id!=="string"||typeof G?.event?.type!=="string")continue;if(G.originId===this.originId)continue;this.localEmit?.(G.organizationId,G.event)}catch{}})().catch((J)=>{console.error("[NatsSSEBroadcast] Subscription error:",J)}),console.log("[NatsSSEBroadcast] Started, subscribed to","mesh.sse.broadcast")}broadcast(Y,Q){this.localEmit?.(Y,Q);let X=this.options.getConnection();if(!X)return;let J={originId:this.originId,organizationId:Y,event:Q};try{X.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(J)))}catch(G){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",G)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null,console.log("[NatsSSEBroadcast] Stopped")}}function DN1(...Y){return{async start(Q){await Promise.all(Y.map((X)=>X.start(Q)))},async stop(){await Promise.all(Y.map((Q)=>Q.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(Q){await Promise.all(Y.map((X)=>X.notify(Q).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class ON1{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Vu6}from"kysely";var LP="mesh_events";class NN1{db;pool;listenClient=null;onNotify=null;constructor(Y,Q){this.db=Y;this.pool=Q}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Q)=>{if(Q.channel===LP&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Q)=>{console.error("[PostgresNotify] Connection error:",Q),this.cleanup()}),await this.listenClient.query(`LISTEN ${LP}`),console.log("[PostgresNotify] Started LISTEN on",LP)}catch(Q){console.error("[PostgresNotify] Failed to start LISTEN:",Q),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${LP}`),console.log("[PostgresNotify] Stopped LISTEN on",LP)}catch{}this.cleanup()}}async notify(Y){try{await Vu6`SELECT pg_notify(${LP}, ${Y})`.execute(this.db)}catch(Q){console.warn("[PostgresNotify] Failed to send NOTIFY:",Q)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function qu6(Y){let Q=process.env.NOTIFY_STRATEGY;if(Q==="nats"||Q==="postgres"||Q==="polling")return Q;if(process.env.NATS_URL)return"nats";if(Y.type==="postgres")return"postgres";return"polling"}function Oi0(Y,Q,X){let J=Zi0(Y.db),G=Q?.pollIntervalMs??Ir.pollIntervalMs,K=qu6(Y),W=new ON1(G),Z=process.env.NATS_URL,H;switch(K){case"nats":{if(!Z)throw Error("[EventBus] NOTIFY_STRATEGY=nats requires NATS_URL to be set");let F=(()=>{try{return new URL(Z).host}catch{return"unknown"}})();if(!X){console.warn(`[EventBus] NATS unavailable (${F}), falling back to polling`),H=W;break}console.log(`[EventBus] Using NATS notify strategy (${F})`),H=DN1(W,new UN1({getConnection:()=>X.getConnection()}));break}case"postgres":{if(Y.type!=="postgres"){console.warn("[EventBus] NOTIFY_STRATEGY=postgres requires a PostgreSQL database, falling back to polling"),H=W;break}console.log("[EventBus] Using PostgreSQL LISTEN/NOTIFY strategy"),H=DN1(W,new NN1(Y.db,Y.pool));break}case"polling":default:console.log("[EventBus] Using polling notify strategy"),H=W}let $=Z&&X?new zN1({getConnection:()=>X.getConnection()}):new wv;if(xJ.start($).catch((F)=>{console.error("[SSEHub] Failed to start broadcast strategy:",F)}),Z&&X)console.log("[SSEHub] Using NATS SSE broadcast (cross-pod)");else console.log("[SSEHub] Using local SSE broadcast (single-pod)");return new BN1({storage:J,config:Q,notifyStrategy:H})}FN();Kv();var Ni0={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var Li0=new JQ;Li0.get("/config",async(Y)=>{try{let Q=Object.keys(p9.socialProviders??{}),X=Q.length>0,J=Q.map((W)=>({name:W,icon:Ni0[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:p9.emailAndPassword?.enabled??!1},magicLink:{enabled:p9.magicLinkConfig?.enabled??!1},resetPassword:{enabled:oO1},socialProviders:{enabled:X,providers:J},sso:p9.ssoConfig?{enabled:!0,providerId:p9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(Q){let X=Q instanceof Error?Q.message:"Failed to load auth config";return Y.json({success:!1,error:X},500)}});var Mi0=Li0;DP();Uv();KY();rZ();vQ();rZ();rZ();i1();Qr();function wi0(Y){let{toolOutputMap:Q}=Y;return _J({description:"The input is a string. Dont make assumptions about its format; prefer using regexes and string manipulation to extract the desired information. You may call this tool multiple times to extract the desired information.",inputExamples:[{input:{tool_call_id:"tool_call_id_1",code:"export default (input) => { return input.match(/[a-z]/g); }"}},{input:{tool_call_id:"tool_call_id_2",code:"export default (input) => { return input.split(' ').map(word => word.length); }"}}],inputSchema:m8(B.object({tool_call_id:B.string(),code:B.string().min(1).describe("JavaScript code to transform the tool output. The code must be an ES module: `export default (input) => { ... }`")})),execute:async({tool_call_id:X,code:J})=>{if(!Q.has(X))throw Error(`Tool output not found for tool call id: ${X}`);let G=Q.get(X),K=await $D1({input:G,code:J,timeoutMs:5000}),W=LN1({return:K.returnValue});if(W>4000)throw Error(`Tool call ${X} output is too long to display (${W} tokens), reduce or truncate the output`);return{result:K.returnValue,error:K.error,consoleLogs:K.consoleLogs}}})}var Bu6=4,Uu6=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g;function zu6(Y){if(!Y)return 0;let Q=Y.match(Uu6)?.length??0,X=Y.length-Q;return Math.ceil(X/Bu6)+Math.ceil(Q*1.5)}function LN1(Y){let Q=typeof Y==="string"?Y:JSON.stringify(Y);return zu6(Q)}function jr(Y,Q){if(Y==="yolo")return!1;if(Y==="none")return!0;return Q!==!0}function Sr(Y){let Q=Y.get("meshContext").organization;if(!Q)throw Error("Organization context is required");if((Q.slug??Q.id)!==Y.req.param("org"))throw Error("Organization mismatch");return Q}async function Av(Y,Q,X,J="none",G){let K=!G?.disableOutputTruncation,Z=(await Y.listTools()).tools.map((H)=>{let{name:$,title:F,description:V,inputSchema:q,annotations:U}=H;return[$,_J({title:F??$,description:V,inputSchema:IW(q),outputSchema:void 0,needsApproval:jr(J,U?.readOnlyHint),execute:async(z,D)=>{let L=performance.now();try{return await Y.callTool({name:H.name,arguments:z},dK,{signal:D.abortSignal,timeout:nn0})}finally{if(X){let w=performance.now()-L;X.write({type:"data-tool-metadata",id:D.toolCallId,data:{annotations:H.annotations,latencyMs:w}})}}},toModelOutput:async({output:z,toolCallId:D})=>{if(K){let w=LN1(z.structuredContent??z.content);if(w>4000)return Q.set(D,JSON.stringify(z.structuredContent??z.content)),{type:"text",value:`Tool call ${D} output is too long to display (${w} tokens), use the read_tool_output tool`}}if(z.isError)return{type:"error-text",value:z.content.map((E)=>E.type==="text"?E.text:null).filter(Boolean).join(`
1390
+ Example output: Available Tools Overview`;function Tr(Y){return typeof Y==="string"?Y:Y.toISOString()}class Nv{db;constructor(Y){this.db=Y}async create(Y){let Q=Y.id??X9("thrd"),X=new Date().toISOString();if(!Y.organization_id)throw Error("organization_id is required");if(!Y.created_by)throw Error("created_by is required");if(!Y.title)Y.title=Er;let J={id:Q,organization_id:Y.organization_id,title:Y.title,description:Y.description??null,status:Y.status??"completed",created_at:X,updated_at:X,created_by:Y.created_by,updated_by:Y.updated_by??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(Y){let Q=await this.db.selectFrom("threads").selectAll().where("id","=",Y).executeTakeFirst();return Q?this.threadFromDbRow(Q):null}async update(Y,Q){let J={updated_at:new Date().toISOString()};if(Q.title!==void 0)J.title=Q.title;if(Q.description!==void 0)J.description=Q.description;if(Q.updated_by!==void 0)J.updated_by=Q.updated_by;if(Q.hidden!==void 0)J.hidden=Q.hidden;if(Q.status!==void 0)J.status=Q.status;await this.db.updateTable("threads").set(J).where("id","=",Y).execute();let G=await this.get(Y);if(!G)throw Error("Thread not found after update");return G}async delete(Y){await this.db.deleteFrom("threads").where("id","=",Y).execute()}async list(Y,Q,X){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",Y).where("hidden","=",!1).orderBy("updated_at","desc");if(Q)J=J.where("created_by","=",Q);let G=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",Y).where("hidden","=",!1);if(Q)G=G.where("created_by","=",Q);if(X?.limit)J=J.limit(X.limit);if(X?.offset)J=J.offset(X.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:K.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async saveMessages(Y){let Q=new Date().toISOString(),X=Y[0]?.thread_id;if(!X)throw Error("thread_id is required when creating multiple messages");let J=new Map;for(let Z of Y){let H=J.get(Z.id);if(H&&H.thread_id!==Z.thread_id)throw Error(`Duplicate message id "${Z.id}" with conflicting thread_ids: "${H.thread_id}" vs "${Z.thread_id}"`);J.set(Z.id,Z)}let G=[...J.values()],K=G.find((Z)=>Z.thread_id!==X);if(K)throw Error(`All messages must target the same thread. Expected thread_id "${X}", but message "${K.id}" has thread_id "${K.thread_id}"`);let W=G.map((Z)=>({id:Z.id,thread_id:X,metadata:Z.metadata?JSON.stringify(Z.metadata):null,parts:JSON.stringify(Z.parts),role:Z.role,created_at:Z.created_at??Q,updated_at:Q}));await this.db.transaction().execute(async(Z)=>{await Z.insertInto("thread_messages").values(W).onConflict((H)=>H.column("id").doUpdateSet(($)=>({metadata:$.ref("excluded.metadata"),parts:$.ref("excluded.parts"),role:$.ref("excluded.role"),updated_at:$.ref("excluded.updated_at")}))).execute(),await Z.updateTable("threads").set({updated_at:Q}).where("id","=",X).execute()})}async listMessages(Y,Q){let X=Q?.sort??"asc",J=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",Y).orderBy("created_at",X).orderBy("id",X),G=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[K,W]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{messages:K.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(Y){return{id:Y.id,organization_id:Y.organization_id,title:Y.title,description:Y.description,status:Y.status,created_at:Tr(Y.created_at),updated_at:Tr(Y.updated_at),created_by:Y.created_by,updated_by:Y.updated_by,hidden:!!Y.hidden}}messageFromDbRow(Y){let Q,X;try{Q=Y.metadata?JSON.parse(Y.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${Y.id}:`,Y.metadata,J),Q=void 0}try{X=typeof Y.parts==="string"?JSON.parse(Y.parts):Y.parts}catch(J){console.error(`Failed to parse parts for message ${Y.id}:`,Y.parts,J),X=[]}return{id:Y.id,thread_id:Y.thread_id,metadata:Q,parts:X,role:Y.role,created_at:Tr(Y.created_at),updated_at:Tr(Y.updated_at)}}}AD1();function og6(Y){if(!Y)return;try{let Q=JSON.parse(Y);if(typeof Q!=="object"||Q===null||Array.isArray(Q))return;let X={};for(let[J,G]of Object.entries(Q))if(typeof G==="string")X[J]=G;return Object.keys(X).length>0?X:void 0}catch{return}}function sg6(Y,Q){for(let[X,J]of Object.entries(Q)){let G=Y[X];if(!G||G.length===0){let K=Y["*"];if(!K||K.length===0)return!1;if(K.includes("*"))continue;for(let W of J)if(!K.includes(W))return!1;continue}if(G.includes("*"))continue;for(let K of J)if(!G.includes(K))return!1}return!0}function tg6(Y){let{auth:Q,headers:X,role:J,permissions:G,userId:K}=Y,W=Q.api.hasPermission;return{hasPermission:async(Z)=>{if(J&&aO1.includes(J))return!0;if(G)return sg6(G,Z);if(!W)return console.error("[Auth] hasPermission API not available"),!1;try{if((await W({headers:X,body:{permission:Z}}))?.success===!0)return!0;let $={};for(let V of Object.keys(Z))$[V]=["*"];return(await W({headers:X,body:{permission:$}}))?.success===!0}catch(H){return console.error("[Auth] Permission check failed:",H),!1}},organization:{create:async(Z)=>{return Q.api.createOrganization({headers:X,body:Z})},update:async(Z)=>{return Q.api.updateOrganization({headers:X,body:Z})},delete:async(Z)=>{await Q.api.deleteOrganization({headers:X,body:{organizationId:Z}})},get:async(Z)=>{return Q.api.getFullOrganization({headers:X,query:Z?{organizationId:Z}:void 0})},list:async(Z)=>{return Q.api.listOrganizations({headers:X,query:Z?{userId:Z}:void 0})},addMember:async(Z)=>{return Q.api.addMember({headers:X,body:Z})},removeMember:async(Z)=>{await Q.api.removeMember({headers:X,body:Z})},listMembers:async(Z)=>{return Q.api.listMembers({headers:X,query:Z?{organizationId:Z.organizationId,limit:Z.limit,offset:Z.offset}:void 0})},updateMemberRole:async(Z)=>{return Q.api.updateMemberRole({headers:X,body:Z})}},apiKey:{create:async(Z)=>{return Q.api.createApiKey({body:{...Z,userId:K}})},list:async()=>{return Q.api.listApiKeys({headers:X})},update:async(Z)=>{return Q.api.updateApiKey({body:{...Z,userId:K}})},delete:async(Z)=>{await Q.api.deleteApiKey({headers:X,body:{keyId:Z}})}}}}async function eg6(Y,Q,X){if(aO1.includes(X))return;let J=await Y.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Q).where("role","=",X).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${X}`);return}}async function Yu6(Y,Q,X,J=Ji0){let G=Y.headers.get("Authorization");try{let K=new Headers(Y.headers);K.set("X-MCP-Session-Auth","true");let W=await J.measure("auth_get_mcp_session",()=>Q.api.getMcpSession({headers:K}));if(W){let Z=W.userId,H=await J.measure("auth_query_membership",()=>X.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Z).executeTakeFirst()),$=H?.role,F=H?{id:H.orgId,slug:H.orgSlug,name:H.orgName}:void 0,V;if(H&&$)V=await J.measure("auth_fetch_role_permissions",()=>eg6(X,H.organizationId,$));return{user:{id:Z,role:$},role:$,permissions:V,organization:F}}}catch(K){console.error("[Auth] OAuth session check failed:",K)}if(G?.startsWith("Bearer ")){let K=G.replace("Bearer ","").trim();try{let W=await J.measure("auth_verify_mesh_jwt",()=>Pp0(K));if(W){console.log("[EventBus:Debug] mesh JWT verified",{sub:W.sub?.slice(0,8)??"NONE",organizationId:W.metadata?.organizationId??"NONE",connectionId:W.metadata?.connectionId??"NONE",permissionKeys:Object.keys(W.permissions??{})});let Z,H=W.metadata?.organizationId;if(W.sub&&H)Z=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",W.sub).where("member.organizationId","=",H).executeTakeFirst()))?.role,console.log("[EventBus:Debug] JWT membership result",{organizationId:H,role:Z??"NO_ROLE"});else console.log("[EventBus:Debug] JWT membership SKIPPED",{hasSub:!!W.sub,hasOrgId:!!H});return{user:{id:W.sub,connectionId:W.metadata?.connectionId,role:Z},role:Z,permissions:W.permissions,organization:W.metadata?.organizationId?{id:W.metadata?.organizationId}:void 0}}}catch{}try{let W=await J.measure("auth_verify_api_key",()=>Q.api.verifyApiKey({body:{key:K}}));if(W?.valid&&W.key){let Z=W.key.metadata?.organization,H=W.key.permissions,$,F=W.key.userId;if(F&&Z?.id)$=(await J.measure("auth_query_membership",()=>X.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",Z.id).executeTakeFirst()))?.role;return{apiKeyId:W.key.id,user:{id:W.key.userId,role:$},role:$,permissions:H,organization:Z?{id:Z.id,slug:Z.slug,name:Z.name}:void 0}}}catch(W){console.error("[Auth] API key check failed:",W)}}try{let K=new Headers(Y.headers);K.delete("Authorization");let W=await J.measure("auth_get_session",()=>Q.api.getSession({headers:K}));if(W){let Z,H;if(W.session.activeOrganizationId){let $=await J.measure("auth_get_full_organization",()=>Q.api.getFullOrganization({headers:K}).catch(()=>null));if($)Z={id:$.id,slug:$.slug,name:$.name},H=$.members?.find((V)=>V.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:H},role:H,organization:Z}}}catch(K){let W=K;console.error("[Auth] Session check failed:",JSON.stringify({message:W.message,body:W.body,stack:W.stack},null,2))}return{user:void 0}}var Xi0,UF={set:(Y)=>{Xi0=Y},create:async(Y,Q)=>{return await Xi0(Y,Q)}},Ji0={measure:async(Y,Q)=>{return await Q()}},Qu6=["x-hub-signature-256"];async function Gi0(Y){let Q=new RD(Y.encryption.key),X={connections:new zS(Y.db,Q),organizationSettings:new QN1(Y.db),monitoring:new eO1(Y.db,Y.databaseType),monitoringDashboards:new YN1(Y.db),virtualMcps:new sO1(Y.db),users:new GN1(Y.db),threads:new Nv(Y.db),tags:new JN1(Y.db),projects:new DS(Y.db),projectPluginConfigs:new XN1(Y.db)};return async(J,G)=>{let K=G?.timings??Ji0,W=Vr(),Z=J?.headers.get("x-caller-id")??void 0,H=J?await Yu6(J,Y.auth,Y.db,K):{user:void 0},$=tg6({auth:Y.auth,headers:J?.headers??new Headers,role:H.role,permissions:H.permissions,userId:H.user?.id}),F={user:H.user};if(H.apiKeyId)F.apiKey={id:H.apiKeyId,name:"",userId:""};let V=H.organization,q=J?process.env.BASE_URL??`${new URL(J.url).origin}`:K7(),U=new FF(Y.auth,F.user?.id,void 0,$,H.role,"self"),z={timings:K,auth:F,connectionId:Z,organization:V,storage:X,vault:Q,authInstance:Y.auth,boundAuth:$,access:U,db:Y.db,tracer:Y.observability.tracer,meter:Y.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,wellKnownForwardableHeaders:Object.fromEntries(Qu6.map((D)=>[D,J?.headers.get(D)??null]).filter(([D,L])=>L!==null)),userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:og6(J?.headers.get("x-mesh-properties"))},eventBus:Y.eventBus,createMCPProxy:async(D)=>{return await an0(D,z)},getOrCreateClient:W};return z}}Pn();class Wi0{db;constructor(Y){this.db=Y}async publishEvent(Y){let Q=new Date().toISOString();return await this.db.insertInto("events").values({id:Y.id,organization_id:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data?JSON.stringify(Y.data):null,cron:Y.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Q,updated_at:Q}).execute(),{id:Y.id,organizationId:Y.organizationId,type:Y.type,source:Y.source,specversion:"1.0",subject:Y.subject??null,time:Y.time,datacontenttype:Y.datacontenttype??"application/json",dataschema:Y.dataschema??null,data:Y.data??null,cron:Y.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Q,updatedAt:Q}}async subscribe(Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("connection_id","=",Y.connectionId).where("event_type","=",Y.eventType);if(Y.publisher)Q=Q.where("publisher","=",Y.publisher);else Q=Q.where("publisher","is",null);if(Y.filter)Q=Q.where("filter","=",Y.filter);else Q=Q.where("filter","is",null);let X=await Q.executeTakeFirst();if(X)return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:Y.id,organization_id:Y.organizationId,connection_id:Y.connectionId,publisher:Y.publisher??null,event_type:Y.eventType,filter:Y.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:Y.id,organizationId:Y.organizationId,connectionId:Y.connectionId,publisher:Y.publisher??null,eventType:Y.eventType,filter:Y.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(Y,Q){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",Y).where("organization_id","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(Y,Q){let X=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y);if(Q)X=X.where("connection_id","=",Q);return(await X.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(Y,Q){let X=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}}async getMatchingSubscriptions(Y){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",Y.organizationId).where("enabled","=",1).where("event_type","=",Y.type).where((X)=>X.or([X("publisher","is",null),X("publisher","=",Y.source)])).execute()).map((X)=>({id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,publisher:X.publisher,eventType:X.event_type,filter:X.filter,enabled:X.enabled===1,createdAt:X.created_at,updatedAt:X.updated_at}))}async createDeliveries(Y,Q,X){if(Q.length===0)return;let J=new Date().toISOString(),G=X??null,K=Q.map((W)=>({id:crypto.randomUUID(),event_id:Y,subscription_id:W,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(K).execute()}async claimPendingDeliveries(Y){let Q=new Date().toISOString(),X;try{X=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(K)=>K.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y)).where("status","=","pending").returning(["id"]).execute()).map((K)=>K.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((K)=>K.or([K("d.next_retry_at","is",null),K("d.next_retry_at","<=",Q)])).orderBy("d.created_at","asc").limit(Y).execute();if(G.length===0)return[];X=G.map((K)=>K.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",X).where("status","=","pending").execute()}if(X.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",X).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(Y){if(Y.length===0)return;let Q=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Q}).where("id","in",Y).execute()}async markDeliveriesFailed(Y,Q,X=20,J=1000,G=3600000){if(Y.length===0)return;for(let K of Y){let W=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",K).executeTakeFirst();if(!W)continue;let Z=W.attempts+1;if(Z>=X)await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"failed",next_retry_at:null}).where("id","=",K).execute();else{let H=Math.min(J*Math.pow(2,Z-1),G),$=new Date(Date.now()+H).toISOString();await this.db.updateTable("event_deliveries").set({attempts:Z,last_error:Q,status:"pending",next_retry_at:$}).where("id","=",K).execute()}}}async updateEventStatus(Y){let Q=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",Y).execute();if(Q.length===0)return;let X=Q.every((K)=>K.status==="delivered"),J=Q.some((K)=>K.status==="failed"),G=Q.some((K)=>K.status==="pending"||K.status==="processing");if(X)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",Y).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",Y).execute()}async resetStuckDeliveries(){let Y=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(Y.numUpdatedRows??0)}async getEvent(Y,Q){let X=await this.db.selectFrom("events").selectAll().where("id","=",Y).where("organization_id","=",Q).executeTakeFirst();if(!X)return null;return{id:X.id,organizationId:X.organization_id,type:X.type,source:X.source,specversion:X.specversion,subject:X.subject,time:X.time,datacontenttype:X.datacontenttype,dataschema:X.dataschema,data:X.data?JSON.parse(X.data):null,cron:X.cron,status:X.status,attempts:X.attempts,lastError:X.last_error,nextRetryAt:X.next_retry_at,createdAt:X.created_at,updatedAt:X.updated_at}}async findActiveCronEvent(Y,Q,X,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",Y).where("type","=",Q).where("source","=",X).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(Y,Q,X){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",Y).where("organization_id","=",Q).where("source","=",X).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",Y).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(Y,Q){if(Y.length===0)return;let X=new Date(Date.now()+Q).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:X}).where("id","in",Y).execute()}async ackDelivery(Y,Q,X){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",Y).where("organization_id","=",Q).executeTakeFirst())return{success:!1};let K=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",Y).where("status","in",["pending","processing"]).where((W)=>W.exists(W.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",X).where("event_subscriptions.organization_id","=",Q))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(K)await this.updateEventStatus(Y);return{success:K}}async syncSubscriptions(Y){let{organizationId:Q,connectionId:X,subscriptions:J}=Y,G=(w,E)=>{return`${w}::${E??""}`},K=await this.listSubscriptions(Q,X),W=new Map;for(let w of K)W.set(G(w.eventType,w.publisher),w);let Z=new Map;for(let w of J)Z.set(G(w.eventType,w.publisher),w);let H=new Date().toISOString(),$=[],F=[],V=[],q=0;for(let[w,E]of Z){let T=W.get(w);if(!T)$.push({id:crypto.randomUUID(),organization_id:Q,connection_id:X,event_type:E.eventType,publisher:E.publisher??null,filter:E.filter??null,enabled:1,created_at:H,updated_at:H});else{let C=T.filter??null,P=E.filter??null;if(C!==P)F.push({id:T.id,filter:P});else q++}}for(let[w,E]of W)if(!Z.has(w))V.push(E.id);if($.length>0)await this.db.insertInto("event_subscriptions").values($).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:H}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let U=$.length,z=F.length,D=V.length,L=await this.listSubscriptions(Q,X);return{created:U,updated:z,deleted:D,unchanged:q,subscriptions:L}}}function Zi0(Y){return new Wi0(Y)}function hJ(Y,Q,X,J,G,K,W,Z){return hJ.fromTZ(hJ.tp(Y,Q,X,J,G,K,W),Z)}hJ.fromTZISO=(Y,Q,X)=>hJ.fromTZ(Xu6(Y,Q),X);hJ.fromTZ=function(Y,Q){let X=new Date(Date.UTC(Y.y,Y.m-1,Y.d,Y.h,Y.i,Y.s)),J=FN1(Y.tz,X),G=new Date(X.getTime()-J),K=FN1(Y.tz,G);if(K-J===0)return G;{let W=new Date(X.getTime()-K),Z=FN1(Y.tz,W);if(Z-K===0)return W;if(!Q&&Z-K>0)return W;if(Q)throw Error("Invalid date passed to fromTZ()");return G}};hJ.toTZ=function(Y,Q){let X=Y.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),J=new Date(X);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Q}};hJ.tp=(Y,Q,X,J,G,K,W)=>({y:Y,m:Q,d:X,h:J,i:G,s:K,tz:W});function FN1(Y,Q=new Date){let X=Q.toLocaleString("en-US",{timeZone:Y,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${X}`)}function Xu6(Y,Q){let X=new Date(Date.parse(Y));if(isNaN(X))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=Y.substring(9);return Y.includes("Z")||J.includes("-")||J.includes("+")?hJ.tp(X.getUTCFullYear(),X.getUTCMonth()+1,X.getUTCDate(),X.getUTCHours(),X.getUTCMinutes(),X.getUTCSeconds(),"Etc/UTC"):hJ.tp(X.getFullYear(),X.getMonth()+1,X.getDate(),X.getHours(),X.getMinutes(),X.getSeconds(),Q)}hJ.minitz=hJ;var VN1=32,Mv=31|VN1,Fi0=[1,2,4,8,16],Ki0=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(Y,Q){this.pattern=Y,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let Y=this.pattern.replace(/\s+/g," ").split(" ");if(Y.length<5||Y.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(Y.length===5&&Y.unshift("0"),Y[3].indexOf("L")>=0&&(Y[3]=Y[3].replace("L",""),this.lastDayOfMonth=!0),Y[3]=="*"&&(this.starDOM=!0),Y[4].length>=3&&(Y[4]=this.replaceAlphaMonths(Y[4])),Y[5].length>=3&&(Y[5]=this.replaceAlphaDays(Y[5])),Y[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new fW(new Date,this.timezone).getDate(!0);Y[0]=Y[0].replace("?",Q.getSeconds().toString()),Y[1]=Y[1].replace("?",Q.getMinutes().toString()),Y[2]=Y[2].replace("?",Q.getHours().toString()),this.starDOM||(Y[3]=Y[3].replace("?",Q.getDate().toString())),Y[4]=Y[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(Y[5]=Y[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(Y),this.partToArray("second",Y[0],0,1),this.partToArray("minute",Y[1],0,1),this.partToArray("hour",Y[2],0,1),this.partToArray("day",Y[3],-1,1),this.partToArray("month",Y[4],-1,1),this.partToArray("dayOfWeek",Y[5],0,Mv),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(Y,Q,X,J){let G=this[Y],K=Y==="day"&&this.lastDayOfMonth;if(Q===""&&!K)throw TypeError("CronPattern: configuration entry "+Y+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return G.fill(J);let W=Q.split(",");if(W.length>1)for(let Z=0;Z<W.length;Z++)this.partToArray(Y,W[Z],X,J);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,Y,X,J):Q.indexOf("-")!==-1?this.handleRange(Q,Y,X,J):Q.indexOf("/")!==-1?this.handleStepping(Q,Y,X,J):Q!==""&&this.handleNumber(Q,Y,X,J)}throwAtIllegalCharacters(Y){for(let Q=0;Q<Y.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(Y[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+Y[Q]+") contains illegal characters.")}handleNumber(Y,Q,X,J){let G=this.extractNth(Y,Q),K=parseInt(G[0],10)+X;if(isNaN(K))throw TypeError("CronPattern: "+Q+" is not a number: '"+Y+"'");this.setPart(Q,K,G[1]||J)}setPart(Y,Q,X){if(!Object.prototype.hasOwnProperty.call(this,Y))throw TypeError("CronPattern: Invalid part specified: "+Y);if(Y==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,X);return}if(Y==="second"||Y==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+Y+": "+Q)}else if(Y==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+Y+": "+Q);this[Y][Q]=X}handleRangeWithStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(K===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+Y+"'");let[,W,Z,H]=K,$=parseInt(W,10)+X,F=parseInt(Z,10)+X,V=parseInt(H,10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if($>F)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let q=$;q<=F;q+=V)this.setPart(Q,q,G[1]||J)}extractNth(Y,Q){let X=Y,J;if(X.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=X.split("#")[1],X=X.split("#")[0]}return[X,J]}handleRange(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("-");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+Y+"'");let W=parseInt(K[0],10)+X,Z=parseInt(K[1],10)+X;if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(W>Z)throw TypeError("CronPattern: From value is larger than to value: '"+Y+"'");for(let H=W;H<=Z;H++)this.setPart(Q,H,G[1]||J)}handleStepping(Y,Q,X,J){let G=this.extractNth(Y,Q),K=G[0].split("/");if(K.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+Y+"'");K[0]===""&&(K[0]="*");let W=0;K[0]!=="*"&&(W=parseInt(K[0],10)+X);let Z=parseInt(K[1],10);if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=W;H<this[Q].length;H+=Z)this.setPart(Q,H,G[1]||J)}replaceAlphaDays(Y){return Y.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(Y){return Y.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(Y){let Q=Y.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":Y}setNthWeekdayOfMonth(Y,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[Y]=this.dayOfWeek[Y]|VN1;else if(Q===Mv)this.dayOfWeek[Y]=Mv;else if(Q<6&&Q>0)this.dayOfWeek[Y]=this.dayOfWeek[Y]|Fi0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Hi0=[31,28,31,30,31,30,31,31,30,31,30,31],zF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],fW=class Y{tz;ms;second;minute;hour;day;month;year;constructor(Q,X){if(this.tz=X,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof Y)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,X,J,G){let K=new Date(Date.UTC(Q,X,J)).getUTCDay(),W=0;for(let Z=1;Z<=J;Z++)new Date(Date.UTC(Q,X,Z)).getUTCDay()===K&&W++;if(G&Mv&&Fi0[W-1]&G)return!0;if(G&VN1){let Z=new Date(Date.UTC(Q,X+1,0)).getUTCDate();for(let H=J+1;H<=Z;H++)if(new Date(Date.UTC(Q,X,H)).getUTCDay()===K)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let X=hJ.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=X.s,this.minute=X.i,this.hour=X.h,this.day=X.d,this.month=X.m-1,this.year=X.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>Hi0[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let X=hJ.fromTZISO(Q);this.ms=X.getUTCMilliseconds(),this.second=X.getUTCSeconds(),this.minute=X.getUTCMinutes(),this.hour=X.getUTCHours(),this.day=X.getUTCDate(),this.month=X.getUTCMonth(),this.year=X.getUTCFullYear(),this.apply()}else return this.fromDate(hJ.fromTZISO(Q,this.tz))}findNext(Q,X,J,G){let K=this[X],W;J.lastDayOfMonth&&(this.month!==1?W=Hi0[this.month]:W=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Z=!J.starDOW&&X=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[X]+G;H<J[X].length;H++){let $=J[X][H];if(X==="day"&&J.lastDayOfMonth&&H-G==W&&($=1),X==="day"&&!J.starDOW){let F=J.dayOfWeek[(Z+(H-G-1))%7];if(F&&F&Mv)F=this.isNthWeekdayOfMonth(this.year,this.month,H-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Q.legacyMode&&!J.starDOM?$=$||F:$=$&&F}if($)return this[X]=H-G,K!==this[X]?2:1}return 3}recurse(Q,X,J){let G=this.findNext(X,zF[J][0],Q,zF[J][2]);if(G>1){let K=J+1;for(;K<zF.length;)this[zF[K][0]]=-zF[K][2],K++;if(G===3)return this[zF[J][1]]++,this[zF[J][0]]=-zF[J][2],this.apply(),this.recurse(Q,X,0);if(this.apply())return this.recurse(Q,X,J-1)}return J+=1,J>=zF.length?this:this.year>=3000?null:this.recurse(Q,X,J)}increment(Q,X,J){return this.second+=X.interval!==void 0&&X.interval>1&&J?X.interval:1,this.ms=0,this.apply(),this.recurse(Q,X,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):hJ.fromTZ(hJ.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Ju6(Y){if(Y===void 0&&(Y={}),delete Y.name,Y.legacyMode=Y.legacyMode===void 0?!0:Y.legacyMode,Y.paused=Y.paused===void 0?!1:Y.paused,Y.maxRuns=Y.maxRuns===void 0?1/0:Y.maxRuns,Y.catch=Y.catch===void 0?!1:Y.catch,Y.interval=Y.interval===void 0?0:parseInt(Y.interval.toString(),10),Y.utcOffset=Y.utcOffset===void 0?void 0:parseInt(Y.utcOffset.toString(),10),Y.unref=Y.unref===void 0?!1:Y.unref,Y.startAt&&(Y.startAt=new fW(Y.startAt,Y.timezone)),Y.stopAt&&(Y.stopAt=new fW(Y.stopAt,Y.timezone)),Y.interval!==null){if(isNaN(Y.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(Y.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(Y.utcOffset!==void 0){if(isNaN(Y.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(Y.utcOffset<-870||Y.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(Y.utcOffset!==void 0&&Y.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(Y.unref!==!0&&Y.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return Y}function Lv(Y){return Object.prototype.toString.call(Y)==="[object Function]"||typeof Y=="function"||Y instanceof Function}function Gu6(Y){return Lv(Y)}function Wu6(Y){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(Y):Y&&typeof Y.unref<"u"&&Y.unref()}var $i0=30000,Cr=[],Rr=class{name;options;_states;fn;constructor(Y,Q,X){let J,G;if(Lv(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(Lv(X))G=X;else if(typeof X=="object")J=X;else if(X!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=Ju6(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new Ki0("* * * * *")},Y&&(Y instanceof Date||typeof Y=="string"&&Y.indexOf(":")>0)?this._states.once=new fW(Y,this.options.timezone||this.options.utcOffset):this._states.pattern=new Ki0(Y,this.options.timezone),this.name){if(Cr.find((K)=>K.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Cr.push(this)}return G!==void 0&&Gu6(G)&&(this.fn=G,this.schedule()),this}nextRun(Y){let Q=this._next(Y);return Q?Q.getDate(!1):null}nextRuns(Y,Q){this._states.maxRuns!==void 0&&Y>this._states.maxRuns&&(Y=this._states.maxRuns);let X=[],J=Q||this._states.currentRun||void 0;for(;Y--&&(J=this.nextRun(J));)X.push(J);return X}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let Y=this.nextRun(this._states.currentRun),Q=!this._states.paused,X=this.fn!==void 0,J=!this._states.kill;return Q&&X&&J&&Y!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(Y){let Q=this._next(Y);return Q?Y instanceof fW||Y instanceof Date?Q.getTime()-Y.getTime():Q.getTime()-new fW(Y).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let Y=Cr.indexOf(this);Y>=0&&Cr.splice(Y,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(Y){if(Y&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");Y&&(this.fn=Y);let Q=this.msToNext(),X=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||X===null?this:(Q>$i0&&(Q=$i0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(X),Q),this._states.currentTimeout&&this.options.unref&&Wu6(this._states.currentTimeout),this)}async _trigger(Y){if(this._states.blocking=!0,this._states.currentRun=new fW(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){Lv(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new fW(Y,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(Y){let Q=new Date,X=!this._states.paused&&Q.getTime()>=Y.getTime(),J=this._states.blocking&&this.options.protect;X&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):X&&J&&Lv(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(Y){let Q=!!(Y||this._states.currentRun),X=!1;!Y&&this.options.startAt&&this.options.interval&&([Y,Q]=this._calculatePreviousRun(Y,Q),X=!Y),Y=new fW(Y,this.options.timezone||this.options.utcOffset),this.options.startAt&&Y&&Y.getTime()<this.options.startAt.getTime()&&(Y=this.options.startAt);let J=this._states.once||new fW(Y,this.options.timezone||this.options.utcOffset);return!X&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=Y.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(Y,Q){let X=new fW(void 0,this.options.timezone||this.options.utcOffset),J=Y;if(this.options.startAt.getTime()<=X.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=X.getTime();)J=new fW(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Q=!0}return J===null&&(J=void 0),[J,Q]}};class wv{localEmit=null;async start(Y){this.localEmit=Y}broadcast(Y,Q){this.localEmit?.(Y,Q)}async stop(){this.localEmit=null}}var Vi0=50,qi0=500;class Bi0{listeners=new Map;totalCount=0;strategy=new wv;started=!1;async start(Y){if(this.started){if(!Y)return;await this.stop()}if(Y)this.strategy=Y;await this.strategy.start((Q,X)=>this.localEmit(Q,X)),this.started=!0}async stop(){if(!this.started)return;await this.strategy.stop(),this.started=!1}add(Y){if(this.totalCount>=qi0)return console.warn(`[SSEHub] Total connection limit reached (${qi0})`),null;let Q=this.listeners.get(Y.organizationId);if(!Q)Q=new Map,this.listeners.set(Y.organizationId,Q);if(Q.size>=Vi0)return console.warn(`[SSEHub] Per-org connection limit reached for ${Y.organizationId} (${Vi0})`),null;return Q.set(Y.id,Y),this.totalCount++,Y.id}remove(Y,Q){let X=this.listeners.get(Y);if(!X)return;if(X.delete(Q)){if(this.totalCount--,X.size===0)this.listeners.delete(Y)}}emit(Y,Q){this.strategy.broadcast(Y,Q)}countForOrg(Y){return this.listeners.get(Y)?.size??0}get count(){return this.totalCount}localEmit(Y,Q){let X=this.listeners.get(Y);if(!X||X.size===0)return;for(let J of X.values()){if(J.typePatterns&&!Zu6(Q.type,J.typePatterns))continue;try{J.push(Q)}catch{this.remove(Y,J.id)}}}}function Zu6(Y,Q){for(let X of Q){if(X===Y)return!0;if(X.endsWith(".*")){let J=X.slice(0,-1);if(Y.startsWith(J))return!0}}return!1}var xJ=new Bi0;function Ui0(Y){return{id:Y.id,type:Y.type,source:Y.source,subject:Y.subject,data:Y.data?Ku6(Y.data):void 0,time:Y.time}}function Ku6(Y){if(typeof Y==="string")try{return JSON.parse(Y)}catch{return Y}return Y}var Ir={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};ta();lS();function Hu6(Y){return Y.endsWith("_self")}function $u6(Y){return Y.slice(0,-5)}function zi0(){return async(Y,Q)=>{try{if(Hu6(Y)&&YD1()){let W=$u6(Y),Z=await UF.create();if(await kd0(Q,{organizationId:W,connectionId:Y,publish:async(F,V,q,U)=>{await Z.eventBus.publish(W,Y,{type:F,subject:V,data:q,deliverAt:U?.deliverAt})},createMCPProxy:async(F)=>{let V=await HN1(F,Z);return{callTool:async(q,U,z)=>{let D=await V.callTool(q,U,z);return{content:D.content,structuredContent:D.structuredContent,isError:D.isError}},close:()=>V.close()}}}))return{success:!0}}let X=await UF.create();console.log("[EventBus:Debug] notify context created",{hasUser:!!X.auth.user,userId:X.auth.user?.id??"NONE",hasOrg:!!X.organization,orgId:X.organization?.id??"NONE",connectionId:Y,eventCount:Q.length,eventTypes:Q.map((W)=>W.type)});let J=await HN1(Y,X);console.log("[EventBus:Debug] proxy created for subscriber",{connectionId:Y,orgIdAfterProxy:X.organization?.id??"NONE"});let K=await mV1.forClient(zO(J)).ON_EVENTS({events:Q});return{success:K.success,error:K.error,retryAfter:K.retryAfter,results:K.results}}catch(X){let J=X instanceof Error?X.message:String(X);return console.error(`[EventBus] Failed to notify connection ${Y}:`,J),{success:!1,error:J}}}}function Di0(Y){return{specversion:"1.0",id:Y.id,source:Y.source,type:Y.type,time:Y.time,subject:Y.subject??void 0,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema??void 0,data:Y.data??void 0}}function Fu6(Y){let Q=new Map;for(let J of Y){let G=J.subscription.connectionId,K=Q.get(G);if(K){if(K.deliveryIds.push(J.delivery.id),!K.seenEventIds.has(J.event.id))K.seenEventIds.add(J.event.id),K.events.push(Di0(J.event))}else Q.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[Di0(J.event)],seenEventIds:new Set([J.event.id])})}let X=new Map;for(let[J,G]of Q)X.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return X}class qN1{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;constructor(Y,Q){this.storage=Y;this.notifySubscriber=zi0(),this.config={...Ir,...Q}}async start(){if(this.running)return;let Y=await this.storage.resetStuckDeliveries();if(Y>0)console.log(`[EventBus] Reset ${Y} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(Y){console.error("[EventBus] Error processing events:",Y)}finally{this.processing=!1}}async processEvents(){let Y=await this.storage.claimPendingDeliveries(this.config.batchSize);if(Y.length===0)return;let Q=Fu6(Y),X=new Set;await Promise.allSettled(Array.from(Q.entries()).map(async([J,G])=>{try{let K=await this.notifySubscriber(G.connectionId,G.events);if(K.results&&Object.keys(K.results).length>0)await this.processPerEventResults(G,K);else if(K.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(K.retryAfter&&K.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,K.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,K.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(K){let W=K instanceof Error?K.message:String(K);console.error(`[EventBus] Failed to notify subscription ${J}:`,W),await this.storage.markDeliveriesFailed(G.deliveryIds,W,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let K of Y)if(G.deliveryIds.includes(K.delivery.id))X.add(K.event.id)}));for(let J of X)try{await this.storage.updateEventStatus(J);let G=Y.find((K)=>K.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(Y,Q){let X=[],J=new Map,G=[],K=new Map;for(let W=0;W<Y.events.length;W++){let Z=Y.events?.[W];if(!Z)continue;let H=Y.deliveryIds?.[W];if(!H)continue;K.set(Z.id,H)}for(let W of Y.events){let Z=K.get(W.id);if(!Z)continue;let H=Q.results?.[W.id];if(H)if(H.success)X.push(Z);else if(H.retryAfter&&H.retryAfter>0){let $=J.get(H.retryAfter)||[];$.push(Z),J.set(H.retryAfter,$)}else G.push({deliveryId:Z,error:H.error||"Event processing failed"});else if(Q.success)X.push(Z);else if(Q.retryAfter&&Q.retryAfter>0){let $=J.get(Q.retryAfter)||[];$.push(Z),J.set(Q.retryAfter,$)}else G.push({deliveryId:Z,error:Q.error||"Batch processing failed"})}if(X.length>0)await this.storage.markDeliveriesDelivered(X);for(let[W,Z]of J)await this.storage.scheduleRetryWithoutAttemptIncrement(Z,W);if(G.length>0){let W=new Map;for(let{deliveryId:Z,error:H}of G){let $=W.get(H)||[];$.push(Z),W.set(H,$)}for(let[Z,H]of W)await this.storage.markDeliveriesFailed(H,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(Y){if(!Y.cron)return;try{let X=new Rr(Y.cron).nextRun();if(!X){console.log(`[EventBus] Cron expression for event ${Y.id} has no more runs`);return}let J=X.toISOString(),G=await this.storage.getMatchingSubscriptions(Y);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${Y.id}, skipping next delivery`);return}await this.storage.createDeliveries(Y.id,G.map((K)=>K.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${Y.id} at ${J}`)}catch(Q){console.error(`[EventBus] Failed to schedule next cron delivery for event ${Y.id}:`,Q)}}}class BN1{storage;worker;notifyStrategy;running=!1;constructor(Y){this.storage=Y.storage,this.notifyStrategy=Y.notifyStrategy,this.worker=new qN1(this.storage,Y.config)}async publish(Y,Q,X){if(X.deliverAt&&X.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(X.cron){try{let F=new Rr(X.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch($){throw Error(`Invalid cron expression: ${$ instanceof Error?$.message:String($)}`)}let H=await this.storage.findActiveCronEvent(Y,X.type,Q,X.cron);if(H)return H}let G=crypto.randomUUID(),K=new Date().toISOString(),W=await this.storage.publishEvent({id:G,organizationId:Y,type:X.type,source:Q,subject:X.subject,time:K,data:X.data,cron:X.cron});xJ.emit(Y,Ui0(W));let Z=await this.storage.getMatchingSubscriptions(W);if(Z.length>0){let H=X.deliverAt??J;if(await this.storage.createDeliveries(G,Z.map(($)=>$.id),H),this.notifyStrategy&&!H)await this.notifyStrategy.notify(G).catch(($)=>{console.warn("[EventBus] Notify failed (non-critical):",$)})}return W}async subscribe(Y,Q){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:Y,connectionId:Q.connectionId,publisher:Q.publisher,eventType:Q.eventType,filter:Q.filter})}async unsubscribe(Y,Q){return this.storage.unsubscribe(Q,Y)}async listSubscriptions(Y,Q){return this.storage.listSubscriptions(Y,Q)}async getSubscription(Y,Q){return this.storage.getSubscription(Q,Y)}async getEvent(Y,Q){return this.storage.getEvent(Q,Y)}async cancelEvent(Y,Q,X){return this.storage.cancelEvent(Q,Y,X)}async ackEvent(Y,Q,X){return this.storage.ackDelivery(Q,Y,X)}async syncSubscriptions(Y,Q){return this.storage.syncSubscriptions({organizationId:Y,...Q})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing after notify:",Y)})});await this.worker.processNow().catch((Y)=>{console.error("[EventBus] Error processing pending events on startup:",Y)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(Y){console.error("[EventBus] Error stopping notify strategy:",Y)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}class UN1{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){let Q=this.options.getConnection();if(!Q||this.sub)return;this.onNotify=Y,this.sub=Q.subscribe("mesh.events.notify"),(async()=>{for await(let X of this.sub)this.onNotify?.()})().catch((X)=>{console.error("[NatsNotify] Subscription error:",X)}),console.log("[NatsNotify] Started, subscribed to","mesh.events.notify")}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null,console.log("[NatsNotify] Stopped")}async notify(Y){let Q=this.options.getConnection();if(!Q)return;try{Q.publish("mesh.events.notify",this.encoder.encode(Y))}catch(X){console.warn("[NatsNotify] Publish failed (non-critical):",X)}}}class zN1{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(Y){this.options=Y}async start(Y){this.localEmit=Y;let Q=this.options.getConnection();if(!Q||this.sub)return;this.sub=Q.subscribe("mesh.sse.broadcast");let X=new TextDecoder;(async()=>{for await(let J of this.sub)try{let G=JSON.parse(X.decode(J.data));if(typeof G?.originId!=="string"||typeof G?.organizationId!=="string"||typeof G?.event?.id!=="string"||typeof G?.event?.type!=="string")continue;if(G.originId===this.originId)continue;this.localEmit?.(G.organizationId,G.event)}catch{}})().catch((J)=>{console.error("[NatsSSEBroadcast] Subscription error:",J)}),console.log("[NatsSSEBroadcast] Started, subscribed to","mesh.sse.broadcast")}broadcast(Y,Q){this.localEmit?.(Y,Q);let X=this.options.getConnection();if(!X)return;let J={originId:this.originId,organizationId:Y,event:Q};try{X.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(J)))}catch(G){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",G)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null,console.log("[NatsSSEBroadcast] Stopped")}}function DN1(...Y){return{async start(Q){await Promise.all(Y.map((X)=>X.start(Q)))},async stop(){await Promise.all(Y.map((Q)=>Q.stop().catch((X)=>{console.error("[NotifyStrategy] Error stopping strategy:",X)})))},async notify(Q){await Promise.all(Y.map((X)=>X.notify(Q).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class ON1{intervalMs;timer=null;onNotify=null;constructor(Y){this.intervalMs=Y}async start(Y){if(this.timer)return;this.onNotify=Y,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(Y){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Vu6}from"kysely";var LP="mesh_events";class NN1{db;pool;listenClient=null;onNotify=null;constructor(Y,Q){this.db=Y;this.pool=Q}async start(Y){if(this.listenClient)return;this.onNotify=Y;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Q)=>{if(Q.channel===LP&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Q)=>{console.error("[PostgresNotify] Connection error:",Q),this.cleanup()}),await this.listenClient.query(`LISTEN ${LP}`),console.log("[PostgresNotify] Started LISTEN on",LP)}catch(Q){console.error("[PostgresNotify] Failed to start LISTEN:",Q),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${LP}`),console.log("[PostgresNotify] Stopped LISTEN on",LP)}catch{}this.cleanup()}}async notify(Y){try{await Vu6`SELECT pg_notify(${LP}, ${Y})`.execute(this.db)}catch(Q){console.warn("[PostgresNotify] Failed to send NOTIFY:",Q)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}function qu6(Y){let Q=process.env.NOTIFY_STRATEGY;if(Q==="nats"||Q==="postgres"||Q==="polling")return Q;if(process.env.NATS_URL)return"nats";if(Y.type==="postgres")return"postgres";return"polling"}function Oi0(Y,Q,X){let J=Zi0(Y.db),G=Q?.pollIntervalMs??Ir.pollIntervalMs,K=qu6(Y),W=new ON1(G),Z=process.env.NATS_URL,H;switch(K){case"nats":{if(!Z)throw Error("[EventBus] NOTIFY_STRATEGY=nats requires NATS_URL to be set");let F=(()=>{try{return new URL(Z).host}catch{return"unknown"}})();if(!X){console.warn(`[EventBus] NATS unavailable (${F}), falling back to polling`),H=W;break}console.log(`[EventBus] Using NATS notify strategy (${F})`),H=DN1(W,new UN1({getConnection:()=>X.getConnection()}));break}case"postgres":{if(Y.type!=="postgres"){console.warn("[EventBus] NOTIFY_STRATEGY=postgres requires a PostgreSQL database, falling back to polling"),H=W;break}console.log("[EventBus] Using PostgreSQL LISTEN/NOTIFY strategy"),H=DN1(W,new NN1(Y.db,Y.pool));break}case"polling":default:console.log("[EventBus] Using polling notify strategy"),H=W}let $=Z&&X?new zN1({getConnection:()=>X.getConnection()}):new wv;if(xJ.start($).catch((F)=>{console.error("[SSEHub] Failed to start broadcast strategy:",F)}),Z&&X)console.log("[SSEHub] Using NATS SSE broadcast (cross-pod)");else console.log("[SSEHub] Using local SSE broadcast (single-pod)");return new BN1({storage:J,config:Q,notifyStrategy:H})}FN();Kv();var Ni0={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}};var Li0=new JQ;Li0.get("/config",async(Y)=>{try{let Q=Object.keys(p9.socialProviders??{}),X=Q.length>0,J=Q.map((W)=>({name:W,icon:Ni0[W].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",K={emailAndPassword:{enabled:p9.emailAndPassword?.enabled??!1},magicLink:{enabled:p9.magicLinkConfig?.enabled??!1},resetPassword:{enabled:oO1},socialProviders:{enabled:X,providers:J},sso:p9.ssoConfig?{enabled:!0,providerId:p9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return Y.json({success:!0,config:K})}catch(Q){let X=Q instanceof Error?Q.message:"Failed to load auth config";return Y.json({success:!1,error:X},500)}});var Mi0=Li0;DP();Uv();KY();rZ();vQ();rZ();rZ();i1();Qr();function wi0(Y){let{toolOutputMap:Q}=Y;return _J({description:"The input is a string. Dont make assumptions about its format; prefer using regexes and string manipulation to extract the desired information. You may call this tool multiple times to extract the desired information.",inputExamples:[{input:{tool_call_id:"tool_call_id_1",code:"export default (input) => { return input.match(/[a-z]/g); }"}},{input:{tool_call_id:"tool_call_id_2",code:"export default (input) => { return input.split(' ').map(word => word.length); }"}}],inputSchema:m8(B.object({tool_call_id:B.string(),code:B.string().min(1).describe("JavaScript code to transform the tool output. The code must be an ES module: `export default (input) => { ... }`")})),execute:async({tool_call_id:X,code:J})=>{if(!Q.has(X))throw Error(`Tool output not found for tool call id: ${X}`);let G=Q.get(X),K=await $D1({input:G,code:J,timeoutMs:5000}),W=LN1({return:K.returnValue});if(W>4000)throw Error(`Tool call ${X} output is too long to display (${W} tokens), reduce or truncate the output`);return{result:K.returnValue,error:K.error,consoleLogs:K.consoleLogs}}})}var Bu6=4,Uu6=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g;function zu6(Y){if(!Y)return 0;let Q=Y.match(Uu6)?.length??0,X=Y.length-Q;return Math.ceil(X/Bu6)+Math.ceil(Q*1.5)}function LN1(Y){let Q=typeof Y==="string"?Y:JSON.stringify(Y);return zu6(Q)}function jr(Y,Q){if(Y==="yolo")return!1;if(Y==="none")return!0;return Q!==!0}function Sr(Y){let Q=Y.get("meshContext").organization;if(!Q)throw Error("Organization context is required");if((Q.slug??Q.id)!==Y.req.param("org"))throw Error("Organization mismatch");return Q}async function Av(Y,Q,X,J="none",G){let K=!G?.disableOutputTruncation,Z=(await Y.listTools()).tools.map((H)=>{let{name:$,title:F,description:V,inputSchema:q,annotations:U}=H;return[$,_J({title:F??$,description:V,inputSchema:IW(q),outputSchema:void 0,needsApproval:jr(J,U?.readOnlyHint),execute:async(z,D)=>{let L=performance.now();try{return await Y.callTool({name:H.name,arguments:z},dK,{signal:D.abortSignal,timeout:nn0})}finally{if(X){let w=performance.now()-L;X.write({type:"data-tool-metadata",id:D.toolCallId,data:{annotations:H.annotations,latencyMs:w}})}}},toModelOutput:async({output:z,toolCallId:D})=>{if(K){let w=LN1(z.structuredContent??z.content);if(w>4000)return Q.set(D,JSON.stringify(z.structuredContent??z.content)),{type:"text",value:`Tool call ${D} output is too long to display (${w} tokens), use the read_tool_output tool`}}if(z.isError)return{type:"error-text",value:z.content.map((E)=>E.type==="text"?E.text:null).filter(Boolean).join(`
1391
1391
  `)||"Unknown error"};if("structuredContent"in z)return{type:"json",value:z.structuredContent};return{type:"text",value:z.content.map((w)=>{if(w.type==="text")return w.text;return JSON.stringify(w)}).join(`
1392
1392
  `)}}})]});return Object.fromEntries(Z)}async function MN1(Y){let Q=Y.get("meshContext"),X=Q.auth?.user?.id;if(!X)throw new TX(401,{message:"Unauthorized"});let J=Sr(Y),G=Y.req.param("threadId");if(/[.*>\s]/.test(G))throw new TX(400,{message:"Invalid thread ID"});let K=await Q.storage.threads.get(G);if(!K||K.organization_id!==J.id)throw new TX(404,{message:"Thread not found"});if(K.created_by!==X)throw new TX(403,{message:"Not authorized"});return{ctx:Q,organization:J,thread:K,threadId:G,userId:X}}rZ();i1();var Du6=B.object({search_term:B.string().optional().describe("Optional search term to filter agents by name, title, or description. Leave empty to return all available agents.")}),Ou6=B.object({agents:B.array(B.object({agent_id:B.string().describe("Unique identifier for the agent"),name:B.string().describe("Human-readable agent name"),purpose:B.string().nullable().describe("What the agent is designed to do"),capabilities:B.array(B.string()).describe("List of capabilities the agent has")}))}),Nu6="Search for agents configured in the organization. Returns agent metadata including purpose and capabilities. Use this to discover specialized agents before delegating work with subtask_run.",Lu6={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1};function Ai0(Y,Q,X){let{organization:J,needsApproval:G}=Q;return _J({description:Nu6,inputSchema:m8(Du6),outputSchema:m8(Ou6),needsApproval:G,execute:async({search_term:K},W)=>{let Z=performance.now();try{let $=(await X.storage.virtualMcps.list(J.id)).filter((V)=>V.status==="active");if(K&&K.trim().length>0){let V=K.toLowerCase();$=$.filter((q)=>{let U=q.title.toLowerCase().includes(V),z=q.description?.toLowerCase().includes(V)??!1;return U||z})}return{agents:$.map((V)=>({agent_id:V.id,name:V.title,purpose:V.description,capabilities:[]}))}}finally{let H=performance.now()-Z;Y.write({type:"data-tool-metadata",id:W.toolCallId,data:{annotations:Lu6,latencyMs:H}})}}})}Uv();KY();rZ();i1();var Mu6=B.object({prompt:B.string().min(1).max(50000).describe("The task to delegate to the subagent. Be specific and self-contained \u2014 "+"the subagent has no access to the parent conversation history."),agent_id:B.string().min(1).max(128).describe("The ID of the agent (Virtual MCP) to delegate to. This agent must exist and be active in the current organization.")}),wu6=`Delegate a self-contained task to another agent. The subagent runs independently with its own tools and returns results when complete. Use this when a task is better handled by a specialized agent, or to parallelize work across agents.
1393
1393