@sequenzy/mcp 0.0.53 → 0.0.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ var r5=Object.create;var{getPrototypeOf:d5,defineProperty:ZQ,getOwnPropertyNames
26
26
  newResult[${T}] = ${_}.value;
27
27
  }
28
28
 
29
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(E,_)=>S(K,E,_)},$,J=O1,z=!r4.jitless,U=z&&PQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!J(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(z&&U&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,L),!A)return K;return a8([],O,K,L,B,Q)}return X(K,L)}});function D8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!G1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((J)=>S0(J,W,b0())))}),Y}var gQ=q("$ZodUnion",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),c(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),c(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),c(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>a1($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let J=!1,z=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)z.push(U),J=!0;else{if(U.issues.length===0)return U;z.push(U)}}if(!J)return D8(z,G,Q,$);return Promise.all(z).then((H)=>{return D8(H,G,Q,$)})}}),e8=q("$ZodDiscriminatedUnion",(Q,Y)=>{gQ.init(Q,Y);let X=Q._zod.parse;c(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let J=$._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[z,H]of Object.entries(J)){if(!G[z])G[z]=new Set;for(let U of H)G[z].add(U)}}return G});let W=E1(()=>{let G=Y.options,$=new Map;for(let J of G){let z=J._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of z){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,J)}}return $});Q._zod.parse=(G,$)=>{let J=G.value;if(!O1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let z=W.value.get(J?.[Y.discriminator]);if(z)return z._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),QW=q("$ZodIntersection",(Q,Y)=>{n.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||J instanceof Promise)return Promise.all([$,J]).then(([H,U])=>{return L8(X,H,U)});return L8(X,$,J)}});function _Q(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(W1(Q)&&W1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let J=_Q(Q[$],Y[$]);if(!J.valid)return{valid:!1,mergeErrorPath:[$,...J.mergeErrorPath]};G[$]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],J=_Q(G,$);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function L8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(G1(Q))return Q;let W=_Q(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var YW=q("$ZodRecord",(Q,Y)=>{n.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!W1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...p0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...p0(H,U.issues));X.value[H]=U.value}}let z;for(let H in G)if(!J.has(H))z=z??[],z.push(H);if(z&&z.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:z})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let z=Y.keyType._zod.run({value:J,issues:[]},W);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((U)=>S0(U,W,b0())),input:J,path:[J],inst:Q}),X.value[z.value]=z.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...p0(J,U.issues));X.value[z.value]=U.value}));else{if(H.issues.length)X.issues.push(...p0(J,H.issues));X.value[z.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var XW=q("$ZodEnum",(Q,Y)=>{n.init(Q,Y);let X=bQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>IQ.has(typeof G)).map((G)=>typeof G==="string"?c0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),WW=q("$ZodLiteral",(Q,Y)=>{if(n.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?c0(X):X?c0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var GW=q("$ZodTransform",(Q,Y)=>{n.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new m0;return X.value=G,X}});function q8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var $W=q("$ZodOptional",(Q,Y)=>{n.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>q8($,X.value));return q8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),JW=q("$ZodNullable",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)}|null)$`):void 0}),c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),zW=q("$ZodDefault",(Q,Y)=>{n.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>F8($,Y));return F8(G,Y)}});function F8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var HW=q("$ZodPrefault",(Q,Y)=>{n.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),UW=q("$ZodNonOptional",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>O8($,Q));return O8(G,Q)}});function O8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var AW=q("$ZodCatch",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((J)=>S0(J,W,b0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>S0($,W,b0()))},input:X.value}),X.issues=[];return X}});var BW=q("$ZodPipe",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"values",()=>Y.in._zod.values),c(Q._zod,"optin",()=>Y.in._zod.optin),c(Q._zod,"optout",()=>Y.out._zod.optout),c(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((J)=>W6(J,Y.in,W));return W6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>W6($,Y.out,W));return W6(G,Y.out,W)}});function W6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var KW=q("$ZodReadonly",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"propValues",()=>Y.innerType._zod.propValues),c(Q._zod,"values",()=>Y.innerType._zod.values),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(M8);return M8(G)}});function M8(Q){return Q.value=Object.freeze(Q.value),Q}var DW=q("$ZodCustom",(Q,Y)=>{G0.init(Q,Y),n.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>V8($,X,W,Q));V8(G,X,W,Q);return}});function V8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(T1(G))}}var fH=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},lH=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${fH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${a4(W.values[0])}`;return`Invalid option: expected one of ${d4(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${d4(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function uQ(){return{localeError:lH()}}var _V=Symbol("ZodOutput"),yV=Symbol("ZodInput");class LW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function mH(){return new LW}var W4=mH();function qW(Q,Y){return new Q({type:"string",...I(Y)})}function FW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...I(Y)})}function hQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...I(Y)})}function OW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...I(Y)})}function MW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(Y)})}function VW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(Y)})}function NW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...I(Y)})}function wW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...I(Y)})}function bW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(Y)})}function jW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...I(Y)})}function PW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(Y)})}function IW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...I(Y)})}function EW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...I(Y)})}function TW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(Y)})}function SW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(Y)})}function RW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(Y)})}function CW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(Y)})}function kW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(Y)})}function vW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...I(Y)})}function xW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...I(Y)})}function _W(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...I(Y)})}function yW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...I(Y)})}function gW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(Y)})}function uW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...I(Y)})}function hW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...I(Y)})}function fW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...I(Y)})}function lW(Q,Y){return new Q({type:"number",checks:[],...I(Y)})}function mW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...I(Y)})}function cW(Q,Y){return new Q({type:"boolean",...I(Y)})}function pW(Q,Y){return new Q({type:"null",...I(Y)})}function iW(Q){return new Q({type:"unknown"})}function nW(Q,Y){return new Q({type:"never",...I(Y)})}function J6(Q,Y){return new kQ({check:"less_than",...I(Y),value:Q,inclusive:!1})}function G4(Q,Y){return new kQ({check:"less_than",...I(Y),value:Q,inclusive:!0})}function z6(Q,Y){return new vQ({check:"greater_than",...I(Y),value:Q,inclusive:!1})}function $4(Q,Y){return new vQ({check:"greater_than",...I(Y),value:Q,inclusive:!0})}function H6(Q,Y){return new sX({check:"multiple_of",...I(Y),value:Q})}function U6(Q,Y){return new Q8({check:"max_length",...I(Y),maximum:Q})}function S1(Q,Y){return new Y8({check:"min_length",...I(Y),minimum:Q})}function A6(Q,Y){return new X8({check:"length_equals",...I(Y),length:Q})}function fQ(Q,Y){return new W8({check:"string_format",format:"regex",...I(Y),pattern:Q})}function lQ(Q){return new G8({check:"string_format",format:"lowercase",...I(Q)})}function mQ(Q){return new $8({check:"string_format",format:"uppercase",...I(Q)})}function cQ(Q,Y){return new J8({check:"string_format",format:"includes",...I(Y),includes:Q})}function pQ(Q,Y){return new z8({check:"string_format",format:"starts_with",...I(Y),prefix:Q})}function iQ(Q,Y){return new H8({check:"string_format",format:"ends_with",...I(Y),suffix:Q})}function M1(Q){return new U8({check:"overwrite",tx:Q})}function nQ(Q){return M1((Y)=>Y.normalize(Q))}function rQ(){return M1((Q)=>Q.trim())}function dQ(){return M1((Q)=>Q.toLowerCase())}function oQ(){return M1((Q)=>Q.toUpperCase())}function rW(Q,Y,X){return new Q({type:"array",element:Y,...I(X)})}function dW(Q,Y,X){let W=I(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function oW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...I(X)})}function tW(Q){let Y=cH((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(T1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(T1(G))}},Q(X.value,X)});return Y}function cH(Q,Y){let X=new G0({check:"custom",...I(Y)});return X._zod.check=Q,X}function R1(Q){return!!Q._zod}function $1(Q,Y){if(R1(Q))return Q4(Q,Y);return Q.safeParse(Y)}function B6(Q){if(!Q)return;let Y;if(R1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function aW(Q){if(R1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var z4={};tY(z4,{time:()=>sQ,duration:()=>eQ,datetime:()=>tQ,date:()=>aQ,ZodISOTime:()=>QG,ZodISODuration:()=>YG,ZodISODateTime:()=>sW,ZodISODate:()=>eW});var sW=q("ZodISODateTime",(Q,Y)=>{C8.init(Q,Y),o.init(Q,Y)});function tQ(Q){return gW(sW,Q)}var eW=q("ZodISODate",(Q,Y)=>{k8.init(Q,Y),o.init(Q,Y)});function aQ(Q){return uW(eW,Q)}var QG=q("ZodISOTime",(Q,Y)=>{v8.init(Q,Y),o.init(Q,Y)});function sQ(Q){return hW(QG,Q)}var YG=q("ZodISODuration",(Q,Y)=>{x8.init(Q,Y),o.init(Q,Y)});function eQ(Q){return fW(YG,Q)}var XG=(Q,Y)=>{s4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>DX(Q,X)},flatten:{value:(X)=>KX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,I1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,I1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},NZ=q("ZodError",XG),N0=q("ZodError",XG,{Parent:Error});var WG=e4(N0),GG=Q6(N0),$G=e1(N0),JG=Y4(N0),zG=LX(N0),HG=qX(N0),UG=FX(N0),AG=OX(N0),BG=MX(N0),KG=VX(N0),DG=ZX(N0),LG=NX(N0);var e=q("ZodType",(Q,Y)=>{return n.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(f.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>T0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>WG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>$G(Q,X,W),Q.parseAsync=async(X,W)=>GG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>JG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>zG(Q,X,W),Q.decode=(X,W)=>HG(Q,X,W),Q.encodeAsync=async(X,W)=>UG(Q,X,W),Q.decodeAsync=async(X,W)=>AG(Q,X,W),Q.safeEncode=(X,W)=>BG(Q,X,W),Q.safeDecode=(X,W)=>KG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>DG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>LG(Q,X,W),Q.refine=(X,W)=>Q.check(h3(X,W)),Q.superRefine=(X)=>Q.check(f3(X)),Q.overwrite=(X)=>Q.check(M1(X)),Q.optional=()=>s(Q),Q.nullable=()=>OG(Q),Q.nullish=()=>s(OG(Q)),Q.nonoptional=(X)=>v3(Q,X),Q.array=()=>y(Q),Q.or=(X)=>i([Q,X]),Q.and=(X)=>D6(Q,X),Q.transform=(X)=>Y9(Q,wG(X)),Q.default=(X)=>R3(Q,X),Q.prefault=(X)=>k3(Q,X),Q.catch=(X)=>_3(Q,X),Q.pipe=(X)=>Y9(Q,X),Q.readonly=()=>u3(Q),Q.describe=(X)=>{let W=Q.clone();return W4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return W4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return W4.get(Q);let W=Q.clone();return W4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),MG=q("_ZodString",(Q,Y)=>{$6.init(Q,Y),e.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(fQ(...W)),Q.includes=(...W)=>Q.check(cQ(...W)),Q.startsWith=(...W)=>Q.check(pQ(...W)),Q.endsWith=(...W)=>Q.check(iQ(...W)),Q.min=(...W)=>Q.check(S1(...W)),Q.max=(...W)=>Q.check(U6(...W)),Q.length=(...W)=>Q.check(A6(...W)),Q.nonempty=(...W)=>Q.check(S1(1,...W)),Q.lowercase=(W)=>Q.check(lQ(W)),Q.uppercase=(W)=>Q.check(mQ(W)),Q.trim=()=>Q.check(rQ()),Q.normalize=(...W)=>Q.check(nQ(...W)),Q.toLowerCase=()=>Q.check(dQ()),Q.toUpperCase=()=>Q.check(oQ())}),sH=q("ZodString",(Q,Y)=>{$6.init(Q,Y),MG.init(Q,Y),Q.email=(X)=>Q.check(FW(eH,X)),Q.url=(X)=>Q.check(NW(Q3,X)),Q.jwt=(X)=>Q.check(yW(q3,X)),Q.emoji=(X)=>Q.check(wW(Y3,X)),Q.guid=(X)=>Q.check(hQ(qG,X)),Q.uuid=(X)=>Q.check(OW(K6,X)),Q.uuidv4=(X)=>Q.check(MW(K6,X)),Q.uuidv6=(X)=>Q.check(VW(K6,X)),Q.uuidv7=(X)=>Q.check(ZW(K6,X)),Q.nanoid=(X)=>Q.check(bW(X3,X)),Q.guid=(X)=>Q.check(hQ(qG,X)),Q.cuid=(X)=>Q.check(jW(W3,X)),Q.cuid2=(X)=>Q.check(PW(G3,X)),Q.ulid=(X)=>Q.check(IW($3,X)),Q.base64=(X)=>Q.check(vW(K3,X)),Q.base64url=(X)=>Q.check(xW(D3,X)),Q.xid=(X)=>Q.check(EW(J3,X)),Q.ksuid=(X)=>Q.check(TW(z3,X)),Q.ipv4=(X)=>Q.check(SW(H3,X)),Q.ipv6=(X)=>Q.check(RW(U3,X)),Q.cidrv4=(X)=>Q.check(CW(A3,X)),Q.cidrv6=(X)=>Q.check(kW(B3,X)),Q.e164=(X)=>Q.check(_W(L3,X)),Q.datetime=(X)=>Q.check(tQ(X)),Q.date=(X)=>Q.check(aQ(X)),Q.time=(X)=>Q.check(sQ(X)),Q.duration=(X)=>Q.check(eQ(X))});function D(Q){return qW(sH,Q)}var o=q("ZodStringFormat",(Q,Y)=>{r.init(Q,Y),MG.init(Q,Y)}),eH=q("ZodEmail",(Q,Y)=>{w8.init(Q,Y),o.init(Q,Y)});var qG=q("ZodGUID",(Q,Y)=>{Z8.init(Q,Y),o.init(Q,Y)});var K6=q("ZodUUID",(Q,Y)=>{N8.init(Q,Y),o.init(Q,Y)});var Q3=q("ZodURL",(Q,Y)=>{b8.init(Q,Y),o.init(Q,Y)});var Y3=q("ZodEmoji",(Q,Y)=>{j8.init(Q,Y),o.init(Q,Y)});var X3=q("ZodNanoID",(Q,Y)=>{P8.init(Q,Y),o.init(Q,Y)});var W3=q("ZodCUID",(Q,Y)=>{I8.init(Q,Y),o.init(Q,Y)});var G3=q("ZodCUID2",(Q,Y)=>{E8.init(Q,Y),o.init(Q,Y)});var $3=q("ZodULID",(Q,Y)=>{T8.init(Q,Y),o.init(Q,Y)});var J3=q("ZodXID",(Q,Y)=>{S8.init(Q,Y),o.init(Q,Y)});var z3=q("ZodKSUID",(Q,Y)=>{R8.init(Q,Y),o.init(Q,Y)});var H3=q("ZodIPv4",(Q,Y)=>{_8.init(Q,Y),o.init(Q,Y)});var U3=q("ZodIPv6",(Q,Y)=>{y8.init(Q,Y),o.init(Q,Y)});var A3=q("ZodCIDRv4",(Q,Y)=>{g8.init(Q,Y),o.init(Q,Y)});var B3=q("ZodCIDRv6",(Q,Y)=>{u8.init(Q,Y),o.init(Q,Y)});var K3=q("ZodBase64",(Q,Y)=>{f8.init(Q,Y),o.init(Q,Y)});var D3=q("ZodBase64URL",(Q,Y)=>{l8.init(Q,Y),o.init(Q,Y)});var L3=q("ZodE164",(Q,Y)=>{m8.init(Q,Y),o.init(Q,Y)});var q3=q("ZodJWT",(Q,Y)=>{c8.init(Q,Y),o.init(Q,Y)});var VG=q("ZodNumber",(Q,Y)=>{yQ.init(Q,Y),e.init(Q,Y),Q.gt=(W,G)=>Q.check(z6(W,G)),Q.gte=(W,G)=>Q.check($4(W,G)),Q.min=(W,G)=>Q.check($4(W,G)),Q.lt=(W,G)=>Q.check(J6(W,G)),Q.lte=(W,G)=>Q.check(G4(W,G)),Q.max=(W,G)=>Q.check(G4(W,G)),Q.int=(W)=>Q.check(FG(W)),Q.safe=(W)=>Q.check(FG(W)),Q.positive=(W)=>Q.check(z6(0,W)),Q.nonnegative=(W)=>Q.check($4(0,W)),Q.negative=(W)=>Q.check(J6(0,W)),Q.nonpositive=(W)=>Q.check(G4(0,W)),Q.multipleOf=(W,G)=>Q.check(H6(W,G)),Q.step=(W,G)=>Q.check(H6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function m(Q){return lW(VG,Q)}var F3=q("ZodNumberFormat",(Q,Y)=>{p8.init(Q,Y),VG.init(Q,Y)});function FG(Q){return mW(F3,Q)}var O3=q("ZodBoolean",(Q,Y)=>{i8.init(Q,Y),e.init(Q,Y)});function W0(Q){return cW(O3,Q)}var M3=q("ZodNull",(Q,Y)=>{n8.init(Q,Y),e.init(Q,Y)});function X9(Q){return pW(M3,Q)}var V3=q("ZodUnknown",(Q,Y)=>{r8.init(Q,Y),e.init(Q,Y)});function t(){return iW(V3)}var Z3=q("ZodNever",(Q,Y)=>{d8.init(Q,Y),e.init(Q,Y)});function N3(Q){return nW(Z3,Q)}var w3=q("ZodArray",(Q,Y)=>{o8.init(Q,Y),e.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(S1(X,W)),Q.nonempty=(X)=>Q.check(S1(1,X)),Q.max=(X,W)=>Q.check(U6(X,W)),Q.length=(X,W)=>Q.check(A6(X,W)),Q.unwrap=()=>Q.element});function y(Q,Y){return rW(w3,Q,Y)}var ZG=q("ZodObject",(Q,Y)=>{s8.init(Q,Y),e.init(Q,Y),f.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>q0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:N3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return f.extend(Q,X)},Q.safeExtend=(X)=>{return f.safeExtend(Q,X)},Q.merge=(X)=>f.merge(Q,X),Q.pick=(X)=>f.pick(Q,X),Q.omit=(X)=>f.omit(Q,X),Q.partial=(...X)=>f.partial(bG,Q,X[0]),Q.required=(...X)=>f.required(jG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...f.normalizeParams(Y)};return new ZG(X)}function K0(Q,Y){return new ZG({type:"object",shape:Q,catchall:t(),...f.normalizeParams(Y)})}var NG=q("ZodUnion",(Q,Y)=>{gQ.init(Q,Y),e.init(Q,Y),Q.options=Y.options});function i(Q,Y){return new NG({type:"union",options:Q,...f.normalizeParams(Y)})}var b3=q("ZodDiscriminatedUnion",(Q,Y)=>{NG.init(Q,Y),e8.init(Q,Y)});function W9(Q,Y,X){return new b3({type:"union",options:Y,discriminator:Q,...f.normalizeParams(X)})}var j3=q("ZodIntersection",(Q,Y)=>{QW.init(Q,Y),e.init(Q,Y)});function D6(Q,Y){return new j3({type:"intersection",left:Q,right:Y})}var P3=q("ZodRecord",(Q,Y)=>{YW.init(Q,Y),e.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function a(Q,Y,X){return new P3({type:"record",keyType:Q,valueType:Y,...f.normalizeParams(X)})}var Q9=q("ZodEnum",(Q,Y)=>{XW.init(Q,Y),e.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let J of W)if(X.has(J))$[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new Q9({...Y,checks:[],...f.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let J of W)if(X.has(J))delete $[J];else throw Error(`Key ${J} not found in enum`);return new Q9({...Y,checks:[],...f.normalizeParams(G),entries:$})}});function q0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new Q9({type:"enum",entries:X,...f.normalizeParams(Y)})}var I3=q("ZodLiteral",(Q,Y)=>{WW.init(Q,Y),e.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new I3({type:"literal",values:Array.isArray(Q)?Q:[Q],...f.normalizeParams(Y)})}var E3=q("ZodTransform",(Q,Y)=>{GW.init(Q,Y),e.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(f.issue($,X.value,Y));else{let J=$;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(f.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function wG(Q){return new E3({type:"transform",transform:Q})}var bG=q("ZodOptional",(Q,Y)=>{$W.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function s(Q){return new bG({type:"optional",innerType:Q})}var T3=q("ZodNullable",(Q,Y)=>{JW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function OG(Q){return new T3({type:"nullable",innerType:Q})}var S3=q("ZodDefault",(Q,Y)=>{zW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function R3(Q,Y){return new S3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var C3=q("ZodPrefault",(Q,Y)=>{HW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function k3(Q,Y){return new C3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var jG=q("ZodNonOptional",(Q,Y)=>{UW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function v3(Q,Y){return new jG({type:"nonoptional",innerType:Q,...f.normalizeParams(Y)})}var x3=q("ZodCatch",(Q,Y)=>{AW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function _3(Q,Y){return new x3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var y3=q("ZodPipe",(Q,Y)=>{BW.init(Q,Y),e.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function Y9(Q,Y){return new y3({type:"pipe",in:Q,out:Y})}var g3=q("ZodReadonly",(Q,Y)=>{KW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function u3(Q){return new g3({type:"readonly",innerType:Q})}var PG=q("ZodCustom",(Q,Y)=>{DW.init(Q,Y),e.init(Q,Y)});function IG(Q,Y){return dW(PG,Q??(()=>!0),Y)}function h3(Q,Y={}){return oW(PG,Q,Y)}function f3(Q){return tW(Q)}function G9(Q,Y){return Y9(wG(Q),Y)}b0(uQ());var $9="2025-11-25";var EG=[$9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],J1="io.modelcontextprotocol/related-task",q6="2.0",$0=IG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),TG=i([D(),m().int()]),SG=D(),FN=K0({ttl:i([m(),X9()]).optional(),pollInterval:m().optional()}),l3=b({ttl:m().optional()}),m3=b({taskId:D()}),J9=K0({progressToken:TG.optional(),[J1]:m3.optional()}),w0=b({_meta:J9.optional()}),H4=w0.extend({task:l3.optional()}),RG=(Q)=>H4.safeParse(Q).success,J0=b({method:D(),params:w0.loose().optional()}),j0=b({_meta:J9.optional()}),P0=b({method:D(),params:j0.loose().optional()}),z0=K0({_meta:J9.optional()}),F6=i([D(),m().int()]),CG=b({jsonrpc:j(q6),id:F6,...J0.shape}).strict(),z9=(Q)=>CG.safeParse(Q).success,kG=b({jsonrpc:j(q6),...P0.shape}).strict(),vG=(Q)=>kG.safeParse(Q).success,H9=b({jsonrpc:j(q6),id:F6,result:z0}).strict(),U4=(Q)=>H9.safeParse(Q).success;var g;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var U9=b({jsonrpc:j(q6),id:F6.optional(),error:b({code:m().int(),message:D(),data:t().optional()})}).strict();var xG=(Q)=>U9.safeParse(Q).success;var _G=i([CG,kG,H9,U9]),ON=i([H9,U9]),O6=z0.strict(),c3=j0.extend({requestId:F6.optional(),reason:D().optional()}),M6=P0.extend({method:j("notifications/cancelled"),params:c3}),p3=b({src:D(),mimeType:D().optional(),sizes:y(D()).optional(),theme:q0(["light","dark"]).optional()}),A4=b({icons:y(p3).optional()}),C1=b({name:D(),title:D().optional()}),yG=C1.extend({...C1.shape,...A4.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),i3=D6(b({applyDefaults:W0().optional()}),a(D(),t())),n3=G9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},D6(b({form:i3.optional(),url:$0.optional()}),a(D(),t()).optional())),r3=K0({list:$0.optional(),cancel:$0.optional(),requests:K0({sampling:K0({createMessage:$0.optional()}).optional(),elicitation:K0({create:$0.optional()}).optional()}).optional()}),d3=K0({list:$0.optional(),cancel:$0.optional(),requests:K0({tools:K0({call:$0.optional()}).optional()}).optional()}),o3=b({experimental:a(D(),$0).optional(),sampling:b({context:$0.optional(),tools:$0.optional()}).optional(),elicitation:n3.optional(),roots:b({listChanged:W0().optional()}).optional(),tasks:r3.optional()}),t3=w0.extend({protocolVersion:D(),capabilities:o3,clientInfo:yG}),A9=J0.extend({method:j("initialize"),params:t3});var a3=b({experimental:a(D(),$0).optional(),logging:$0.optional(),completions:$0.optional(),prompts:b({listChanged:W0().optional()}).optional(),resources:b({subscribe:W0().optional(),listChanged:W0().optional()}).optional(),tools:b({listChanged:W0().optional()}).optional(),tasks:d3.optional()}),s3=z0.extend({protocolVersion:D(),capabilities:a3,serverInfo:yG,instructions:D().optional()}),B9=P0.extend({method:j("notifications/initialized"),params:j0.optional()});var V6=J0.extend({method:j("ping"),params:w0.optional()}),e3=b({progress:m(),total:s(m()),message:s(D())}),QU=b({...j0.shape,...e3.shape,progressToken:TG}),Z6=P0.extend({method:j("notifications/progress"),params:QU}),YU=w0.extend({cursor:SG.optional()}),B4=J0.extend({params:YU.optional()}),K4=z0.extend({nextCursor:SG.optional()}),XU=q0(["working","input_required","completed","failed","cancelled"]),D4=b({taskId:D(),status:XU,ttl:i([m(),X9()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:s(m()),statusMessage:s(D())}),k1=z0.extend({task:D4}),WU=j0.merge(D4),L4=P0.extend({method:j("notifications/tasks/status"),params:WU}),N6=J0.extend({method:j("tasks/get"),params:w0.extend({taskId:D()})}),w6=z0.merge(D4),b6=J0.extend({method:j("tasks/result"),params:w0.extend({taskId:D()})}),MN=z0.loose(),j6=B4.extend({method:j("tasks/list")}),P6=K4.extend({tasks:y(D4)}),I6=J0.extend({method:j("tasks/cancel"),params:w0.extend({taskId:D()})}),gG=z0.merge(D4),uG=b({uri:D(),mimeType:s(D()),_meta:a(D(),t()).optional()}),hG=uG.extend({text:D()}),K9=D().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),fG=uG.extend({blob:K9}),q4=q0(["user","assistant"]),v1=b({audience:y(q4).optional(),priority:m().min(0).max(1).optional(),lastModified:z4.datetime({offset:!0}).optional()}),lG=b({...C1.shape,...A4.shape,uri:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),GU=b({...C1.shape,...A4.shape,uriTemplate:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),D9=B4.extend({method:j("resources/list")}),$U=K4.extend({resources:y(lG)}),JU=B4.extend({method:j("resources/templates/list")}),zU=K4.extend({resourceTemplates:y(GU)}),L9=w0.extend({uri:D()}),HU=L9,q9=J0.extend({method:j("resources/read"),params:HU}),UU=z0.extend({contents:y(i([hG,fG]))}),AU=P0.extend({method:j("notifications/resources/list_changed"),params:j0.optional()}),BU=L9,KU=J0.extend({method:j("resources/subscribe"),params:BU}),DU=L9,LU=J0.extend({method:j("resources/unsubscribe"),params:DU}),qU=j0.extend({uri:D()}),FU=P0.extend({method:j("notifications/resources/updated"),params:qU}),OU=b({name:D(),description:s(D()),required:s(W0())}),MU=b({...C1.shape,...A4.shape,description:s(D()),arguments:s(y(OU)),_meta:s(K0({}))}),VU=B4.extend({method:j("prompts/list")}),ZU=K4.extend({prompts:y(MU)}),NU=w0.extend({name:D(),arguments:a(D(),D()).optional()}),wU=J0.extend({method:j("prompts/get"),params:NU}),F9=b({type:j("text"),text:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),O9=b({type:j("image"),data:K9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),M9=b({type:j("audio"),data:K9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),bU=b({type:j("tool_use"),name:D(),id:D(),input:a(D(),t()),_meta:a(D(),t()).optional()}),jU=b({type:j("resource"),resource:i([hG,fG]),annotations:v1.optional(),_meta:a(D(),t()).optional()}),PU=lG.extend({type:j("resource_link")}),V9=i([F9,O9,M9,PU,jU]),IU=b({role:q4,content:V9}),EU=z0.extend({description:D().optional(),messages:y(IU)}),TU=P0.extend({method:j("notifications/prompts/list_changed"),params:j0.optional()}),SU=b({title:D().optional(),readOnlyHint:W0().optional(),destructiveHint:W0().optional(),idempotentHint:W0().optional(),openWorldHint:W0().optional()}),RU=b({taskSupport:q0(["required","optional","forbidden"]).optional()}),mG=b({...C1.shape,...A4.shape,description:D().optional(),inputSchema:b({type:j("object"),properties:a(D(),$0).optional(),required:y(D()).optional()}).catchall(t()),outputSchema:b({type:j("object"),properties:a(D(),$0).optional(),required:y(D()).optional()}).catchall(t()).optional(),annotations:SU.optional(),execution:RU.optional(),_meta:a(D(),t()).optional()}),Z9=B4.extend({method:j("tools/list")}),CU=K4.extend({tools:y(mG)}),E6=z0.extend({content:y(V9).default([]),structuredContent:a(D(),t()).optional(),isError:W0().optional()}),VN=E6.or(z0.extend({toolResult:t()})),kU=H4.extend({name:D(),arguments:a(D(),t()).optional()}),F4=J0.extend({method:j("tools/call"),params:kU}),vU=P0.extend({method:j("notifications/tools/list_changed"),params:j0.optional()}),ZN=b({autoRefresh:W0().default(!0),debounceMs:m().int().nonnegative().default(300)}),O4=q0(["debug","info","notice","warning","error","critical","alert","emergency"]),xU=w0.extend({level:O4}),N9=J0.extend({method:j("logging/setLevel"),params:xU}),_U=j0.extend({level:O4,logger:D().optional(),data:t()}),yU=P0.extend({method:j("notifications/message"),params:_U}),gU=b({name:D().optional()}),uU=b({hints:y(gU).optional(),costPriority:m().min(0).max(1).optional(),speedPriority:m().min(0).max(1).optional(),intelligencePriority:m().min(0).max(1).optional()}),hU=b({mode:q0(["auto","required","none"]).optional()}),fU=b({type:j("tool_result"),toolUseId:D().describe("The unique identifier for the corresponding tool call."),content:y(V9).default([]),structuredContent:b({}).loose().optional(),isError:W0().optional(),_meta:a(D(),t()).optional()}),lU=W9("type",[F9,O9,M9]),L6=W9("type",[F9,O9,M9,bU,fU]),mU=b({role:q4,content:i([L6,y(L6)]),_meta:a(D(),t()).optional()}),cU=H4.extend({messages:y(mU),modelPreferences:uU.optional(),systemPrompt:D().optional(),includeContext:q0(["none","thisServer","allServers"]).optional(),temperature:m().optional(),maxTokens:m().int(),stopSequences:y(D()).optional(),metadata:$0.optional(),tools:y(mG).optional(),toolChoice:hU.optional()}),pU=J0.extend({method:j("sampling/createMessage"),params:cU}),w9=z0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens"]).or(D())),role:q4,content:lU}),b9=z0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens","toolUse"]).or(D())),role:q4,content:i([L6,y(L6)])}),iU=b({type:j("boolean"),title:D().optional(),description:D().optional(),default:W0().optional()}),nU=b({type:j("string"),title:D().optional(),description:D().optional(),minLength:m().optional(),maxLength:m().optional(),format:q0(["email","uri","date","date-time"]).optional(),default:D().optional()}),rU=b({type:q0(["number","integer"]),title:D().optional(),description:D().optional(),minimum:m().optional(),maximum:m().optional(),default:m().optional()}),dU=b({type:j("string"),title:D().optional(),description:D().optional(),enum:y(D()),default:D().optional()}),oU=b({type:j("string"),title:D().optional(),description:D().optional(),oneOf:y(b({const:D(),title:D()})),default:D().optional()}),tU=b({type:j("string"),title:D().optional(),description:D().optional(),enum:y(D()),enumNames:y(D()).optional(),default:D().optional()}),aU=i([dU,oU]),sU=b({type:j("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:b({type:j("string"),enum:y(D())}),default:y(D()).optional()}),eU=b({type:j("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:b({anyOf:y(b({const:D(),title:D()}))}),default:y(D()).optional()}),QA=i([sU,eU]),YA=i([tU,aU,QA]),XA=i([YA,iU,nU,rU]),WA=H4.extend({mode:j("form").optional(),message:D(),requestedSchema:b({type:j("object"),properties:a(D(),XA),required:y(D()).optional()})}),GA=H4.extend({mode:j("url"),message:D(),elicitationId:D(),url:D().url()}),$A=i([WA,GA]),JA=J0.extend({method:j("elicitation/create"),params:$A}),zA=j0.extend({elicitationId:D()}),HA=P0.extend({method:j("notifications/elicitation/complete"),params:zA}),T6=z0.extend({action:q0(["accept","decline","cancel"]),content:G9((Q)=>Q===null?void 0:Q,a(D(),i([D(),m(),W0(),y(D())])).optional())}),UA=b({type:j("ref/resource"),uri:D()});var AA=b({type:j("ref/prompt"),name:D()}),BA=w0.extend({ref:i([AA,UA]),argument:b({name:D(),value:D()}),context:b({arguments:a(D(),D()).optional()}).optional()}),KA=J0.extend({method:j("completion/complete"),params:BA});var DA=z0.extend({completion:K0({values:y(D()).max(100),total:s(m().int()),hasMore:s(W0())})}),LA=b({uri:D().startsWith("file://"),name:D().optional(),_meta:a(D(),t()).optional()}),qA=J0.extend({method:j("roots/list"),params:w0.optional()}),j9=z0.extend({roots:y(LA)}),FA=P0.extend({method:j("notifications/roots/list_changed"),params:j0.optional()}),NN=i([V6,A9,KA,N9,wU,VU,D9,JU,q9,KU,LU,F4,Z9,N6,b6,j6,I6]),wN=i([M6,Z6,B9,FA,L4]),bN=i([O6,w9,b9,T6,j9,w6,P6,k1]),jN=i([V6,pU,JA,qA,N6,b6,j6,I6]),PN=i([M6,Z6,yU,FU,AU,vU,TU,L4,HA]),IN=i([O6,s3,DA,EU,ZU,$U,zU,UU,E6,CU,w6,P6,k1]);class k extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===g.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new cG(W.elicitations,Y)}return new k(Q,Y,X)}}class cG extends k{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(g.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function z1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var OA=Symbol("Let zodToJsonSchema decide on which parser to use");var $w=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function P9(Q){let X=B6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=aW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function I9(Q,Y){let X=$1(Q,Y);if(!X.success)throw X.error;return X.data}var bA=60000;class E9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(M6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(Z6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(V6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(N6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(b6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let z=J.message,H=z.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),J.type==="response")U(z);else{let A=z,B=new k(A.error.code,A.error.message,A.error.data);U(B)}else{let A=J.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new k(g.InvalidParams,`Task not found: ${G}`);if(!z1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(z1($.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[J1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(j6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new k(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(I6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,`Task not found: ${Y.params.taskId}`);if(z1(W.status))throw new k(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new k(g.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof k)throw W;throw new k(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),k.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),U4(G)||xG(G))this._onresponse(G);else if(z9(G))this._onrequest(G,$);else if(vG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=k.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[J1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let J=RG(Q.params)?Q.params.task:void 0,z=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&z)await z.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:z,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:g.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&$&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(z){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(z);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),U4(Q))X(Q);else{let $=new k(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(U4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let J=$.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(U4(Q))W(Q);else{let $=k.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof k?$:new k(g.InternalError,String($))}}return}let G;try{let $=await this.request(Q,k1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new k(g.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},z1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new k(g.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new k(g.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let z=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,z)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof k?$:new k(g.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:J,relatedTask:z}=X??{};return new Promise((H,U)=>{let A=(V)=>{U(V)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(V){A(V);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(J)K.params={...K.params,task:J};if(z)K.params={...K.params,_meta:{...K.params?._meta||{},[J1]:z}};let L=(V)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(V)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let S=V instanceof k?V:new k(g.RequestTimeout,String(V));U(S)};this._responseHandlers.set(B,(V)=>{if(X?.signal?.aborted)return;if(V instanceof Error)return U(V);try{let S=$1(Y,V.result);if(!S.success)U(S.error);else H(S.data)}catch(S){U(S)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??bA,M=()=>L(k.fromError(g.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let Z=z?.taskId;if(Z){let V=(S)=>{let E=this._responseHandlers.get(B);if(E)E(S);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,V),this._enqueueTaskMessage(Z,{type:"request",message:K,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(B),U(S)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((V)=>{this._cleanupTimeout(B),U(V)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},w6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},P6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},gG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[J1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[J1]:Y.relatedTask}}};this._transport?.send(J,Y).catch((z)=>this._onerror(z))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[J1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=P9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=I9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=P9(Q);this._notificationHandlers.set(X,(W)=>{let G=I9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&z9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new k(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new k(g.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new k(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let z=L4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(z),z1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let J=await X.getTask(W,Y);if(!J)throw new k(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(z1(J.status))throw new k(g.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let H=L4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(H),z1(z.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function pG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function iG(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let J=X[G];if(pG(J)&&pG($))X[G]={...J,...$};else X[G]=$}return X}var w5=oY(NY(),1),b5=oY(N5(),1);function kM(){let Q=new w5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return b5.default(Q),Q}class CY{constructor(Q){this._ajv=Q??kM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class kY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function j5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function P5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class vY extends E9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(O4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new CY,this.setRequestHandler(A9,(X)=>this._oninitialize(X)),this.setNotificationHandler(B9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(N9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,J=O4.safeParse($);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new kY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=iG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=B6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(R1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async(z,H)=>{let U=$1(F4,z);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new k(g.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y(z,H));if(A.task){let L=$1(k1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new k(g.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=$1(E6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new k(g.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){P5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;j5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:EG.includes(Y)?Y:$9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},O6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=$?Array.isArray($.content)?$.content:[$.content]:[],z=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(z){let H=new Set(J.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},b9,Y);return this.request({method:"sampling/createMessage",params:Q},w9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},T6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},T6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new k(g.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch($){if($ instanceof k)throw $;throw new k(g.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},j9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var I5={name:"@sequenzy/mcp",version:"0.0.53",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var xY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],E5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function xM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function f0(Q){let Y=Q?.trim();return Y?Y:void 0}function a0(Q){return encodeURIComponent(Q)}function Y0(Q,Y){return`${Q}${Y}`}function X0(Q,Y=""){return`/dashboard/company/${a0(Q)}${Y}`}function T5(Q,Y,X){return Y0(Q,`${X0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function _M(Q,Y){let X=xY.map((W)=>[W,Y?T5(Q,Y,W):""]);return Object.fromEntries(X)}function q1(Q={},Y){let X=xM(Y),W=f0(Q.companyId),G={},$=_M(X,W);if(!W)return{appUrl:X,routeTemplates:E5,settingsTabValues:xY,urls:G,settingsUrls:$};G.dashboard=Y0(X,X0(W)),G.campaigns=Y0(X,X0(W,"/campaign")),G.sequences=Y0(X,X0(W,"/sequences")),G.settings=Y0(X,X0(W,"/settings")),G.emails=Y0(X,X0(W,"/emails")),G.subscribers=Y0(X,X0(W,"/subscribers")),G.sentEmails=Y0(X,X0(W,"/sent-emails")),G.segments=Y0(X,X0(W,"/segments")),G.metrics=Y0(X,X0(W,"/metrics")),G.transactional=Y0(X,X0(W,"/transactional"));let J=f0(Q.campaignId);if(J)G.campaign=Y0(X,X0(W,`/campaign/${a0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let z=f0(Q.sequenceId);if(z)G.sequence=Y0(X,X0(W,`/sequences/${a0(z)}`));let H=f0(Q.emailId)??f0(Q.templateId);if(H)G.email=Y0(X,X0(W,`/emails/${a0(H)}`)),G.template=G.email;let U=f0(Q.transactionalId);if(U)G.transactionalEmail=Y0(X,X0(W,`/transactional/${a0(U)}`));let A=f0(Q.emailSendId);if(A)G.emailSend=Y0(X,X0(W,`/sent-emails/${a0(A)}`));let B=f0(Q.domainId);if(B)G.domain=Y0(X,X0(W,`/settings/domain/${a0(B)}`)),G.domainVerify=`${G.domain}/verify`;let K=f0(Q.status);if(K)G.campaignList=Y0(X,X0(W,`/campaign/list/${a0(K)}`)),G.sequenceList=Y0(X,X0(W,`/sequences/list/${a0(K)}`));let L=f0(Q.settingsTab);if(L)G.settingsTab=T5(X,W,L);return{appUrl:X,routeTemplates:E5,settingsTabValues:xY,urls:G,settingsUrls:$}}var S5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function R5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await F("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await F("GET","/api/v1/account"),W=Q1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await F("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await F("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await F("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await F("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await F("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await F("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await F("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await F("GET","/api/v1/tags");break;case"sequenzy://health":Y=await F("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=q1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:e0(Y)}]}}}import{readFileSync as yM,statSync as gM}from"node:fs";import{basename as uM}from"node:path";var m4="Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",i1="Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`.",u5="Sequenzy email blocks. Provide blocks or html for email steps. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items.",C5=500,qQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],FQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],uY={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"]},hM=Object.entries(uY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),k5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${hM}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},v5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function hY(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function fY(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=hY([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(fY):[]}}function fM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function lM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function x5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function mM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),J=X.at(-2),z=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return $&&Number.isInteger(H)&&H>0&&z!==void 0&&x5(z)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&x5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function cM(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function pM(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function iM(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function nM(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function rM(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function dM(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let z=X.indexOf(":");if(z===-1)return null;let H=X.substring(0,z).trim(),U=Number.parseInt(X.substring(z+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=cM(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=pM(G);if(iM(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!nM(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!rM(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}function mY(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in uY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=uY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!fM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!lM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=mM(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=dM(X,W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((z)=>z.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function cY(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=mY(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(cY);return[]}function P1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function LQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function oM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=mY(G);return $?[$]:[]}):cY(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function tM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=mY(G);return $?[$]:[]}):X?cY(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}function aM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;return Y}function sM(Q){let Y=N(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((z)=>typeof z==="string"?z.trim():"").filter((z)=>z.length>0)??[];if(W?.some((z)=>typeof z!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=N(Q,"fieldPath"),J=N(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function eM(Q){P1("create_campaign",Q),LQ("create_campaign",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function QV(Q){if(N(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!B0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function YV(Q){P1("create_transactional_email",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var _5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:u5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function XV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function B0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function y5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function WV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function GV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,J=0,z=0,H=0;while(!0){let A=WV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await F("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);J=B.pagination?.total??B.subscribers.length,z=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:J,totalPages:z,fetchedPages:H},returned:U.length,truncated:X!==void 0&&J>0&&U.length<J}}function $V(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function c4(Q,Y){let X=$V(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function lY(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function _Y(Q,Y){return F("GET",lY(Q),void 0,Y)}function N(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function x(Q,Y,X){let W=N(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function s0(Q,Y,X,W){let G=N(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function yY(Q,Y,X,W){let G=x(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function p4(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function g5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!FQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${FQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function gY(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>C5)throw Error(`\`emails\` must include no more than ${C5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}var JV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function zV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return JV[Y]??null}var HV=104857600;async function UV(Q,Y){if(!eY())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=zV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=gM(Q).size;if(W>HV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=yM(Q),$=await F("POST","/api/v1/products/delivery/upload-url",{filename:uM(Q),contentType:X,fileSizeBytes:W},Y),J=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function h5(Q){let Y=N(Q,"companyId");if(Y)return Y;let X=Q1();if(X)return X;try{return(await F("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function i4(Q,Y){if(!B0(Q)||!Y)return Q;return{...Q,url:Y}}function f5(Q,Y){if(!B0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function DQ(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!B0(W))return W;let G=N(W,"id");if(!G)return W;let $=q1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return f5(W,$.urls);let J=X==="sequence"?$.urls.sequence:X==="template"?$.urls.email:$.urls.transactionalEmail;return i4(W,J)})}function AV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!B0(Y))return Y;let X=N(Y,"id");if(!X)return Y;let W=q1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var BV=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function KV(Q,Y,X){if(!B0(X)||!BV.has(Q))return X;let W=B0(X.company)?X.company:void 0,$=N(X,"selectedCompanyId")??N(X,"currentCompanyId")??N(X,"companyId")??(W?N(W,"id"):void 0)??(W?N(W,"companyId"):void 0)??await h5(Y);if(!$)return X;let J=B0(X.campaign)?X.campaign:void 0,z=B0(X.sequence)?X.sequence:void 0,H=B0(X.template)?X.template:void 0,U=B0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,A={companyId:$,campaignId:N(Y,"campaignId")??N(X,"campaignId")??(J?N(J,"id"):void 0),sequenceId:N(Y,"sequenceId")??N(X,"sequenceId")??(z?N(z,"id"):void 0),emailId:N(X,"templateId")??(H?N(H,"id"):void 0)??(U?N(U,"emailId"):void 0)??N(Y,"templateId"),transactionalId:N(Y,"transactionalId")??(U?N(U,"id"):void 0)??N(Y,"idOrSlug"),emailSendId:N(Y,"emailSendId")??N(X,"emailSendId")??(B0(X.emailSend)?N(X.emailSend,"id"):void 0),status:N(Y,"status")},B=q1(A),K=W?q1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:AV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:DQ(X.campaigns,$,"campaign")},...Array.isArray(X.sequences)&&{sequences:DQ(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:DQ(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:DQ(X.transactional,$,"transactional")},...W&&K!==void 0&&{company:{...W,url:K.urls.dashboard,settingsUrl:K.urls.settings}},...J&&B.urls.campaign!==void 0&&{campaign:f5(J,B.urls)},...z&&B.urls.sequence!==void 0&&{sequence:i4(z,B.urls.sequence)},...H&&B.urls.email!==void 0&&{template:i4(H,B.urls.email)},...U&&B.urls.transactionalEmail!==void 0&&{transactional:i4(U,B.urls.transactionalEmail)},...B0(X.emailSend)&&B.urls.emailSend!==void 0&&{emailSend:i4(X.emailSend,B.urls.emailSend)},appUrls:B.urls}}var l5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
29
+ `)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(E,_)=>S(K,E,_)},$,J=O1,z=!r4.jitless,U=z&&PQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!J(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if(z&&U&&L?.async===!1&&L.jitless!==!0){if(!$)$=G(Y.shape);if(K=$(K,L),!A)return K;return a8([],O,K,L,B,Q)}return X(K,L)}});function D8(Q,Y,X,W){for(let $ of Q)if($.issues.length===0)return Y.value=$.value,Y;let G=Q.filter(($)=>!G1($));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map(($)=>$.issues.map((J)=>S0(J,W,b0())))}),Y}var gQ=q("$ZodUnion",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),c(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),c(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),c(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map(($)=>$._zod.pattern);return new RegExp(`^(${G.map(($)=>a1($.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,$)=>{if(X)return W(G,$);let J=!1,z=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},$);if(U instanceof Promise)z.push(U),J=!0;else{if(U.issues.length===0)return U;z.push(U)}}if(!J)return D8(z,G,Q,$);return Promise.all(z).then((H)=>{return D8(H,G,Q,$)})}}),e8=q("$ZodDiscriminatedUnion",(Q,Y)=>{gQ.init(Q,Y);let X=Q._zod.parse;c(Q._zod,"propValues",()=>{let G={};for(let $ of Y.options){let J=$._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf($)}"`);for(let[z,H]of Object.entries(J)){if(!G[z])G[z]=new Set;for(let U of H)G[z].add(U)}}return G});let W=E1(()=>{let G=Y.options,$=new Map;for(let J of G){let z=J._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of z){if($.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);$.set(H,J)}}return $});Q._zod.parse=(G,$)=>{let J=G.value;if(!O1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let z=W.value.get(J?.[Y.discriminator]);if(z)return z._zod.run(G,$);if(Y.unionFallback)return X(G,$);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),QW=q("$ZodIntersection",(Q,Y)=>{n.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,$=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if($ instanceof Promise||J instanceof Promise)return Promise.all([$,J]).then(([H,U])=>{return L8(X,H,U)});return L8(X,$,J)}});function _Q(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(W1(Q)&&W1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter(($)=>X.indexOf($)!==-1),G={...Q,...Y};for(let $ of W){let J=_Q(Q[$],Y[$]);if(!J.valid)return{valid:!1,mergeErrorPath:[$,...J.mergeErrorPath]};G[$]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],$=Y[W],J=_Q(G,$);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function L8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(G1(Q))return Q;let W=_Q(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var YW=q("$ZodRecord",(Q,Y)=>{n.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!W1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let $=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)$.push(U.then((A)=>{if(A.issues.length)X.issues.push(...p0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...p0(H,U.issues));X.value[H]=U.value}}let z;for(let H in G)if(!J.has(H))z=z??[],z.push(H);if(z&&z.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:z})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let z=Y.keyType._zod.run({value:J,issues:[]},W);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:z.issues.map((U)=>S0(U,W,b0())),input:J,path:[J],inst:Q}),X.value[z.value]=z.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)$.push(H.then((U)=>{if(U.issues.length)X.issues.push(...p0(J,U.issues));X.value[z.value]=U.value}));else{if(H.issues.length)X.issues.push(...p0(J,H.issues));X.value[z.value]=H.value}}}if($.length)return Promise.all($).then(()=>X);return X}});var XW=q("$ZodEnum",(Q,Y)=>{n.init(Q,Y);let X=bQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>IQ.has(typeof G)).map((G)=>typeof G==="string"?c0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,$)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),WW=q("$ZodLiteral",(Q,Y)=>{if(n.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?c0(X):X?c0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var GW=q("$ZodTransform",(Q,Y)=>{n.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new m0;return X.value=G,X}});function q8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var $W=q("$ZodOptional",(Q,Y)=>{n.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>q8($,X.value));return q8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),JW=q("$ZodNullable",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)}|null)$`):void 0}),c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),zW=q("$ZodDefault",(Q,Y)=>{n.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>F8($,Y));return F8(G,Y)}});function F8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var HW=q("$ZodPrefault",(Q,Y)=>{n.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),UW=q("$ZodNonOptional",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>O8($,Q));return O8(G,Q)}});function O8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var AW=q("$ZodCatch",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>{if(X.value=$.value,$.issues.length)X.value=Y.catchValue({...X,error:{issues:$.issues.map((J)=>S0(J,W,b0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map(($)=>S0($,W,b0()))},input:X.value}),X.issues=[];return X}});var BW=q("$ZodPipe",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"values",()=>Y.in._zod.values),c(Q._zod,"optin",()=>Y.in._zod.optin),c(Q._zod,"optout",()=>Y.out._zod.optout),c(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let $=Y.out._zod.run(X,W);if($ instanceof Promise)return $.then((J)=>W6(J,Y.in,W));return W6($,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then(($)=>W6($,Y.out,W));return W6(G,Y.out,W)}});function W6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var KW=q("$ZodReadonly",(Q,Y)=>{n.init(Q,Y),c(Q._zod,"propValues",()=>Y.innerType._zod.propValues),c(Q._zod,"values",()=>Y.innerType._zod.values),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(M8);return M8(G)}});function M8(Q){return Q.value=Object.freeze(Q.value),Q}var DW=q("$ZodCustom",(Q,Y)=>{G0.init(Q,Y),n.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then(($)=>V8($,X,W,Q));V8(G,X,W,Q);return}});function V8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(T1(G))}}var fH=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},lH=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${fH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${a4(W.values[0])}`;return`Invalid option: expected one of ${d4(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",$=Y(W.origin);if($)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${$.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",$=Y(W.origin);if($)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${$.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${d4(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function uQ(){return{localeError:lH()}}var _V=Symbol("ZodOutput"),yV=Symbol("ZodInput");class LW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function mH(){return new LW}var W4=mH();function qW(Q,Y){return new Q({type:"string",...I(Y)})}function FW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...I(Y)})}function hQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...I(Y)})}function OW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...I(Y)})}function MW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(Y)})}function VW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(Y)})}function NW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...I(Y)})}function wW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...I(Y)})}function bW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(Y)})}function jW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...I(Y)})}function PW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(Y)})}function IW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...I(Y)})}function EW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...I(Y)})}function TW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(Y)})}function SW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(Y)})}function RW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(Y)})}function CW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(Y)})}function kW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(Y)})}function vW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...I(Y)})}function xW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...I(Y)})}function _W(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...I(Y)})}function yW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...I(Y)})}function gW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(Y)})}function uW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...I(Y)})}function hW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...I(Y)})}function fW(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...I(Y)})}function lW(Q,Y){return new Q({type:"number",checks:[],...I(Y)})}function mW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...I(Y)})}function cW(Q,Y){return new Q({type:"boolean",...I(Y)})}function pW(Q,Y){return new Q({type:"null",...I(Y)})}function iW(Q){return new Q({type:"unknown"})}function nW(Q,Y){return new Q({type:"never",...I(Y)})}function J6(Q,Y){return new kQ({check:"less_than",...I(Y),value:Q,inclusive:!1})}function G4(Q,Y){return new kQ({check:"less_than",...I(Y),value:Q,inclusive:!0})}function z6(Q,Y){return new vQ({check:"greater_than",...I(Y),value:Q,inclusive:!1})}function $4(Q,Y){return new vQ({check:"greater_than",...I(Y),value:Q,inclusive:!0})}function H6(Q,Y){return new sX({check:"multiple_of",...I(Y),value:Q})}function U6(Q,Y){return new Q8({check:"max_length",...I(Y),maximum:Q})}function S1(Q,Y){return new Y8({check:"min_length",...I(Y),minimum:Q})}function A6(Q,Y){return new X8({check:"length_equals",...I(Y),length:Q})}function fQ(Q,Y){return new W8({check:"string_format",format:"regex",...I(Y),pattern:Q})}function lQ(Q){return new G8({check:"string_format",format:"lowercase",...I(Q)})}function mQ(Q){return new $8({check:"string_format",format:"uppercase",...I(Q)})}function cQ(Q,Y){return new J8({check:"string_format",format:"includes",...I(Y),includes:Q})}function pQ(Q,Y){return new z8({check:"string_format",format:"starts_with",...I(Y),prefix:Q})}function iQ(Q,Y){return new H8({check:"string_format",format:"ends_with",...I(Y),suffix:Q})}function M1(Q){return new U8({check:"overwrite",tx:Q})}function nQ(Q){return M1((Y)=>Y.normalize(Q))}function rQ(){return M1((Q)=>Q.trim())}function dQ(){return M1((Q)=>Q.toLowerCase())}function oQ(){return M1((Q)=>Q.toUpperCase())}function rW(Q,Y,X){return new Q({type:"array",element:Y,...I(X)})}function dW(Q,Y,X){let W=I(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function oW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...I(X)})}function tW(Q){let Y=cH((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(T1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(T1(G))}},Q(X.value,X)});return Y}function cH(Q,Y){let X=new G0({check:"custom",...I(Y)});return X._zod.check=Q,X}function R1(Q){return!!Q._zod}function $1(Q,Y){if(R1(Q))return Q4(Q,Y);return Q.safeParse(Y)}function B6(Q){if(!Q)return;let Y;if(R1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function aW(Q){if(R1(Q)){let $=Q._zod?.def;if($){if($.value!==void 0)return $.value;if(Array.isArray($.values)&&$.values.length>0)return $.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var z4={};tY(z4,{time:()=>sQ,duration:()=>eQ,datetime:()=>tQ,date:()=>aQ,ZodISOTime:()=>QG,ZodISODuration:()=>YG,ZodISODateTime:()=>sW,ZodISODate:()=>eW});var sW=q("ZodISODateTime",(Q,Y)=>{C8.init(Q,Y),o.init(Q,Y)});function tQ(Q){return gW(sW,Q)}var eW=q("ZodISODate",(Q,Y)=>{k8.init(Q,Y),o.init(Q,Y)});function aQ(Q){return uW(eW,Q)}var QG=q("ZodISOTime",(Q,Y)=>{v8.init(Q,Y),o.init(Q,Y)});function sQ(Q){return hW(QG,Q)}var YG=q("ZodISODuration",(Q,Y)=>{x8.init(Q,Y),o.init(Q,Y)});function eQ(Q){return fW(YG,Q)}var XG=(Q,Y)=>{s4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>DX(Q,X)},flatten:{value:(X)=>KX(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,I1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,I1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},NZ=q("ZodError",XG),N0=q("ZodError",XG,{Parent:Error});var WG=e4(N0),GG=Q6(N0),$G=e1(N0),JG=Y4(N0),zG=LX(N0),HG=qX(N0),UG=FX(N0),AG=OX(N0),BG=MX(N0),KG=VX(N0),DG=ZX(N0),LG=NX(N0);var e=q("ZodType",(Q,Y)=>{return n.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(f.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>T0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>WG(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>$G(Q,X,W),Q.parseAsync=async(X,W)=>GG(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>JG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>zG(Q,X,W),Q.decode=(X,W)=>HG(Q,X,W),Q.encodeAsync=async(X,W)=>UG(Q,X,W),Q.decodeAsync=async(X,W)=>AG(Q,X,W),Q.safeEncode=(X,W)=>BG(Q,X,W),Q.safeDecode=(X,W)=>KG(Q,X,W),Q.safeEncodeAsync=async(X,W)=>DG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>LG(Q,X,W),Q.refine=(X,W)=>Q.check(h3(X,W)),Q.superRefine=(X)=>Q.check(f3(X)),Q.overwrite=(X)=>Q.check(M1(X)),Q.optional=()=>s(Q),Q.nullable=()=>OG(Q),Q.nullish=()=>s(OG(Q)),Q.nonoptional=(X)=>v3(Q,X),Q.array=()=>y(Q),Q.or=(X)=>i([Q,X]),Q.and=(X)=>D6(Q,X),Q.transform=(X)=>Y9(Q,wG(X)),Q.default=(X)=>R3(Q,X),Q.prefault=(X)=>k3(Q,X),Q.catch=(X)=>_3(Q,X),Q.pipe=(X)=>Y9(Q,X),Q.readonly=()=>u3(Q),Q.describe=(X)=>{let W=Q.clone();return W4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return W4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return W4.get(Q);let W=Q.clone();return W4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),MG=q("_ZodString",(Q,Y)=>{$6.init(Q,Y),e.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(fQ(...W)),Q.includes=(...W)=>Q.check(cQ(...W)),Q.startsWith=(...W)=>Q.check(pQ(...W)),Q.endsWith=(...W)=>Q.check(iQ(...W)),Q.min=(...W)=>Q.check(S1(...W)),Q.max=(...W)=>Q.check(U6(...W)),Q.length=(...W)=>Q.check(A6(...W)),Q.nonempty=(...W)=>Q.check(S1(1,...W)),Q.lowercase=(W)=>Q.check(lQ(W)),Q.uppercase=(W)=>Q.check(mQ(W)),Q.trim=()=>Q.check(rQ()),Q.normalize=(...W)=>Q.check(nQ(...W)),Q.toLowerCase=()=>Q.check(dQ()),Q.toUpperCase=()=>Q.check(oQ())}),sH=q("ZodString",(Q,Y)=>{$6.init(Q,Y),MG.init(Q,Y),Q.email=(X)=>Q.check(FW(eH,X)),Q.url=(X)=>Q.check(NW(Q3,X)),Q.jwt=(X)=>Q.check(yW(q3,X)),Q.emoji=(X)=>Q.check(wW(Y3,X)),Q.guid=(X)=>Q.check(hQ(qG,X)),Q.uuid=(X)=>Q.check(OW(K6,X)),Q.uuidv4=(X)=>Q.check(MW(K6,X)),Q.uuidv6=(X)=>Q.check(VW(K6,X)),Q.uuidv7=(X)=>Q.check(ZW(K6,X)),Q.nanoid=(X)=>Q.check(bW(X3,X)),Q.guid=(X)=>Q.check(hQ(qG,X)),Q.cuid=(X)=>Q.check(jW(W3,X)),Q.cuid2=(X)=>Q.check(PW(G3,X)),Q.ulid=(X)=>Q.check(IW($3,X)),Q.base64=(X)=>Q.check(vW(K3,X)),Q.base64url=(X)=>Q.check(xW(D3,X)),Q.xid=(X)=>Q.check(EW(J3,X)),Q.ksuid=(X)=>Q.check(TW(z3,X)),Q.ipv4=(X)=>Q.check(SW(H3,X)),Q.ipv6=(X)=>Q.check(RW(U3,X)),Q.cidrv4=(X)=>Q.check(CW(A3,X)),Q.cidrv6=(X)=>Q.check(kW(B3,X)),Q.e164=(X)=>Q.check(_W(L3,X)),Q.datetime=(X)=>Q.check(tQ(X)),Q.date=(X)=>Q.check(aQ(X)),Q.time=(X)=>Q.check(sQ(X)),Q.duration=(X)=>Q.check(eQ(X))});function D(Q){return qW(sH,Q)}var o=q("ZodStringFormat",(Q,Y)=>{r.init(Q,Y),MG.init(Q,Y)}),eH=q("ZodEmail",(Q,Y)=>{w8.init(Q,Y),o.init(Q,Y)});var qG=q("ZodGUID",(Q,Y)=>{Z8.init(Q,Y),o.init(Q,Y)});var K6=q("ZodUUID",(Q,Y)=>{N8.init(Q,Y),o.init(Q,Y)});var Q3=q("ZodURL",(Q,Y)=>{b8.init(Q,Y),o.init(Q,Y)});var Y3=q("ZodEmoji",(Q,Y)=>{j8.init(Q,Y),o.init(Q,Y)});var X3=q("ZodNanoID",(Q,Y)=>{P8.init(Q,Y),o.init(Q,Y)});var W3=q("ZodCUID",(Q,Y)=>{I8.init(Q,Y),o.init(Q,Y)});var G3=q("ZodCUID2",(Q,Y)=>{E8.init(Q,Y),o.init(Q,Y)});var $3=q("ZodULID",(Q,Y)=>{T8.init(Q,Y),o.init(Q,Y)});var J3=q("ZodXID",(Q,Y)=>{S8.init(Q,Y),o.init(Q,Y)});var z3=q("ZodKSUID",(Q,Y)=>{R8.init(Q,Y),o.init(Q,Y)});var H3=q("ZodIPv4",(Q,Y)=>{_8.init(Q,Y),o.init(Q,Y)});var U3=q("ZodIPv6",(Q,Y)=>{y8.init(Q,Y),o.init(Q,Y)});var A3=q("ZodCIDRv4",(Q,Y)=>{g8.init(Q,Y),o.init(Q,Y)});var B3=q("ZodCIDRv6",(Q,Y)=>{u8.init(Q,Y),o.init(Q,Y)});var K3=q("ZodBase64",(Q,Y)=>{f8.init(Q,Y),o.init(Q,Y)});var D3=q("ZodBase64URL",(Q,Y)=>{l8.init(Q,Y),o.init(Q,Y)});var L3=q("ZodE164",(Q,Y)=>{m8.init(Q,Y),o.init(Q,Y)});var q3=q("ZodJWT",(Q,Y)=>{c8.init(Q,Y),o.init(Q,Y)});var VG=q("ZodNumber",(Q,Y)=>{yQ.init(Q,Y),e.init(Q,Y),Q.gt=(W,G)=>Q.check(z6(W,G)),Q.gte=(W,G)=>Q.check($4(W,G)),Q.min=(W,G)=>Q.check($4(W,G)),Q.lt=(W,G)=>Q.check(J6(W,G)),Q.lte=(W,G)=>Q.check(G4(W,G)),Q.max=(W,G)=>Q.check(G4(W,G)),Q.int=(W)=>Q.check(FG(W)),Q.safe=(W)=>Q.check(FG(W)),Q.positive=(W)=>Q.check(z6(0,W)),Q.nonnegative=(W)=>Q.check($4(0,W)),Q.negative=(W)=>Q.check(J6(0,W)),Q.nonpositive=(W)=>Q.check(G4(0,W)),Q.multipleOf=(W,G)=>Q.check(H6(W,G)),Q.step=(W,G)=>Q.check(H6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function m(Q){return lW(VG,Q)}var F3=q("ZodNumberFormat",(Q,Y)=>{p8.init(Q,Y),VG.init(Q,Y)});function FG(Q){return mW(F3,Q)}var O3=q("ZodBoolean",(Q,Y)=>{i8.init(Q,Y),e.init(Q,Y)});function W0(Q){return cW(O3,Q)}var M3=q("ZodNull",(Q,Y)=>{n8.init(Q,Y),e.init(Q,Y)});function X9(Q){return pW(M3,Q)}var V3=q("ZodUnknown",(Q,Y)=>{r8.init(Q,Y),e.init(Q,Y)});function t(){return iW(V3)}var Z3=q("ZodNever",(Q,Y)=>{d8.init(Q,Y),e.init(Q,Y)});function N3(Q){return nW(Z3,Q)}var w3=q("ZodArray",(Q,Y)=>{o8.init(Q,Y),e.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(S1(X,W)),Q.nonempty=(X)=>Q.check(S1(1,X)),Q.max=(X,W)=>Q.check(U6(X,W)),Q.length=(X,W)=>Q.check(A6(X,W)),Q.unwrap=()=>Q.element});function y(Q,Y){return rW(w3,Q,Y)}var ZG=q("ZodObject",(Q,Y)=>{s8.init(Q,Y),e.init(Q,Y),f.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>q0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:N3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return f.extend(Q,X)},Q.safeExtend=(X)=>{return f.safeExtend(Q,X)},Q.merge=(X)=>f.merge(Q,X),Q.pick=(X)=>f.pick(Q,X),Q.omit=(X)=>f.omit(Q,X),Q.partial=(...X)=>f.partial(bG,Q,X[0]),Q.required=(...X)=>f.required(jG,Q,X[0])});function b(Q,Y){let X={type:"object",shape:Q??{},...f.normalizeParams(Y)};return new ZG(X)}function K0(Q,Y){return new ZG({type:"object",shape:Q,catchall:t(),...f.normalizeParams(Y)})}var NG=q("ZodUnion",(Q,Y)=>{gQ.init(Q,Y),e.init(Q,Y),Q.options=Y.options});function i(Q,Y){return new NG({type:"union",options:Q,...f.normalizeParams(Y)})}var b3=q("ZodDiscriminatedUnion",(Q,Y)=>{NG.init(Q,Y),e8.init(Q,Y)});function W9(Q,Y,X){return new b3({type:"union",options:Y,discriminator:Q,...f.normalizeParams(X)})}var j3=q("ZodIntersection",(Q,Y)=>{QW.init(Q,Y),e.init(Q,Y)});function D6(Q,Y){return new j3({type:"intersection",left:Q,right:Y})}var P3=q("ZodRecord",(Q,Y)=>{YW.init(Q,Y),e.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function a(Q,Y,X){return new P3({type:"record",keyType:Q,valueType:Y,...f.normalizeParams(X)})}var Q9=q("ZodEnum",(Q,Y)=>{XW.init(Q,Y),e.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let $={};for(let J of W)if(X.has(J))$[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new Q9({...Y,checks:[],...f.normalizeParams(G),entries:$})},Q.exclude=(W,G)=>{let $={...Y.entries};for(let J of W)if(X.has(J))delete $[J];else throw Error(`Key ${J} not found in enum`);return new Q9({...Y,checks:[],...f.normalizeParams(G),entries:$})}});function q0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new Q9({type:"enum",entries:X,...f.normalizeParams(Y)})}var I3=q("ZodLiteral",(Q,Y)=>{WW.init(Q,Y),e.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function j(Q,Y){return new I3({type:"literal",values:Array.isArray(Q)?Q:[Q],...f.normalizeParams(Y)})}var E3=q("ZodTransform",(Q,Y)=>{GW.init(Q,Y),e.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);X.addIssue=($)=>{if(typeof $==="string")X.issues.push(f.issue($,X.value,Y));else{let J=$;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(f.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then(($)=>{return X.value=$,X});return X.value=G,X}});function wG(Q){return new E3({type:"transform",transform:Q})}var bG=q("ZodOptional",(Q,Y)=>{$W.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function s(Q){return new bG({type:"optional",innerType:Q})}var T3=q("ZodNullable",(Q,Y)=>{JW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function OG(Q){return new T3({type:"nullable",innerType:Q})}var S3=q("ZodDefault",(Q,Y)=>{zW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function R3(Q,Y){return new S3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var C3=q("ZodPrefault",(Q,Y)=>{HW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function k3(Q,Y){return new C3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var jG=q("ZodNonOptional",(Q,Y)=>{UW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function v3(Q,Y){return new jG({type:"nonoptional",innerType:Q,...f.normalizeParams(Y)})}var x3=q("ZodCatch",(Q,Y)=>{AW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function _3(Q,Y){return new x3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var y3=q("ZodPipe",(Q,Y)=>{BW.init(Q,Y),e.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function Y9(Q,Y){return new y3({type:"pipe",in:Q,out:Y})}var g3=q("ZodReadonly",(Q,Y)=>{KW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function u3(Q){return new g3({type:"readonly",innerType:Q})}var PG=q("ZodCustom",(Q,Y)=>{DW.init(Q,Y),e.init(Q,Y)});function IG(Q,Y){return dW(PG,Q??(()=>!0),Y)}function h3(Q,Y={}){return oW(PG,Q,Y)}function f3(Q){return tW(Q)}function G9(Q,Y){return Y9(wG(Q),Y)}b0(uQ());var $9="2025-11-25";var EG=[$9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],J1="io.modelcontextprotocol/related-task",q6="2.0",$0=IG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),TG=i([D(),m().int()]),SG=D(),FN=K0({ttl:i([m(),X9()]).optional(),pollInterval:m().optional()}),l3=b({ttl:m().optional()}),m3=b({taskId:D()}),J9=K0({progressToken:TG.optional(),[J1]:m3.optional()}),w0=b({_meta:J9.optional()}),H4=w0.extend({task:l3.optional()}),RG=(Q)=>H4.safeParse(Q).success,J0=b({method:D(),params:w0.loose().optional()}),j0=b({_meta:J9.optional()}),P0=b({method:D(),params:j0.loose().optional()}),z0=K0({_meta:J9.optional()}),F6=i([D(),m().int()]),CG=b({jsonrpc:j(q6),id:F6,...J0.shape}).strict(),z9=(Q)=>CG.safeParse(Q).success,kG=b({jsonrpc:j(q6),...P0.shape}).strict(),vG=(Q)=>kG.safeParse(Q).success,H9=b({jsonrpc:j(q6),id:F6,result:z0}).strict(),U4=(Q)=>H9.safeParse(Q).success;var g;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var U9=b({jsonrpc:j(q6),id:F6.optional(),error:b({code:m().int(),message:D(),data:t().optional()})}).strict();var xG=(Q)=>U9.safeParse(Q).success;var _G=i([CG,kG,H9,U9]),ON=i([H9,U9]),O6=z0.strict(),c3=j0.extend({requestId:F6.optional(),reason:D().optional()}),M6=P0.extend({method:j("notifications/cancelled"),params:c3}),p3=b({src:D(),mimeType:D().optional(),sizes:y(D()).optional(),theme:q0(["light","dark"]).optional()}),A4=b({icons:y(p3).optional()}),C1=b({name:D(),title:D().optional()}),yG=C1.extend({...C1.shape,...A4.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),i3=D6(b({applyDefaults:W0().optional()}),a(D(),t())),n3=G9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},D6(b({form:i3.optional(),url:$0.optional()}),a(D(),t()).optional())),r3=K0({list:$0.optional(),cancel:$0.optional(),requests:K0({sampling:K0({createMessage:$0.optional()}).optional(),elicitation:K0({create:$0.optional()}).optional()}).optional()}),d3=K0({list:$0.optional(),cancel:$0.optional(),requests:K0({tools:K0({call:$0.optional()}).optional()}).optional()}),o3=b({experimental:a(D(),$0).optional(),sampling:b({context:$0.optional(),tools:$0.optional()}).optional(),elicitation:n3.optional(),roots:b({listChanged:W0().optional()}).optional(),tasks:r3.optional()}),t3=w0.extend({protocolVersion:D(),capabilities:o3,clientInfo:yG}),A9=J0.extend({method:j("initialize"),params:t3});var a3=b({experimental:a(D(),$0).optional(),logging:$0.optional(),completions:$0.optional(),prompts:b({listChanged:W0().optional()}).optional(),resources:b({subscribe:W0().optional(),listChanged:W0().optional()}).optional(),tools:b({listChanged:W0().optional()}).optional(),tasks:d3.optional()}),s3=z0.extend({protocolVersion:D(),capabilities:a3,serverInfo:yG,instructions:D().optional()}),B9=P0.extend({method:j("notifications/initialized"),params:j0.optional()});var V6=J0.extend({method:j("ping"),params:w0.optional()}),e3=b({progress:m(),total:s(m()),message:s(D())}),QU=b({...j0.shape,...e3.shape,progressToken:TG}),Z6=P0.extend({method:j("notifications/progress"),params:QU}),YU=w0.extend({cursor:SG.optional()}),B4=J0.extend({params:YU.optional()}),K4=z0.extend({nextCursor:SG.optional()}),XU=q0(["working","input_required","completed","failed","cancelled"]),D4=b({taskId:D(),status:XU,ttl:i([m(),X9()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:s(m()),statusMessage:s(D())}),k1=z0.extend({task:D4}),WU=j0.merge(D4),L4=P0.extend({method:j("notifications/tasks/status"),params:WU}),N6=J0.extend({method:j("tasks/get"),params:w0.extend({taskId:D()})}),w6=z0.merge(D4),b6=J0.extend({method:j("tasks/result"),params:w0.extend({taskId:D()})}),MN=z0.loose(),j6=B4.extend({method:j("tasks/list")}),P6=K4.extend({tasks:y(D4)}),I6=J0.extend({method:j("tasks/cancel"),params:w0.extend({taskId:D()})}),gG=z0.merge(D4),uG=b({uri:D(),mimeType:s(D()),_meta:a(D(),t()).optional()}),hG=uG.extend({text:D()}),K9=D().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),fG=uG.extend({blob:K9}),q4=q0(["user","assistant"]),v1=b({audience:y(q4).optional(),priority:m().min(0).max(1).optional(),lastModified:z4.datetime({offset:!0}).optional()}),lG=b({...C1.shape,...A4.shape,uri:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),GU=b({...C1.shape,...A4.shape,uriTemplate:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),D9=B4.extend({method:j("resources/list")}),$U=K4.extend({resources:y(lG)}),JU=B4.extend({method:j("resources/templates/list")}),zU=K4.extend({resourceTemplates:y(GU)}),L9=w0.extend({uri:D()}),HU=L9,q9=J0.extend({method:j("resources/read"),params:HU}),UU=z0.extend({contents:y(i([hG,fG]))}),AU=P0.extend({method:j("notifications/resources/list_changed"),params:j0.optional()}),BU=L9,KU=J0.extend({method:j("resources/subscribe"),params:BU}),DU=L9,LU=J0.extend({method:j("resources/unsubscribe"),params:DU}),qU=j0.extend({uri:D()}),FU=P0.extend({method:j("notifications/resources/updated"),params:qU}),OU=b({name:D(),description:s(D()),required:s(W0())}),MU=b({...C1.shape,...A4.shape,description:s(D()),arguments:s(y(OU)),_meta:s(K0({}))}),VU=B4.extend({method:j("prompts/list")}),ZU=K4.extend({prompts:y(MU)}),NU=w0.extend({name:D(),arguments:a(D(),D()).optional()}),wU=J0.extend({method:j("prompts/get"),params:NU}),F9=b({type:j("text"),text:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),O9=b({type:j("image"),data:K9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),M9=b({type:j("audio"),data:K9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),bU=b({type:j("tool_use"),name:D(),id:D(),input:a(D(),t()),_meta:a(D(),t()).optional()}),jU=b({type:j("resource"),resource:i([hG,fG]),annotations:v1.optional(),_meta:a(D(),t()).optional()}),PU=lG.extend({type:j("resource_link")}),V9=i([F9,O9,M9,PU,jU]),IU=b({role:q4,content:V9}),EU=z0.extend({description:D().optional(),messages:y(IU)}),TU=P0.extend({method:j("notifications/prompts/list_changed"),params:j0.optional()}),SU=b({title:D().optional(),readOnlyHint:W0().optional(),destructiveHint:W0().optional(),idempotentHint:W0().optional(),openWorldHint:W0().optional()}),RU=b({taskSupport:q0(["required","optional","forbidden"]).optional()}),mG=b({...C1.shape,...A4.shape,description:D().optional(),inputSchema:b({type:j("object"),properties:a(D(),$0).optional(),required:y(D()).optional()}).catchall(t()),outputSchema:b({type:j("object"),properties:a(D(),$0).optional(),required:y(D()).optional()}).catchall(t()).optional(),annotations:SU.optional(),execution:RU.optional(),_meta:a(D(),t()).optional()}),Z9=B4.extend({method:j("tools/list")}),CU=K4.extend({tools:y(mG)}),E6=z0.extend({content:y(V9).default([]),structuredContent:a(D(),t()).optional(),isError:W0().optional()}),VN=E6.or(z0.extend({toolResult:t()})),kU=H4.extend({name:D(),arguments:a(D(),t()).optional()}),F4=J0.extend({method:j("tools/call"),params:kU}),vU=P0.extend({method:j("notifications/tools/list_changed"),params:j0.optional()}),ZN=b({autoRefresh:W0().default(!0),debounceMs:m().int().nonnegative().default(300)}),O4=q0(["debug","info","notice","warning","error","critical","alert","emergency"]),xU=w0.extend({level:O4}),N9=J0.extend({method:j("logging/setLevel"),params:xU}),_U=j0.extend({level:O4,logger:D().optional(),data:t()}),yU=P0.extend({method:j("notifications/message"),params:_U}),gU=b({name:D().optional()}),uU=b({hints:y(gU).optional(),costPriority:m().min(0).max(1).optional(),speedPriority:m().min(0).max(1).optional(),intelligencePriority:m().min(0).max(1).optional()}),hU=b({mode:q0(["auto","required","none"]).optional()}),fU=b({type:j("tool_result"),toolUseId:D().describe("The unique identifier for the corresponding tool call."),content:y(V9).default([]),structuredContent:b({}).loose().optional(),isError:W0().optional(),_meta:a(D(),t()).optional()}),lU=W9("type",[F9,O9,M9]),L6=W9("type",[F9,O9,M9,bU,fU]),mU=b({role:q4,content:i([L6,y(L6)]),_meta:a(D(),t()).optional()}),cU=H4.extend({messages:y(mU),modelPreferences:uU.optional(),systemPrompt:D().optional(),includeContext:q0(["none","thisServer","allServers"]).optional(),temperature:m().optional(),maxTokens:m().int(),stopSequences:y(D()).optional(),metadata:$0.optional(),tools:y(mG).optional(),toolChoice:hU.optional()}),pU=J0.extend({method:j("sampling/createMessage"),params:cU}),w9=z0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens"]).or(D())),role:q4,content:lU}),b9=z0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens","toolUse"]).or(D())),role:q4,content:i([L6,y(L6)])}),iU=b({type:j("boolean"),title:D().optional(),description:D().optional(),default:W0().optional()}),nU=b({type:j("string"),title:D().optional(),description:D().optional(),minLength:m().optional(),maxLength:m().optional(),format:q0(["email","uri","date","date-time"]).optional(),default:D().optional()}),rU=b({type:q0(["number","integer"]),title:D().optional(),description:D().optional(),minimum:m().optional(),maximum:m().optional(),default:m().optional()}),dU=b({type:j("string"),title:D().optional(),description:D().optional(),enum:y(D()),default:D().optional()}),oU=b({type:j("string"),title:D().optional(),description:D().optional(),oneOf:y(b({const:D(),title:D()})),default:D().optional()}),tU=b({type:j("string"),title:D().optional(),description:D().optional(),enum:y(D()),enumNames:y(D()).optional(),default:D().optional()}),aU=i([dU,oU]),sU=b({type:j("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:b({type:j("string"),enum:y(D())}),default:y(D()).optional()}),eU=b({type:j("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:b({anyOf:y(b({const:D(),title:D()}))}),default:y(D()).optional()}),QA=i([sU,eU]),YA=i([tU,aU,QA]),XA=i([YA,iU,nU,rU]),WA=H4.extend({mode:j("form").optional(),message:D(),requestedSchema:b({type:j("object"),properties:a(D(),XA),required:y(D()).optional()})}),GA=H4.extend({mode:j("url"),message:D(),elicitationId:D(),url:D().url()}),$A=i([WA,GA]),JA=J0.extend({method:j("elicitation/create"),params:$A}),zA=j0.extend({elicitationId:D()}),HA=P0.extend({method:j("notifications/elicitation/complete"),params:zA}),T6=z0.extend({action:q0(["accept","decline","cancel"]),content:G9((Q)=>Q===null?void 0:Q,a(D(),i([D(),m(),W0(),y(D())])).optional())}),UA=b({type:j("ref/resource"),uri:D()});var AA=b({type:j("ref/prompt"),name:D()}),BA=w0.extend({ref:i([AA,UA]),argument:b({name:D(),value:D()}),context:b({arguments:a(D(),D()).optional()}).optional()}),KA=J0.extend({method:j("completion/complete"),params:BA});var DA=z0.extend({completion:K0({values:y(D()).max(100),total:s(m().int()),hasMore:s(W0())})}),LA=b({uri:D().startsWith("file://"),name:D().optional(),_meta:a(D(),t()).optional()}),qA=J0.extend({method:j("roots/list"),params:w0.optional()}),j9=z0.extend({roots:y(LA)}),FA=P0.extend({method:j("notifications/roots/list_changed"),params:j0.optional()}),NN=i([V6,A9,KA,N9,wU,VU,D9,JU,q9,KU,LU,F4,Z9,N6,b6,j6,I6]),wN=i([M6,Z6,B9,FA,L4]),bN=i([O6,w9,b9,T6,j9,w6,P6,k1]),jN=i([V6,pU,JA,qA,N6,b6,j6,I6]),PN=i([M6,Z6,yU,FU,AU,vU,TU,L4,HA]),IN=i([O6,s3,DA,EU,ZU,$U,zU,UU,E6,CU,w6,P6,k1]);class k extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===g.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new cG(W.elicitations,Y)}return new k(Q,Y,X)}}class cG extends k{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(g.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function z1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var OA=Symbol("Let zodToJsonSchema decide on which parser to use");var $w=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function P9(Q){let X=B6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=aW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function I9(Q,Y){let X=$1(Q,Y);if(!X.success)throw X.error;return X.data}var bA=60000;class E9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(M6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(Z6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(V6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(N6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(b6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let z=J.message,H=z.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),J.type==="response")U(z);else{let A=z,B=new k(A.error.code,A.error.message,A.error.data);U(B)}else{let A=J.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let $=await this._taskStore.getTask(G,X.sessionId);if(!$)throw new k(g.InvalidParams,`Task not found: ${G}`);if(!z1($.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(z1($.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[J1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(j6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new k(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(I6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,`Task not found: ${Y.params.taskId}`);if(z1(W.status))throw new k(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new k(g.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof k)throw W;throw new k(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),k.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,$)=>{if(W?.(G,$),U4(G)||xG(G))this._onresponse(G);else if(z9(G))this._onrequest(G,$);else if(vG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=k.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[J1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let $=new AbortController;this._requestHandlerAbortControllers.set(Q.id,$);let J=RG(Q.params)?Q.params.task:void 0,z=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:$.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&z)await z.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:z,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if($.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if($.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:g.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let $=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&$&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(z){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),$(z);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),U4(Q))X(Q);else{let $=new k(Q.error.code,Q.error.message,Q.error.data);X($)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(U4(Q)&&Q.result&&typeof Q.result==="object"){let $=Q.result;if($.task&&typeof $.task==="object"){let J=$.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(U4(Q))W(Q);else{let $=k.fromError(Q.error.code,Q.error.message,Q.error.data);W($)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch($){yield{type:"error",error:$ instanceof k?$:new k(g.InternalError,String($))}}return}let G;try{let $=await this.request(Q,k1,X);if($.task)G=$.task.taskId,yield{type:"taskCreated",task:$.task};else throw new k(g.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},z1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new k(g.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new k(g.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let z=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,z)),X?.signal?.throwIfAborted()}}catch($){yield{type:"error",error:$ instanceof k?$:new k(g.InternalError,String($))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$,task:J,relatedTask:z}=X??{};return new Promise((H,U)=>{let A=(V)=>{U(V)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(V){A(V);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(J)K.params={...K.params,task:J};if(z)K.params={...K.params,_meta:{...K.params?._meta||{},[J1]:z}};let L=(V)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(V)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let S=V instanceof k?V:new k(g.RequestTimeout,String(V));U(S)};this._responseHandlers.set(B,(V)=>{if(X?.signal?.aborted)return;if(V instanceof Error)return U(V);try{let S=$1(Y,V.result);if(!S.success)U(S.error);else H(S.data)}catch(S){U(S)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??bA,M=()=>L(k.fromError(g.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let Z=z?.taskId;if(Z){let V=(S)=>{let E=this._responseHandlers.get(B);if(E)E(S);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,V),this._enqueueTaskMessage(Z,{type:"request",message:K,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(B),U(S)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:$}).catch((V)=>{this._cleanupTimeout(B),U(V)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},w6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},P6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},gG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[J1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[J1]:Y.relatedTask}}};this._transport?.send(J,Y).catch((z)=>this._onerror(z))});return}let $={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)$={...$,params:{...$.params,_meta:{...$.params?._meta||{},[J1]:Y.relatedTask}}};await this._transport.send($,Y)}setRequestHandler(Q,Y){let X=P9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let $=I9(Q,W);return Promise.resolve(Y($,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=P9(Q);this._notificationHandlers.set(X,(W)=>{let G=I9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&z9(W.message)){let G=W.message.id,$=this._requestResolvers.get(G);if($)$(new k(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new k(g.InvalidRequest,"Request cancelled"));return}let $=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout($),G(new k(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,$)=>{await X.storeTaskResult(W,G,$,Y);let J=await X.getTask(W,Y);if(J){let z=L4.parse({method:"notifications/tasks/status",params:J});if(await this.notification(z),z1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,$)=>{let J=await X.getTask(W,Y);if(!J)throw new k(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(z1(J.status))throw new k(g.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,$,Y);let z=await X.getTask(W,Y);if(z){let H=L4.parse({method:"notifications/tasks/status",params:z});if(await this.notification(H),z1(z.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function pG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function iG(Q,Y){let X={...Q};for(let W in Y){let G=W,$=Y[G];if($===void 0)continue;let J=X[G];if(pG(J)&&pG($))X[G]={...J,...$};else X[G]=$}return X}var w5=oY(NY(),1),b5=oY(N5(),1);function kM(){let Q=new w5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return b5.default(Q),Q}class CY{constructor(Q){this._ajv=Q??kM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class kY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function j5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function P5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class vY extends E9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(O4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new CY,this.setRequestHandler(A9,(X)=>this._oninitialize(X)),this.setNotificationHandler(B9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(N9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:$}=X.params,J=O4.safeParse($);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new kY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=iG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=B6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(R1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async(z,H)=>{let U=$1(F4,z);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new k(g.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y(z,H));if(A.task){let L=$1(k1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new k(g.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=$1(E6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new k(g.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){P5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;j5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:EG.includes(Y)?Y:$9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},O6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),$=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=$?Array.isArray($.content)?$.content:[$.content]:[],z=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!z)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(z){let H=new Set(J.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},b9,Y);return this.request({method:"sampling/createMessage",params:Q},w9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},T6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},T6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new k(g.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch($){if($ instanceof k)throw $;throw new k(g.InternalError,`Error validating elicitation response: ${$ instanceof Error?$.message:String($)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},j9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var I5={name:"@sequenzy/mcp",version:"0.0.54",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var xY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],E5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function xM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function f0(Q){let Y=Q?.trim();return Y?Y:void 0}function a0(Q){return encodeURIComponent(Q)}function Y0(Q,Y){return`${Q}${Y}`}function X0(Q,Y=""){return`/dashboard/company/${a0(Q)}${Y}`}function T5(Q,Y,X){return Y0(Q,`${X0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function _M(Q,Y){let X=xY.map((W)=>[W,Y?T5(Q,Y,W):""]);return Object.fromEntries(X)}function q1(Q={},Y){let X=xM(Y),W=f0(Q.companyId),G={},$=_M(X,W);if(!W)return{appUrl:X,routeTemplates:E5,settingsTabValues:xY,urls:G,settingsUrls:$};G.dashboard=Y0(X,X0(W)),G.campaigns=Y0(X,X0(W,"/campaign")),G.sequences=Y0(X,X0(W,"/sequences")),G.settings=Y0(X,X0(W,"/settings")),G.emails=Y0(X,X0(W,"/emails")),G.subscribers=Y0(X,X0(W,"/subscribers")),G.sentEmails=Y0(X,X0(W,"/sent-emails")),G.segments=Y0(X,X0(W,"/segments")),G.metrics=Y0(X,X0(W,"/metrics")),G.transactional=Y0(X,X0(W,"/transactional"));let J=f0(Q.campaignId);if(J)G.campaign=Y0(X,X0(W,`/campaign/${a0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let z=f0(Q.sequenceId);if(z)G.sequence=Y0(X,X0(W,`/sequences/${a0(z)}`));let H=f0(Q.emailId)??f0(Q.templateId);if(H)G.email=Y0(X,X0(W,`/emails/${a0(H)}`)),G.template=G.email;let U=f0(Q.transactionalId);if(U)G.transactionalEmail=Y0(X,X0(W,`/transactional/${a0(U)}`));let A=f0(Q.emailSendId);if(A)G.emailSend=Y0(X,X0(W,`/sent-emails/${a0(A)}`));let B=f0(Q.domainId);if(B)G.domain=Y0(X,X0(W,`/settings/domain/${a0(B)}`)),G.domainVerify=`${G.domain}/verify`;let K=f0(Q.status);if(K)G.campaignList=Y0(X,X0(W,`/campaign/list/${a0(K)}`)),G.sequenceList=Y0(X,X0(W,`/sequences/list/${a0(K)}`));let L=f0(Q.settingsTab);if(L)G.settingsTab=T5(X,W,L);return{appUrl:X,routeTemplates:E5,settingsTabValues:xY,urls:G,settingsUrls:$}}var S5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function R5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await F("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await F("GET","/api/v1/account"),W=Q1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await F("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await F("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await F("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await F("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await F("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await F("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await F("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await F("GET","/api/v1/tags");break;case"sequenzy://health":Y=await F("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=q1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:e0(Y)}]}}}import{readFileSync as yM,statSync as gM}from"node:fs";import{basename as uM}from"node:path";var m4="Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",i1="Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`.",u5="Sequenzy email blocks. Provide blocks or html for email steps. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items.",C5=500,qQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],FQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],uY={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"]},hM=Object.entries(uY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),k5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${hM}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},v5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function hY(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function fY(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=hY([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(fY):[]}}function fM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function lM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function x5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function mM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let $=X.slice(0,-2).join(":").trim(),J=X.at(-2),z=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return $&&Number.isInteger(H)&&H>0&&z!==void 0&&x5(z)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&x5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function cM(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function pM(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function iM(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function nM(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function rM(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function dM(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let z=X.indexOf(":");if(z===-1)return null;let H=X.substring(0,z).trim(),U=Number.parseInt(X.substring(z+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:$}=cM(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=pM(G);if(iM(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!nM(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!rM(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return $?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}function mY(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in uY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let $=uY[X];if(!$.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${$.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!fM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!lM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=mM(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=dM(X,W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((z)=>z.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function cY(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=mY(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(cY);return[]}function P1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function LQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function oM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=mY(G);return $?[$]:[]}):cY(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function tM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let $=mY(G);return $?[$]:[]}):X?cY(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}function aM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;return Y}function sM(Q){let Y=N(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map((z)=>typeof z==="string"?z.trim():"").filter((z)=>z.length>0)??[];if(W?.some((z)=>typeof z!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let $=N(Q,"fieldPath"),J=N(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...$!==void 0&&{fieldPath:$},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function eM(Q){P1("create_campaign",Q),LQ("create_campaign",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function QV(Q){if(N(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!B0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function YV(Q){P1("create_transactional_email",Q);let Y=N(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&N(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var _5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:u5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function XV(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function B0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function y5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function WV(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function GV(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],$=1,J=0,z=0,H=0;while(!0){let A=WV({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:$,pageSize:W}),B=await F("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);J=B.pagination?.total??B.subscribers.length,z=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?$>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;$+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:J,totalPages:z,fetchedPages:H},returned:U.length,truncated:X!==void 0&&J>0&&U.length<J}}function $V(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function c4(Q,Y){let X=$V(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function lY(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function _Y(Q,Y){return F("GET",lY(Q),void 0,Y)}function N(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function x(Q,Y,X){let W=N(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function s0(Q,Y,X,W){let G=N(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function yY(Q,Y,X,W){let G=x(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function p4(Q,Y,X,W,G){let $=Y[X];if($===void 0)return;if(typeof $!=="number"||!Number.isInteger($)||$<W||$>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return $}function g5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!FQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${FQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function gY(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let $=W.trim();if($.length>0)X.push($)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>C5)throw Error(`\`emails\` must include no more than ${C5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}var JV={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function zV(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return JV[Y]??null}var HV=104857600;async function UV(Q,Y){if(!eY())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=zV(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=gM(Q).size;if(W>HV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=yM(Q),$=await F("POST","/api/v1/products/delivery/upload-url",{filename:uM(Q),contentType:X,fileSizeBytes:W},Y),J=await fetch($.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:$.publicUrl,fileName:$.fileName,fileSizeBytes:W,mimeType:X}}async function h5(Q){let Y=N(Q,"companyId");if(Y)return Y;let X=Q1();if(X)return X;try{return(await F("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function i4(Q,Y){if(!B0(Q)||!Y)return Q;return{...Q,url:Y}}function f5(Q,Y){if(!B0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function DQ(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!B0(W))return W;let G=N(W,"id");if(!G)return W;let $=q1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return f5(W,$.urls);let J=X==="sequence"?$.urls.sequence:X==="template"?$.urls.email:$.urls.transactionalEmail;return i4(W,J)})}function AV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!B0(Y))return Y;let X=N(Y,"id");if(!X)return Y;let W=q1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var BV=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function KV(Q,Y,X){if(!B0(X)||!BV.has(Q))return X;let W=B0(X.company)?X.company:void 0,$=N(X,"selectedCompanyId")??N(X,"currentCompanyId")??N(X,"companyId")??(W?N(W,"id"):void 0)??(W?N(W,"companyId"):void 0)??await h5(Y);if(!$)return X;let J=B0(X.campaign)?X.campaign:void 0,z=B0(X.sequence)?X.sequence:void 0,H=B0(X.template)?X.template:void 0,U=B0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,A={companyId:$,campaignId:N(Y,"campaignId")??N(X,"campaignId")??(J?N(J,"id"):void 0),sequenceId:N(Y,"sequenceId")??N(X,"sequenceId")??(z?N(z,"id"):void 0),emailId:N(X,"templateId")??(H?N(H,"id"):void 0)??(U?N(U,"emailId"):void 0)??N(Y,"templateId"),transactionalId:N(Y,"transactionalId")??(U?N(U,"id"):void 0)??N(Y,"idOrSlug"),emailSendId:N(Y,"emailSendId")??N(X,"emailSendId")??(B0(X.emailSend)?N(X.emailSend,"id"):void 0),status:N(Y,"status")},B=q1(A),K=W?q1({companyId:$}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:AV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:DQ(X.campaigns,$,"campaign")},...Array.isArray(X.sequences)&&{sequences:DQ(X.sequences,$,"sequence")},...Array.isArray(X.templates)&&{templates:DQ(X.templates,$,"template")},...Array.isArray(X.transactional)&&{transactional:DQ(X.transactional,$,"transactional")},...W&&K!==void 0&&{company:{...W,url:K.urls.dashboard,settingsUrl:K.urls.settings}},...J&&B.urls.campaign!==void 0&&{campaign:f5(J,B.urls)},...z&&B.urls.sequence!==void 0&&{sequence:i4(z,B.urls.sequence)},...H&&B.urls.email!==void 0&&{template:i4(H,B.urls.email)},...U&&B.urls.transactionalEmail!==void 0&&{transactional:i4(U,B.urls.transactionalEmail)},...B0(X.emailSend)&&B.urls.emailSend!==void 0&&{emailSend:i4(X.emailSend,B.urls.emailSend)},appUrls:B.urls}}var l5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
30
30
  1. Call select_company first to choose which company to work with, OR
31
31
  2. Pass companyId explicitly in each tool call
32
32
 
package/dist/server.js CHANGED
@@ -25,7 +25,7 @@ var h5=Object.create;var{getPrototypeOf:f5,defineProperty:VQ,getOwnPropertyNames
25
25
  newResult[${T}] = ${_}.value;
26
26
  }
27
27
 
28
- `)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(E,_)=>S(K,E,_)},z,J=F1,$=!r4.jitless,U=$&&bQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!J(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if($&&U&&L?.async===!1&&L.jitless!==!0){if(!z)z=G(Y.shape);if(K=z(K,L),!A)return K;return r8([],O,K,L,B,Q)}return X(K,L)}});function H8(Q,Y,X,W){for(let z of Q)if(z.issues.length===0)return Y.value=z.value,Y;let G=Q.filter((z)=>!X1(z));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map((z)=>z.issues.map((J)=>S0(J,W,j0())))}),Y}var yQ=q("$ZodUnion",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),c(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),c(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),c(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map((z)=>z._zod.pattern);return new RegExp(`^(${G.map((z)=>a1(z.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,z)=>{if(X)return W(G,z);let J=!1,$=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},z);if(U instanceof Promise)$.push(U),J=!0;else{if(U.issues.length===0)return U;$.push(U)}}if(!J)return H8($,G,Q,z);return Promise.all($).then((H)=>{return H8(H,G,Q,z)})}}),d8=q("$ZodDiscriminatedUnion",(Q,Y)=>{yQ.init(Q,Y);let X=Q._zod.parse;c(Q._zod,"propValues",()=>{let G={};for(let z of Y.options){let J=z._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let[$,H]of Object.entries(J)){if(!G[$])G[$]=new Set;for(let U of H)G[$].add(U)}}return G});let W=E1(()=>{let G=Y.options,z=new Map;for(let J of G){let $=J._zod.propValues?.[Y.discriminator];if(!$||$.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of $){if(z.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);z.set(H,J)}}return z});Q._zod.parse=(G,z)=>{let J=G.value;if(!F1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let $=W.value.get(J?.[Y.discriminator]);if($)return $._zod.run(G,z);if(Y.unionFallback)return X(G,z);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),o8=q("$ZodIntersection",(Q,Y)=>{r.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,z=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if(z instanceof Promise||J instanceof Promise)return Promise.all([z,J]).then(([H,U])=>{return U8(X,H,U)});return U8(X,z,J)}});function xQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(Y1(Q)&&Y1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter((z)=>X.indexOf(z)!==-1),G={...Q,...Y};for(let z of W){let J=xQ(Q[z],Y[z]);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};G[z]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],z=Y[W],J=xQ(G,z);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function U8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(X1(Q))return Q;let W=xQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var t8=q("$ZodRecord",(Q,Y)=>{r.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!Y1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let z=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)z.push(U.then((A)=>{if(A.issues.length)X.issues.push(...p0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...p0(H,U.issues));X.value[H]=U.value}}let $;for(let H in G)if(!J.has(H))$=$??[],$.push(H);if($&&$.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:$})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let $=Y.keyType._zod.run({value:J,issues:[]},W);if($ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if($.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:$.issues.map((U)=>S0(U,W,j0())),input:J,path:[J],inst:Q}),X.value[$.value]=$.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)z.push(H.then((U)=>{if(U.issues.length)X.issues.push(...p0(J,U.issues));X.value[$.value]=U.value}));else{if(H.issues.length)X.issues.push(...p0(J,H.issues));X.value[$.value]=H.value}}}if(z.length)return Promise.all(z).then(()=>X);return X}});var a8=q("$ZodEnum",(Q,Y)=>{r.init(Q,Y);let X=wQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>PQ.has(typeof G)).map((G)=>typeof G==="string"?c0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,z)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),s8=q("$ZodLiteral",(Q,Y)=>{if(r.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?c0(X):X?c0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var e8=q("$ZodTransform",(Q,Y)=>{r.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new m0;return X.value=G,X}});function A8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var QW=q("$ZodOptional",(Q,Y)=>{r.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>A8(z,X.value));return A8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),YW=q("$ZodNullable",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)}|null)$`):void 0}),c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),XW=q("$ZodDefault",(Q,Y)=>{r.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>B8(z,Y));return B8(G,Y)}});function B8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var WW=q("$ZodPrefault",(Q,Y)=>{r.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),GW=q("$ZodNonOptional",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>K8(z,Q));return K8(G,Q)}});function K8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var zW=q("$ZodCatch",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>{if(X.value=z.value,z.issues.length)X.value=Y.catchValue({...X,error:{issues:z.issues.map((J)=>S0(J,W,j0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map((z)=>S0(z,W,j0()))},input:X.value}),X.issues=[];return X}});var JW=q("$ZodPipe",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"values",()=>Y.in._zod.values),c(Q._zod,"optin",()=>Y.in._zod.optin),c(Q._zod,"optout",()=>Y.out._zod.optout),c(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let z=Y.out._zod.run(X,W);if(z instanceof Promise)return z.then((J)=>X6(J,Y.in,W));return X6(z,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>X6(z,Y.out,W));return X6(G,Y.out,W)}});function X6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var $W=q("$ZodReadonly",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"propValues",()=>Y.innerType._zod.propValues),c(Q._zod,"values",()=>Y.innerType._zod.values),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(D8);return D8(G)}});function D8(Q){return Q.value=Object.freeze(Q.value),Q}var HW=q("$ZodCustom",(Q,Y)=>{G0.init(Q,Y),r.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then((z)=>L8(z,X,W,Q));L8(G,X,W,Q);return}});function L8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(T1(G))}}var kH=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},vH=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${kH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${t4(W.values[0])}`;return`Invalid option: expected one of ${n4(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",z=Y(W.origin);if(z)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${z.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",z=Y(W.origin);if(z)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${z.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${n4(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function gQ(){return{localeError:vH()}}var EV=Symbol("ZodOutput"),TV=Symbol("ZodInput");class UW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function xH(){return new UW}var W4=xH();function AW(Q,Y){return new Q({type:"string",...I(Y)})}function BW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...I(Y)})}function uQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...I(Y)})}function KW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...I(Y)})}function DW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(Y)})}function LW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(Y)})}function qW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(Y)})}function FW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...I(Y)})}function OW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...I(Y)})}function MW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(Y)})}function VW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...I(Y)})}function NW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...I(Y)})}function wW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...I(Y)})}function jW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(Y)})}function bW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(Y)})}function PW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(Y)})}function IW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(Y)})}function EW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(Y)})}function TW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...I(Y)})}function SW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...I(Y)})}function RW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...I(Y)})}function CW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...I(Y)})}function kW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(Y)})}function vW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...I(Y)})}function xW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...I(Y)})}function _W(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...I(Y)})}function yW(Q,Y){return new Q({type:"number",checks:[],...I(Y)})}function gW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...I(Y)})}function uW(Q,Y){return new Q({type:"boolean",...I(Y)})}function hW(Q,Y){return new Q({type:"null",...I(Y)})}function fW(Q){return new Q({type:"unknown"})}function lW(Q,Y){return new Q({type:"never",...I(Y)})}function z6(Q,Y){return new CQ({check:"less_than",...I(Y),value:Q,inclusive:!1})}function G4(Q,Y){return new CQ({check:"less_than",...I(Y),value:Q,inclusive:!0})}function J6(Q,Y){return new kQ({check:"greater_than",...I(Y),value:Q,inclusive:!1})}function z4(Q,Y){return new kQ({check:"greater_than",...I(Y),value:Q,inclusive:!0})}function $6(Q,Y){return new nX({check:"multiple_of",...I(Y),value:Q})}function H6(Q,Y){return new oX({check:"max_length",...I(Y),maximum:Q})}function S1(Q,Y){return new tX({check:"min_length",...I(Y),minimum:Q})}function U6(Q,Y){return new aX({check:"length_equals",...I(Y),length:Q})}function hQ(Q,Y){return new sX({check:"string_format",format:"regex",...I(Y),pattern:Q})}function fQ(Q){return new eX({check:"string_format",format:"lowercase",...I(Q)})}function lQ(Q){return new Q8({check:"string_format",format:"uppercase",...I(Q)})}function mQ(Q,Y){return new Y8({check:"string_format",format:"includes",...I(Y),includes:Q})}function cQ(Q,Y){return new X8({check:"string_format",format:"starts_with",...I(Y),prefix:Q})}function pQ(Q,Y){return new W8({check:"string_format",format:"ends_with",...I(Y),suffix:Q})}function O1(Q){return new G8({check:"overwrite",tx:Q})}function iQ(Q){return O1((Y)=>Y.normalize(Q))}function rQ(){return O1((Q)=>Q.trim())}function nQ(){return O1((Q)=>Q.toLowerCase())}function dQ(){return O1((Q)=>Q.toUpperCase())}function mW(Q,Y,X){return new Q({type:"array",element:Y,...I(X)})}function cW(Q,Y,X){let W=I(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function pW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...I(X)})}function iW(Q){let Y=_H((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(T1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(T1(G))}},Q(X.value,X)});return Y}function _H(Q,Y){let X=new G0({check:"custom",...I(Y)});return X._zod.check=Q,X}function R1(Q){return!!Q._zod}function W1(Q,Y){if(R1(Q))return Q4(Q,Y);return Q.safeParse(Y)}function A6(Q){if(!Q)return;let Y;if(R1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function rW(Q){if(R1(Q)){let z=Q._zod?.def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var $4={};rY($4,{time:()=>aQ,duration:()=>sQ,datetime:()=>oQ,date:()=>tQ,ZodISOTime:()=>oW,ZodISODuration:()=>tW,ZodISODateTime:()=>nW,ZodISODate:()=>dW});var nW=q("ZodISODateTime",(Q,Y)=>{I8.init(Q,Y),o.init(Q,Y)});function oQ(Q){return kW(nW,Q)}var dW=q("ZodISODate",(Q,Y)=>{E8.init(Q,Y),o.init(Q,Y)});function tQ(Q){return vW(dW,Q)}var oW=q("ZodISOTime",(Q,Y)=>{T8.init(Q,Y),o.init(Q,Y)});function aQ(Q){return xW(oW,Q)}var tW=q("ZodISODuration",(Q,Y)=>{S8.init(Q,Y),o.init(Q,Y)});function sQ(Q){return _W(tW,Q)}var aW=(Q,Y)=>{a4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>HX(Q,X)},flatten:{value:(X)=>$X(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,I1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,I1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},DN=q("ZodError",aW),Z0=q("ZodError",aW,{Parent:Error});var sW=s4(Z0),eW=e4(Z0),QG=e1(Z0),YG=Y4(Z0),XG=UX(Z0),WG=AX(Z0),GG=BX(Z0),zG=KX(Z0),JG=DX(Z0),$G=LX(Z0),HG=qX(Z0),UG=FX(Z0);var e=q("ZodType",(Q,Y)=>{return r.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(f.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>T0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>sW(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>QG(Q,X,W),Q.parseAsync=async(X,W)=>eW(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>YG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>XG(Q,X,W),Q.decode=(X,W)=>WG(Q,X,W),Q.encodeAsync=async(X,W)=>GG(Q,X,W),Q.decodeAsync=async(X,W)=>zG(Q,X,W),Q.safeEncode=(X,W)=>JG(Q,X,W),Q.safeDecode=(X,W)=>$G(Q,X,W),Q.safeEncodeAsync=async(X,W)=>HG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>UG(Q,X,W),Q.refine=(X,W)=>Q.check(C3(X,W)),Q.superRefine=(X)=>Q.check(k3(X)),Q.overwrite=(X)=>Q.check(O1(X)),Q.optional=()=>s(Q),Q.nullable=()=>KG(Q),Q.nullish=()=>s(KG(Q)),Q.nonoptional=(X)=>P3(Q,X),Q.array=()=>y(Q),Q.or=(X)=>i([Q,X]),Q.and=(X)=>K6(Q,X),Q.transform=(X)=>Q9(Q,OG(X)),Q.default=(X)=>w3(Q,X),Q.prefault=(X)=>b3(Q,X),Q.catch=(X)=>E3(Q,X),Q.pipe=(X)=>Q9(Q,X),Q.readonly=()=>R3(Q),Q.describe=(X)=>{let W=Q.clone();return W4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return W4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return W4.get(Q);let W=Q.clone();return W4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),DG=q("_ZodString",(Q,Y)=>{G6.init(Q,Y),e.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(hQ(...W)),Q.includes=(...W)=>Q.check(mQ(...W)),Q.startsWith=(...W)=>Q.check(cQ(...W)),Q.endsWith=(...W)=>Q.check(pQ(...W)),Q.min=(...W)=>Q.check(S1(...W)),Q.max=(...W)=>Q.check(H6(...W)),Q.length=(...W)=>Q.check(U6(...W)),Q.nonempty=(...W)=>Q.check(S1(1,...W)),Q.lowercase=(W)=>Q.check(fQ(W)),Q.uppercase=(W)=>Q.check(lQ(W)),Q.trim=()=>Q.check(rQ()),Q.normalize=(...W)=>Q.check(iQ(...W)),Q.toLowerCase=()=>Q.check(nQ()),Q.toUpperCase=()=>Q.check(dQ())}),pH=q("ZodString",(Q,Y)=>{G6.init(Q,Y),DG.init(Q,Y),Q.email=(X)=>Q.check(BW(iH,X)),Q.url=(X)=>Q.check(FW(rH,X)),Q.jwt=(X)=>Q.check(CW($3,X)),Q.emoji=(X)=>Q.check(OW(nH,X)),Q.guid=(X)=>Q.check(uQ(AG,X)),Q.uuid=(X)=>Q.check(KW(B6,X)),Q.uuidv4=(X)=>Q.check(DW(B6,X)),Q.uuidv6=(X)=>Q.check(LW(B6,X)),Q.uuidv7=(X)=>Q.check(qW(B6,X)),Q.nanoid=(X)=>Q.check(MW(dH,X)),Q.guid=(X)=>Q.check(uQ(AG,X)),Q.cuid=(X)=>Q.check(VW(oH,X)),Q.cuid2=(X)=>Q.check(NW(tH,X)),Q.ulid=(X)=>Q.check(ZW(aH,X)),Q.base64=(X)=>Q.check(TW(G3,X)),Q.base64url=(X)=>Q.check(SW(z3,X)),Q.xid=(X)=>Q.check(wW(sH,X)),Q.ksuid=(X)=>Q.check(jW(eH,X)),Q.ipv4=(X)=>Q.check(bW(Q3,X)),Q.ipv6=(X)=>Q.check(PW(Y3,X)),Q.cidrv4=(X)=>Q.check(IW(X3,X)),Q.cidrv6=(X)=>Q.check(EW(W3,X)),Q.e164=(X)=>Q.check(RW(J3,X)),Q.datetime=(X)=>Q.check(oQ(X)),Q.date=(X)=>Q.check(tQ(X)),Q.time=(X)=>Q.check(aQ(X)),Q.duration=(X)=>Q.check(sQ(X))});function D(Q){return AW(pH,Q)}var o=q("ZodStringFormat",(Q,Y)=>{n.init(Q,Y),DG.init(Q,Y)}),iH=q("ZodEmail",(Q,Y)=>{O8.init(Q,Y),o.init(Q,Y)});var AG=q("ZodGUID",(Q,Y)=>{q8.init(Q,Y),o.init(Q,Y)});var B6=q("ZodUUID",(Q,Y)=>{F8.init(Q,Y),o.init(Q,Y)});var rH=q("ZodURL",(Q,Y)=>{M8.init(Q,Y),o.init(Q,Y)});var nH=q("ZodEmoji",(Q,Y)=>{V8.init(Q,Y),o.init(Q,Y)});var dH=q("ZodNanoID",(Q,Y)=>{N8.init(Q,Y),o.init(Q,Y)});var oH=q("ZodCUID",(Q,Y)=>{Z8.init(Q,Y),o.init(Q,Y)});var tH=q("ZodCUID2",(Q,Y)=>{w8.init(Q,Y),o.init(Q,Y)});var aH=q("ZodULID",(Q,Y)=>{j8.init(Q,Y),o.init(Q,Y)});var sH=q("ZodXID",(Q,Y)=>{b8.init(Q,Y),o.init(Q,Y)});var eH=q("ZodKSUID",(Q,Y)=>{P8.init(Q,Y),o.init(Q,Y)});var Q3=q("ZodIPv4",(Q,Y)=>{R8.init(Q,Y),o.init(Q,Y)});var Y3=q("ZodIPv6",(Q,Y)=>{C8.init(Q,Y),o.init(Q,Y)});var X3=q("ZodCIDRv4",(Q,Y)=>{k8.init(Q,Y),o.init(Q,Y)});var W3=q("ZodCIDRv6",(Q,Y)=>{v8.init(Q,Y),o.init(Q,Y)});var G3=q("ZodBase64",(Q,Y)=>{_8.init(Q,Y),o.init(Q,Y)});var z3=q("ZodBase64URL",(Q,Y)=>{y8.init(Q,Y),o.init(Q,Y)});var J3=q("ZodE164",(Q,Y)=>{g8.init(Q,Y),o.init(Q,Y)});var $3=q("ZodJWT",(Q,Y)=>{u8.init(Q,Y),o.init(Q,Y)});var LG=q("ZodNumber",(Q,Y)=>{_Q.init(Q,Y),e.init(Q,Y),Q.gt=(W,G)=>Q.check(J6(W,G)),Q.gte=(W,G)=>Q.check(z4(W,G)),Q.min=(W,G)=>Q.check(z4(W,G)),Q.lt=(W,G)=>Q.check(z6(W,G)),Q.lte=(W,G)=>Q.check(G4(W,G)),Q.max=(W,G)=>Q.check(G4(W,G)),Q.int=(W)=>Q.check(BG(W)),Q.safe=(W)=>Q.check(BG(W)),Q.positive=(W)=>Q.check(J6(0,W)),Q.nonnegative=(W)=>Q.check(z4(0,W)),Q.negative=(W)=>Q.check(z6(0,W)),Q.nonpositive=(W)=>Q.check(G4(0,W)),Q.multipleOf=(W,G)=>Q.check($6(W,G)),Q.step=(W,G)=>Q.check($6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function m(Q){return yW(LG,Q)}var H3=q("ZodNumberFormat",(Q,Y)=>{h8.init(Q,Y),LG.init(Q,Y)});function BG(Q){return gW(H3,Q)}var U3=q("ZodBoolean",(Q,Y)=>{f8.init(Q,Y),e.init(Q,Y)});function W0(Q){return uW(U3,Q)}var A3=q("ZodNull",(Q,Y)=>{l8.init(Q,Y),e.init(Q,Y)});function Y9(Q){return hW(A3,Q)}var B3=q("ZodUnknown",(Q,Y)=>{m8.init(Q,Y),e.init(Q,Y)});function t(){return fW(B3)}var K3=q("ZodNever",(Q,Y)=>{c8.init(Q,Y),e.init(Q,Y)});function D3(Q){return lW(K3,Q)}var L3=q("ZodArray",(Q,Y)=>{p8.init(Q,Y),e.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(S1(X,W)),Q.nonempty=(X)=>Q.check(S1(1,X)),Q.max=(X,W)=>Q.check(H6(X,W)),Q.length=(X,W)=>Q.check(U6(X,W)),Q.unwrap=()=>Q.element});function y(Q,Y){return mW(L3,Q,Y)}var qG=q("ZodObject",(Q,Y)=>{n8.init(Q,Y),e.init(Q,Y),f.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>q0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:D3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return f.extend(Q,X)},Q.safeExtend=(X)=>{return f.safeExtend(Q,X)},Q.merge=(X)=>f.merge(Q,X),Q.pick=(X)=>f.pick(Q,X),Q.omit=(X)=>f.omit(Q,X),Q.partial=(...X)=>f.partial(MG,Q,X[0]),Q.required=(...X)=>f.required(VG,Q,X[0])});function j(Q,Y){let X={type:"object",shape:Q??{},...f.normalizeParams(Y)};return new qG(X)}function K0(Q,Y){return new qG({type:"object",shape:Q,catchall:t(),...f.normalizeParams(Y)})}var FG=q("ZodUnion",(Q,Y)=>{yQ.init(Q,Y),e.init(Q,Y),Q.options=Y.options});function i(Q,Y){return new FG({type:"union",options:Q,...f.normalizeParams(Y)})}var q3=q("ZodDiscriminatedUnion",(Q,Y)=>{FG.init(Q,Y),d8.init(Q,Y)});function X9(Q,Y,X){return new q3({type:"union",options:Y,discriminator:Q,...f.normalizeParams(X)})}var F3=q("ZodIntersection",(Q,Y)=>{o8.init(Q,Y),e.init(Q,Y)});function K6(Q,Y){return new F3({type:"intersection",left:Q,right:Y})}var O3=q("ZodRecord",(Q,Y)=>{t8.init(Q,Y),e.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function a(Q,Y,X){return new O3({type:"record",keyType:Q,valueType:Y,...f.normalizeParams(X)})}var eQ=q("ZodEnum",(Q,Y)=>{a8.init(Q,Y),e.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let z={};for(let J of W)if(X.has(J))z[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new eQ({...Y,checks:[],...f.normalizeParams(G),entries:z})},Q.exclude=(W,G)=>{let z={...Y.entries};for(let J of W)if(X.has(J))delete z[J];else throw Error(`Key ${J} not found in enum`);return new eQ({...Y,checks:[],...f.normalizeParams(G),entries:z})}});function q0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new eQ({type:"enum",entries:X,...f.normalizeParams(Y)})}var M3=q("ZodLiteral",(Q,Y)=>{s8.init(Q,Y),e.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new M3({type:"literal",values:Array.isArray(Q)?Q:[Q],...f.normalizeParams(Y)})}var V3=q("ZodTransform",(Q,Y)=>{e8.init(Q,Y),e.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);X.addIssue=(z)=>{if(typeof z==="string")X.issues.push(f.issue(z,X.value,Y));else{let J=z;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(f.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then((z)=>{return X.value=z,X});return X.value=G,X}});function OG(Q){return new V3({type:"transform",transform:Q})}var MG=q("ZodOptional",(Q,Y)=>{QW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function s(Q){return new MG({type:"optional",innerType:Q})}var N3=q("ZodNullable",(Q,Y)=>{YW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function KG(Q){return new N3({type:"nullable",innerType:Q})}var Z3=q("ZodDefault",(Q,Y)=>{XW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function w3(Q,Y){return new Z3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var j3=q("ZodPrefault",(Q,Y)=>{WW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function b3(Q,Y){return new j3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var VG=q("ZodNonOptional",(Q,Y)=>{GW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function P3(Q,Y){return new VG({type:"nonoptional",innerType:Q,...f.normalizeParams(Y)})}var I3=q("ZodCatch",(Q,Y)=>{zW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function E3(Q,Y){return new I3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var T3=q("ZodPipe",(Q,Y)=>{JW.init(Q,Y),e.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function Q9(Q,Y){return new T3({type:"pipe",in:Q,out:Y})}var S3=q("ZodReadonly",(Q,Y)=>{$W.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function R3(Q){return new S3({type:"readonly",innerType:Q})}var NG=q("ZodCustom",(Q,Y)=>{HW.init(Q,Y),e.init(Q,Y)});function ZG(Q,Y){return cW(NG,Q??(()=>!0),Y)}function C3(Q,Y={}){return pW(NG,Q,Y)}function k3(Q){return iW(Q)}function W9(Q,Y){return Q9(OG(Q),Y)}j0(gQ());var G9="2025-11-25";var wG=[G9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],G1="io.modelcontextprotocol/related-task",L6="2.0",z0=ZG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),jG=i([D(),m().int()]),bG=D(),HZ=K0({ttl:i([m(),Y9()]).optional(),pollInterval:m().optional()}),v3=j({ttl:m().optional()}),x3=j({taskId:D()}),z9=K0({progressToken:jG.optional(),[G1]:x3.optional()}),w0=j({_meta:z9.optional()}),H4=w0.extend({task:v3.optional()}),PG=(Q)=>H4.safeParse(Q).success,J0=j({method:D(),params:w0.loose().optional()}),b0=j({_meta:z9.optional()}),P0=j({method:D(),params:b0.loose().optional()}),$0=K0({_meta:z9.optional()}),q6=i([D(),m().int()]),IG=j({jsonrpc:b(L6),id:q6,...J0.shape}).strict(),J9=(Q)=>IG.safeParse(Q).success,EG=j({jsonrpc:b(L6),...P0.shape}).strict(),TG=(Q)=>EG.safeParse(Q).success,$9=j({jsonrpc:b(L6),id:q6,result:$0}).strict(),U4=(Q)=>$9.safeParse(Q).success;var g;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var H9=j({jsonrpc:b(L6),id:q6.optional(),error:j({code:m().int(),message:D(),data:t().optional()})}).strict();var SG=(Q)=>H9.safeParse(Q).success;var UZ=i([IG,EG,$9,H9]),AZ=i([$9,H9]),F6=$0.strict(),_3=b0.extend({requestId:q6.optional(),reason:D().optional()}),O6=P0.extend({method:b("notifications/cancelled"),params:_3}),y3=j({src:D(),mimeType:D().optional(),sizes:y(D()).optional(),theme:q0(["light","dark"]).optional()}),A4=j({icons:y(y3).optional()}),C1=j({name:D(),title:D().optional()}),RG=C1.extend({...C1.shape,...A4.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),g3=K6(j({applyDefaults:W0().optional()}),a(D(),t())),u3=W9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},K6(j({form:g3.optional(),url:z0.optional()}),a(D(),t()).optional())),h3=K0({list:z0.optional(),cancel:z0.optional(),requests:K0({sampling:K0({createMessage:z0.optional()}).optional(),elicitation:K0({create:z0.optional()}).optional()}).optional()}),f3=K0({list:z0.optional(),cancel:z0.optional(),requests:K0({tools:K0({call:z0.optional()}).optional()}).optional()}),l3=j({experimental:a(D(),z0).optional(),sampling:j({context:z0.optional(),tools:z0.optional()}).optional(),elicitation:u3.optional(),roots:j({listChanged:W0().optional()}).optional(),tasks:h3.optional()}),m3=w0.extend({protocolVersion:D(),capabilities:l3,clientInfo:RG}),U9=J0.extend({method:b("initialize"),params:m3});var c3=j({experimental:a(D(),z0).optional(),logging:z0.optional(),completions:z0.optional(),prompts:j({listChanged:W0().optional()}).optional(),resources:j({subscribe:W0().optional(),listChanged:W0().optional()}).optional(),tools:j({listChanged:W0().optional()}).optional(),tasks:f3.optional()}),p3=$0.extend({protocolVersion:D(),capabilities:c3,serverInfo:RG,instructions:D().optional()}),A9=P0.extend({method:b("notifications/initialized"),params:b0.optional()});var M6=J0.extend({method:b("ping"),params:w0.optional()}),i3=j({progress:m(),total:s(m()),message:s(D())}),r3=j({...b0.shape,...i3.shape,progressToken:jG}),V6=P0.extend({method:b("notifications/progress"),params:r3}),n3=w0.extend({cursor:bG.optional()}),B4=J0.extend({params:n3.optional()}),K4=$0.extend({nextCursor:bG.optional()}),d3=q0(["working","input_required","completed","failed","cancelled"]),D4=j({taskId:D(),status:d3,ttl:i([m(),Y9()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:s(m()),statusMessage:s(D())}),k1=$0.extend({task:D4}),o3=b0.merge(D4),L4=P0.extend({method:b("notifications/tasks/status"),params:o3}),N6=J0.extend({method:b("tasks/get"),params:w0.extend({taskId:D()})}),Z6=$0.merge(D4),w6=J0.extend({method:b("tasks/result"),params:w0.extend({taskId:D()})}),BZ=$0.loose(),j6=B4.extend({method:b("tasks/list")}),b6=K4.extend({tasks:y(D4)}),P6=J0.extend({method:b("tasks/cancel"),params:w0.extend({taskId:D()})}),CG=$0.merge(D4),kG=j({uri:D(),mimeType:s(D()),_meta:a(D(),t()).optional()}),vG=kG.extend({text:D()}),B9=D().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),xG=kG.extend({blob:B9}),q4=q0(["user","assistant"]),v1=j({audience:y(q4).optional(),priority:m().min(0).max(1).optional(),lastModified:$4.datetime({offset:!0}).optional()}),_G=j({...C1.shape,...A4.shape,uri:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),t3=j({...C1.shape,...A4.shape,uriTemplate:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),K9=B4.extend({method:b("resources/list")}),a3=K4.extend({resources:y(_G)}),s3=B4.extend({method:b("resources/templates/list")}),e3=K4.extend({resourceTemplates:y(t3)}),D9=w0.extend({uri:D()}),QU=D9,L9=J0.extend({method:b("resources/read"),params:QU}),YU=$0.extend({contents:y(i([vG,xG]))}),XU=P0.extend({method:b("notifications/resources/list_changed"),params:b0.optional()}),WU=D9,GU=J0.extend({method:b("resources/subscribe"),params:WU}),zU=D9,JU=J0.extend({method:b("resources/unsubscribe"),params:zU}),$U=b0.extend({uri:D()}),HU=P0.extend({method:b("notifications/resources/updated"),params:$U}),UU=j({name:D(),description:s(D()),required:s(W0())}),AU=j({...C1.shape,...A4.shape,description:s(D()),arguments:s(y(UU)),_meta:s(K0({}))}),BU=B4.extend({method:b("prompts/list")}),KU=K4.extend({prompts:y(AU)}),DU=w0.extend({name:D(),arguments:a(D(),D()).optional()}),LU=J0.extend({method:b("prompts/get"),params:DU}),q9=j({type:b("text"),text:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),F9=j({type:b("image"),data:B9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),O9=j({type:b("audio"),data:B9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),qU=j({type:b("tool_use"),name:D(),id:D(),input:a(D(),t()),_meta:a(D(),t()).optional()}),FU=j({type:b("resource"),resource:i([vG,xG]),annotations:v1.optional(),_meta:a(D(),t()).optional()}),OU=_G.extend({type:b("resource_link")}),M9=i([q9,F9,O9,OU,FU]),MU=j({role:q4,content:M9}),VU=$0.extend({description:D().optional(),messages:y(MU)}),NU=P0.extend({method:b("notifications/prompts/list_changed"),params:b0.optional()}),ZU=j({title:D().optional(),readOnlyHint:W0().optional(),destructiveHint:W0().optional(),idempotentHint:W0().optional(),openWorldHint:W0().optional()}),wU=j({taskSupport:q0(["required","optional","forbidden"]).optional()}),yG=j({...C1.shape,...A4.shape,description:D().optional(),inputSchema:j({type:b("object"),properties:a(D(),z0).optional(),required:y(D()).optional()}).catchall(t()),outputSchema:j({type:b("object"),properties:a(D(),z0).optional(),required:y(D()).optional()}).catchall(t()).optional(),annotations:ZU.optional(),execution:wU.optional(),_meta:a(D(),t()).optional()}),V9=B4.extend({method:b("tools/list")}),jU=K4.extend({tools:y(yG)}),I6=$0.extend({content:y(M9).default([]),structuredContent:a(D(),t()).optional(),isError:W0().optional()}),KZ=I6.or($0.extend({toolResult:t()})),bU=H4.extend({name:D(),arguments:a(D(),t()).optional()}),F4=J0.extend({method:b("tools/call"),params:bU}),PU=P0.extend({method:b("notifications/tools/list_changed"),params:b0.optional()}),DZ=j({autoRefresh:W0().default(!0),debounceMs:m().int().nonnegative().default(300)}),O4=q0(["debug","info","notice","warning","error","critical","alert","emergency"]),IU=w0.extend({level:O4}),N9=J0.extend({method:b("logging/setLevel"),params:IU}),EU=b0.extend({level:O4,logger:D().optional(),data:t()}),TU=P0.extend({method:b("notifications/message"),params:EU}),SU=j({name:D().optional()}),RU=j({hints:y(SU).optional(),costPriority:m().min(0).max(1).optional(),speedPriority:m().min(0).max(1).optional(),intelligencePriority:m().min(0).max(1).optional()}),CU=j({mode:q0(["auto","required","none"]).optional()}),kU=j({type:b("tool_result"),toolUseId:D().describe("The unique identifier for the corresponding tool call."),content:y(M9).default([]),structuredContent:j({}).loose().optional(),isError:W0().optional(),_meta:a(D(),t()).optional()}),vU=X9("type",[q9,F9,O9]),D6=X9("type",[q9,F9,O9,qU,kU]),xU=j({role:q4,content:i([D6,y(D6)]),_meta:a(D(),t()).optional()}),_U=H4.extend({messages:y(xU),modelPreferences:RU.optional(),systemPrompt:D().optional(),includeContext:q0(["none","thisServer","allServers"]).optional(),temperature:m().optional(),maxTokens:m().int(),stopSequences:y(D()).optional(),metadata:z0.optional(),tools:y(yG).optional(),toolChoice:CU.optional()}),yU=J0.extend({method:b("sampling/createMessage"),params:_U}),Z9=$0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens"]).or(D())),role:q4,content:vU}),w9=$0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens","toolUse"]).or(D())),role:q4,content:i([D6,y(D6)])}),gU=j({type:b("boolean"),title:D().optional(),description:D().optional(),default:W0().optional()}),uU=j({type:b("string"),title:D().optional(),description:D().optional(),minLength:m().optional(),maxLength:m().optional(),format:q0(["email","uri","date","date-time"]).optional(),default:D().optional()}),hU=j({type:q0(["number","integer"]),title:D().optional(),description:D().optional(),minimum:m().optional(),maximum:m().optional(),default:m().optional()}),fU=j({type:b("string"),title:D().optional(),description:D().optional(),enum:y(D()),default:D().optional()}),lU=j({type:b("string"),title:D().optional(),description:D().optional(),oneOf:y(j({const:D(),title:D()})),default:D().optional()}),mU=j({type:b("string"),title:D().optional(),description:D().optional(),enum:y(D()),enumNames:y(D()).optional(),default:D().optional()}),cU=i([fU,lU]),pU=j({type:b("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:j({type:b("string"),enum:y(D())}),default:y(D()).optional()}),iU=j({type:b("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:j({anyOf:y(j({const:D(),title:D()}))}),default:y(D()).optional()}),rU=i([pU,iU]),nU=i([mU,cU,rU]),dU=i([nU,gU,uU,hU]),oU=H4.extend({mode:b("form").optional(),message:D(),requestedSchema:j({type:b("object"),properties:a(D(),dU),required:y(D()).optional()})}),tU=H4.extend({mode:b("url"),message:D(),elicitationId:D(),url:D().url()}),aU=i([oU,tU]),sU=J0.extend({method:b("elicitation/create"),params:aU}),eU=b0.extend({elicitationId:D()}),QA=P0.extend({method:b("notifications/elicitation/complete"),params:eU}),E6=$0.extend({action:q0(["accept","decline","cancel"]),content:W9((Q)=>Q===null?void 0:Q,a(D(),i([D(),m(),W0(),y(D())])).optional())}),YA=j({type:b("ref/resource"),uri:D()});var XA=j({type:b("ref/prompt"),name:D()}),WA=w0.extend({ref:i([XA,YA]),argument:j({name:D(),value:D()}),context:j({arguments:a(D(),D()).optional()}).optional()}),GA=J0.extend({method:b("completion/complete"),params:WA});var zA=$0.extend({completion:K0({values:y(D()).max(100),total:s(m().int()),hasMore:s(W0())})}),JA=j({uri:D().startsWith("file://"),name:D().optional(),_meta:a(D(),t()).optional()}),$A=J0.extend({method:b("roots/list"),params:w0.optional()}),j9=$0.extend({roots:y(JA)}),HA=P0.extend({method:b("notifications/roots/list_changed"),params:b0.optional()}),LZ=i([M6,U9,GA,N9,LU,BU,K9,s3,L9,GU,JU,F4,V9,N6,w6,j6,P6]),qZ=i([O6,V6,A9,HA,L4]),FZ=i([F6,Z9,w9,E6,j9,Z6,b6,k1]),OZ=i([M6,yU,sU,$A,N6,w6,j6,P6]),MZ=i([O6,V6,TU,HU,XU,PU,NU,L4,QA]),VZ=i([F6,p3,zA,VU,KU,a3,e3,YU,I6,jU,Z6,b6,k1]);class k extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===g.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new gG(W.elicitations,Y)}return new k(Q,Y,X)}}class gG extends k{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(g.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function z1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var UA=Symbol("Let zodToJsonSchema decide on which parser to use");var sZ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b9(Q){let X=A6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=rW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function P9(Q,Y){let X=W1(Q,Y);if(!X.success)throw X.error;return X.data}var qA=60000;class I9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(O6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(V6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(M6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(N6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(w6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let $=J.message,H=$.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),J.type==="response")U($);else{let A=$,B=new k(A.error.code,A.error.message,A.error.data);U(B)}else{let A=J.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let z=await this._taskStore.getTask(G,X.sessionId);if(!z)throw new k(g.InvalidParams,`Task not found: ${G}`);if(!z1(z.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(z1(z.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[G1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(j6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new k(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(P6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,`Task not found: ${Y.params.taskId}`);if(z1(W.status))throw new k(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new k(g.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof k)throw W;throw new k(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),k.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,z)=>{if(W?.(G,z),U4(G)||SG(G))this._onresponse(G);else if(J9(G))this._onrequest(G,z);else if(TG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=k.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[G1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let z=new AbortController;this._requestHandlerAbortControllers.set(Q.id,z);let J=PG(Q.params)?Q.params.task:void 0,$=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:z.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&$)await $.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:$,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if(z.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if(z.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:g.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let z=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&z&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch($){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),z($);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),U4(Q))X(Q);else{let z=new k(Q.error.code,Q.error.message,Q.error.data);X(z)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(U4(Q)&&Q.result&&typeof Q.result==="object"){let z=Q.result;if(z.task&&typeof z.task==="object"){let J=z.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(U4(Q))W(Q);else{let z=k.fromError(Q.error.code,Q.error.message,Q.error.data);W(z)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch(z){yield{type:"error",error:z instanceof k?z:new k(g.InternalError,String(z))}}return}let G;try{let z=await this.request(Q,k1,X);if(z.task)G=z.task.taskId,yield{type:"taskCreated",task:z.task};else throw new k(g.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},z1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new k(g.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new k(g.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let $=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,$)),X?.signal?.throwIfAborted()}}catch(z){yield{type:"error",error:z instanceof k?z:new k(g.InternalError,String(z))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z,task:J,relatedTask:$}=X??{};return new Promise((H,U)=>{let A=(V)=>{U(V)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(V){A(V);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(J)K.params={...K.params,task:J};if($)K.params={...K.params,_meta:{...K.params?._meta||{},[G1]:$}};let L=(V)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(V)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let S=V instanceof k?V:new k(g.RequestTimeout,String(V));U(S)};this._responseHandlers.set(B,(V)=>{if(X?.signal?.aborted)return;if(V instanceof Error)return U(V);try{let S=W1(Y,V.result);if(!S.success)U(S.error);else H(S.data)}catch(S){U(S)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??qA,M=()=>L(k.fromError(g.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=$?.taskId;if(N){let V=(S)=>{let E=this._responseHandlers.get(B);if(E)E(S);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,V),this._enqueueTaskMessage(N,{type:"request",message:K,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(B),U(S)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((V)=>{this._cleanupTimeout(B),U(V)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},Z6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},b6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},CG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[G1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[G1]:Y.relatedTask}}};this._transport?.send(J,Y).catch(($)=>this._onerror($))});return}let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[G1]:Y.relatedTask}}};await this._transport.send(z,Y)}setRequestHandler(Q,Y){let X=b9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let z=P9(Q,W);return Promise.resolve(Y(z,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=b9(Q);this._notificationHandlers.set(X,(W)=>{let G=P9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&J9(W.message)){let G=W.message.id,z=this._requestResolvers.get(G);if(z)z(new k(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new k(g.InvalidRequest,"Request cancelled"));return}let z=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout(z),G(new k(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,z)=>{await X.storeTaskResult(W,G,z,Y);let J=await X.getTask(W,Y);if(J){let $=L4.parse({method:"notifications/tasks/status",params:J});if(await this.notification($),z1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,z)=>{let J=await X.getTask(W,Y);if(!J)throw new k(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(z1(J.status))throw new k(g.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,z,Y);let $=await X.getTask(W,Y);if($){let H=L4.parse({method:"notifications/tasks/status",params:$});if(await this.notification(H),z1($.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function uG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function hG(Q,Y){let X={...Q};for(let W in Y){let G=W,z=Y[G];if(z===void 0)continue;let J=X[G];if(uG(J)&&uG(z))X[G]={...J,...z};else X[G]=z}return X}var F5=iY(NY(),1),O5=iY(q5(),1);function bM(){let Q=new F5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return O5.default(Q),Q}class RY{constructor(Q){this._ajv=Q??bM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class CY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function M5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function V5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class kY extends I9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(O4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new RY,this.setRequestHandler(U9,(X)=>this._oninitialize(X)),this.setNotificationHandler(A9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(N9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:z}=X.params,J=O4.safeParse(z);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new CY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=hG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=A6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(R1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async($,H)=>{let U=W1(F4,$);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new k(g.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y($,H));if(A.task){let L=W1(k1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new k(g.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=W1(I6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new k(g.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){V5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;M5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:wG.includes(Y)?Y:G9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},F6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),z=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=z?Array.isArray(z.content)?z.content:[z.content]:[],$=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!$)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if($){let H=new Set(J.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},w9,Y);return this.request({method:"sampling/createMessage",params:Q},Z9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},E6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},E6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new k(g.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(z){if(z instanceof k)throw z;throw new k(g.InternalError,`Error validating elicitation response: ${z instanceof Error?z.message:String(z)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},j9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var N5={name:"@sequenzy/mcp",version:"0.0.53",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var vY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],Z5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function IM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function f0(Q){let Y=Q?.trim();return Y?Y:void 0}function a0(Q){return encodeURIComponent(Q)}function Y0(Q,Y){return`${Q}${Y}`}function X0(Q,Y=""){return`/dashboard/company/${a0(Q)}${Y}`}function w5(Q,Y,X){return Y0(Q,`${X0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function EM(Q,Y){let X=vY.map((W)=>[W,Y?w5(Q,Y,W):""]);return Object.fromEntries(X)}function D1(Q={},Y){let X=IM(Y),W=f0(Q.companyId),G={},z=EM(X,W);if(!W)return{appUrl:X,routeTemplates:Z5,settingsTabValues:vY,urls:G,settingsUrls:z};G.dashboard=Y0(X,X0(W)),G.campaigns=Y0(X,X0(W,"/campaign")),G.sequences=Y0(X,X0(W,"/sequences")),G.settings=Y0(X,X0(W,"/settings")),G.emails=Y0(X,X0(W,"/emails")),G.subscribers=Y0(X,X0(W,"/subscribers")),G.sentEmails=Y0(X,X0(W,"/sent-emails")),G.segments=Y0(X,X0(W,"/segments")),G.metrics=Y0(X,X0(W,"/metrics")),G.transactional=Y0(X,X0(W,"/transactional"));let J=f0(Q.campaignId);if(J)G.campaign=Y0(X,X0(W,`/campaign/${a0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let $=f0(Q.sequenceId);if($)G.sequence=Y0(X,X0(W,`/sequences/${a0($)}`));let H=f0(Q.emailId)??f0(Q.templateId);if(H)G.email=Y0(X,X0(W,`/emails/${a0(H)}`)),G.template=G.email;let U=f0(Q.transactionalId);if(U)G.transactionalEmail=Y0(X,X0(W,`/transactional/${a0(U)}`));let A=f0(Q.emailSendId);if(A)G.emailSend=Y0(X,X0(W,`/sent-emails/${a0(A)}`));let B=f0(Q.domainId);if(B)G.domain=Y0(X,X0(W,`/settings/domain/${a0(B)}`)),G.domainVerify=`${G.domain}/verify`;let K=f0(Q.status);if(K)G.campaignList=Y0(X,X0(W,`/campaign/list/${a0(K)}`)),G.sequenceList=Y0(X,X0(W,`/sequences/list/${a0(K)}`));let L=f0(Q.settingsTab);if(L)G.settingsTab=w5(X,W,L);return{appUrl:X,routeTemplates:Z5,settingsTabValues:vY,urls:G,settingsUrls:z}}var j5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function b5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await F("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await F("GET","/api/v1/account"),W=q1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await F("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await F("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await F("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await F("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await F("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await F("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await F("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await F("GET","/api/v1/tags");break;case"sequenzy://health":Y=await F("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=D1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:P1(Y)}]}}}import{readFileSync as TM,statSync as SM}from"node:fs";import{basename as RM}from"node:path";var m4="Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",i1="Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`.",k5="Sequenzy email blocks. Provide blocks or html for email steps. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items.",P5=500,LQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],qQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],gY={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"]},CM=Object.entries(gY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),I5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${CM}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},E5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function uY(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function hY(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=uY([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(hY):[]}}function kM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function vM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function T5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function xM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let z=X.slice(0,-2).join(":").trim(),J=X.at(-2),$=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return z&&Number.isInteger(H)&&H>0&&$!==void 0&&T5($)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&T5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function _M(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function yM(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function gM(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function uM(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function hM(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function fM(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let $=X.indexOf(":");if($===-1)return null;let H=X.substring(0,$).trim(),U=Number.parseInt(X.substring($+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:z}=_M(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=yM(G);if(gM(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!uM(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!hM(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return z?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}function lY(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in gY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let z=gY[X];if(!z.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${z.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!kM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!vM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=xM(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=fM(X,W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map(($)=>$.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function mY(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=lY(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(mY);return[]}function b1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function DQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function lM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let z=lY(G);return z?[z]:[]}):mY(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function mM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let z=lY(G);return z?[z]:[]}):X?mY(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}function cM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;return Y}function pM(Q){let Y=Z(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map(($)=>typeof $==="string"?$.trim():"").filter(($)=>$.length>0)??[];if(W?.some(($)=>typeof $!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let z=Z(Q,"fieldPath"),J=Z(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...z!==void 0&&{fieldPath:z},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function iM(Q){b1("create_campaign",Q),DQ("create_campaign",Q);let Y=Z(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&Z(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function rM(Q){if(Z(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!B0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function nM(Q){b1("create_transactional_email",Q);let Y=Z(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&Z(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var S5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:k5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function dM(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function B0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function R5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function oM(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function tM(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],z=1,J=0,$=0,H=0;while(!0){let A=oM({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:z,pageSize:W}),B=await F("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);J=B.pagination?.total??B.subscribers.length,$=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?z>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;z+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:J,totalPages:$,fetchedPages:H},returned:U.length,truncated:X!==void 0&&J>0&&U.length<J}}function aM(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function c4(Q,Y){let X=aM(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function fY(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function xY(Q,Y){return F("GET",fY(Q),void 0,Y)}function Z(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function x(Q,Y,X){let W=Z(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function s0(Q,Y,X,W){let G=Z(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function _Y(Q,Y,X,W){let G=x(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function p4(Q,Y,X,W,G){let z=Y[X];if(z===void 0)return;if(typeof z!=="number"||!Number.isInteger(z)||z<W||z>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return z}function C5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!qQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${qQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function yY(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let z=W.trim();if(z.length>0)X.push(z)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>P5)throw Error(`\`emails\` must include no more than ${P5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}var sM={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function eM(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return sM[Y]??null}var QV=104857600;async function YV(Q,Y){if(!dY())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=eM(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=SM(Q).size;if(W>QV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=TM(Q),z=await F("POST","/api/v1/products/delivery/upload-url",{filename:RM(Q),contentType:X,fileSizeBytes:W},Y),J=await fetch(z.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:z.publicUrl,fileName:z.fileName,fileSizeBytes:W,mimeType:X}}async function v5(Q){let Y=Z(Q,"companyId");if(Y)return Y;let X=q1();if(X)return X;try{return(await F("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function i4(Q,Y){if(!B0(Q)||!Y)return Q;return{...Q,url:Y}}function x5(Q,Y){if(!B0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function KQ(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!B0(W))return W;let G=Z(W,"id");if(!G)return W;let z=D1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return x5(W,z.urls);let J=X==="sequence"?z.urls.sequence:X==="template"?z.urls.email:z.urls.transactionalEmail;return i4(W,J)})}function XV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!B0(Y))return Y;let X=Z(Y,"id");if(!X)return Y;let W=D1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var WV=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function GV(Q,Y,X){if(!B0(X)||!WV.has(Q))return X;let W=B0(X.company)?X.company:void 0,z=Z(X,"selectedCompanyId")??Z(X,"currentCompanyId")??Z(X,"companyId")??(W?Z(W,"id"):void 0)??(W?Z(W,"companyId"):void 0)??await v5(Y);if(!z)return X;let J=B0(X.campaign)?X.campaign:void 0,$=B0(X.sequence)?X.sequence:void 0,H=B0(X.template)?X.template:void 0,U=B0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,A={companyId:z,campaignId:Z(Y,"campaignId")??Z(X,"campaignId")??(J?Z(J,"id"):void 0),sequenceId:Z(Y,"sequenceId")??Z(X,"sequenceId")??($?Z($,"id"):void 0),emailId:Z(X,"templateId")??(H?Z(H,"id"):void 0)??(U?Z(U,"emailId"):void 0)??Z(Y,"templateId"),transactionalId:Z(Y,"transactionalId")??(U?Z(U,"id"):void 0)??Z(Y,"idOrSlug"),emailSendId:Z(Y,"emailSendId")??Z(X,"emailSendId")??(B0(X.emailSend)?Z(X.emailSend,"id"):void 0),status:Z(Y,"status")},B=D1(A),K=W?D1({companyId:z}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:XV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:KQ(X.campaigns,z,"campaign")},...Array.isArray(X.sequences)&&{sequences:KQ(X.sequences,z,"sequence")},...Array.isArray(X.templates)&&{templates:KQ(X.templates,z,"template")},...Array.isArray(X.transactional)&&{transactional:KQ(X.transactional,z,"transactional")},...W&&K!==void 0&&{company:{...W,url:K.urls.dashboard,settingsUrl:K.urls.settings}},...J&&B.urls.campaign!==void 0&&{campaign:x5(J,B.urls)},...$&&B.urls.sequence!==void 0&&{sequence:i4($,B.urls.sequence)},...H&&B.urls.email!==void 0&&{template:i4(H,B.urls.email)},...U&&B.urls.transactionalEmail!==void 0&&{transactional:i4(U,B.urls.transactionalEmail)},...B0(X.emailSend)&&B.urls.emailSend!==void 0&&{emailSend:i4(X.emailSend,B.urls.emailSend)},appUrls:B.urls}}var _5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
28
+ `)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(E,_)=>S(K,E,_)},z,J=F1,$=!r4.jitless,U=$&&bQ.value,A=Y.catchall,B;Q._zod.parse=(K,L)=>{B??(B=W.value);let O=K.value;if(!J(O))return K.issues.push({expected:"object",code:"invalid_type",input:O,inst:Q}),K;if($&&U&&L?.async===!1&&L.jitless!==!0){if(!z)z=G(Y.shape);if(K=z(K,L),!A)return K;return r8([],O,K,L,B,Q)}return X(K,L)}});function H8(Q,Y,X,W){for(let z of Q)if(z.issues.length===0)return Y.value=z.value,Y;let G=Q.filter((z)=>!X1(z));if(G.length===1)return Y.value=G[0].value,G[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:X,errors:Q.map((z)=>z.issues.map((J)=>S0(J,W,j0())))}),Y}var yQ=q("$ZodUnion",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"optin",()=>Y.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),c(Q._zod,"optout",()=>Y.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),c(Q._zod,"values",()=>{if(Y.options.every((G)=>G._zod.values))return new Set(Y.options.flatMap((G)=>Array.from(G._zod.values)));return}),c(Q._zod,"pattern",()=>{if(Y.options.every((G)=>G._zod.pattern)){let G=Y.options.map((z)=>z._zod.pattern);return new RegExp(`^(${G.map((z)=>a1(z.source)).join("|")})$`)}return});let X=Y.options.length===1,W=Y.options[0]._zod.run;Q._zod.parse=(G,z)=>{if(X)return W(G,z);let J=!1,$=[];for(let H of Y.options){let U=H._zod.run({value:G.value,issues:[]},z);if(U instanceof Promise)$.push(U),J=!0;else{if(U.issues.length===0)return U;$.push(U)}}if(!J)return H8($,G,Q,z);return Promise.all($).then((H)=>{return H8(H,G,Q,z)})}}),d8=q("$ZodDiscriminatedUnion",(Q,Y)=>{yQ.init(Q,Y);let X=Q._zod.parse;c(Q._zod,"propValues",()=>{let G={};for(let z of Y.options){let J=z._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(z)}"`);for(let[$,H]of Object.entries(J)){if(!G[$])G[$]=new Set;for(let U of H)G[$].add(U)}}return G});let W=E1(()=>{let G=Y.options,z=new Map;for(let J of G){let $=J._zod.propValues?.[Y.discriminator];if(!$||$.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let H of $){if(z.has(H))throw Error(`Duplicate discriminator value "${String(H)}"`);z.set(H,J)}}return z});Q._zod.parse=(G,z)=>{let J=G.value;if(!F1(J))return G.issues.push({code:"invalid_type",expected:"object",input:J,inst:Q}),G;let $=W.value.get(J?.[Y.discriminator]);if($)return $._zod.run(G,z);if(Y.unionFallback)return X(G,z);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,input:J,path:[Y.discriminator],inst:Q}),G}}),o8=q("$ZodIntersection",(Q,Y)=>{r.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value,z=Y.left._zod.run({value:G,issues:[]},W),J=Y.right._zod.run({value:G,issues:[]},W);if(z instanceof Promise||J instanceof Promise)return Promise.all([z,J]).then(([H,U])=>{return U8(X,H,U)});return U8(X,z,J)}});function xQ(Q,Y){if(Q===Y)return{valid:!0,data:Q};if(Q instanceof Date&&Y instanceof Date&&+Q===+Y)return{valid:!0,data:Q};if(Y1(Q)&&Y1(Y)){let X=Object.keys(Y),W=Object.keys(Q).filter((z)=>X.indexOf(z)!==-1),G={...Q,...Y};for(let z of W){let J=xQ(Q[z],Y[z]);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};G[z]=J.data}return{valid:!0,data:G}}if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let X=[];for(let W=0;W<Q.length;W++){let G=Q[W],z=Y[W],J=xQ(G,z);if(!J.valid)return{valid:!1,mergeErrorPath:[W,...J.mergeErrorPath]};X.push(J.data)}return{valid:!0,data:X}}return{valid:!1,mergeErrorPath:[]}}function U8(Q,Y,X){if(Y.issues.length)Q.issues.push(...Y.issues);if(X.issues.length)Q.issues.push(...X.issues);if(X1(Q))return Q;let W=xQ(Y.value,X.value);if(!W.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(W.mergeErrorPath)}`);return Q.value=W.data,Q}var t8=q("$ZodRecord",(Q,Y)=>{r.init(Q,Y),Q._zod.parse=(X,W)=>{let G=X.value;if(!Y1(G))return X.issues.push({expected:"record",code:"invalid_type",input:G,inst:Q}),X;let z=[];if(Y.keyType._zod.values){let J=Y.keyType._zod.values;X.value={};for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){let U=Y.valueType._zod.run({value:G[H],issues:[]},W);if(U instanceof Promise)z.push(U.then((A)=>{if(A.issues.length)X.issues.push(...p0(H,A.issues));X.value[H]=A.value}));else{if(U.issues.length)X.issues.push(...p0(H,U.issues));X.value[H]=U.value}}let $;for(let H in G)if(!J.has(H))$=$??[],$.push(H);if($&&$.length>0)X.issues.push({code:"unrecognized_keys",input:G,inst:Q,keys:$})}else{X.value={};for(let J of Reflect.ownKeys(G)){if(J==="__proto__")continue;let $=Y.keyType._zod.run({value:J,issues:[]},W);if($ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if($.issues.length){X.issues.push({code:"invalid_key",origin:"record",issues:$.issues.map((U)=>S0(U,W,j0())),input:J,path:[J],inst:Q}),X.value[$.value]=$.value;continue}let H=Y.valueType._zod.run({value:G[J],issues:[]},W);if(H instanceof Promise)z.push(H.then((U)=>{if(U.issues.length)X.issues.push(...p0(J,U.issues));X.value[$.value]=U.value}));else{if(H.issues.length)X.issues.push(...p0(J,H.issues));X.value[$.value]=H.value}}}if(z.length)return Promise.all(z).then(()=>X);return X}});var a8=q("$ZodEnum",(Q,Y)=>{r.init(Q,Y);let X=wQ(Y.entries),W=new Set(X);Q._zod.values=W,Q._zod.pattern=new RegExp(`^(${X.filter((G)=>PQ.has(typeof G)).map((G)=>typeof G==="string"?c0(G):G.toString()).join("|")})$`),Q._zod.parse=(G,z)=>{let J=G.value;if(W.has(J))return G;return G.issues.push({code:"invalid_value",values:X,input:J,inst:Q}),G}}),s8=q("$ZodLiteral",(Q,Y)=>{if(r.init(Q,Y),Y.values.length===0)throw Error("Cannot create literal schema with no valid values");Q._zod.values=new Set(Y.values),Q._zod.pattern=new RegExp(`^(${Y.values.map((X)=>typeof X==="string"?c0(X):X?c0(X.toString()):String(X)).join("|")})$`),Q._zod.parse=(X,W)=>{let G=X.value;if(Q._zod.values.has(G))return X;return X.issues.push({code:"invalid_value",values:Y.values,input:G,inst:Q}),X}});var e8=q("$ZodTransform",(Q,Y)=>{r.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);let G=Y.transform(X.value,X);if(W.async)return(G instanceof Promise?G:Promise.resolve(G)).then((J)=>{return X.value=J,X});if(G instanceof Promise)throw new m0;return X.value=G,X}});function A8(Q,Y){if(Q.issues.length&&Y===void 0)return{issues:[],value:void 0};return Q}var QW=q("$ZodOptional",(Q,Y)=>{r.init(Q,Y),Q._zod.optin="optional",Q._zod.optout="optional",c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,void 0]):void 0}),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)})?$`):void 0}),Q._zod.parse=(X,W)=>{if(Y.innerType._zod.optin==="optional"){let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>A8(z,X.value));return A8(G,X.value)}if(X.value===void 0)return X;return Y.innerType._zod.run(X,W)}}),YW=q("$ZodNullable",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"pattern",()=>{let X=Y.innerType._zod.pattern;return X?new RegExp(`^(${a1(X.source)}|null)$`):void 0}),c(Q._zod,"values",()=>{return Y.innerType._zod.values?new Set([...Y.innerType._zod.values,null]):void 0}),Q._zod.parse=(X,W)=>{if(X.value===null)return X;return Y.innerType._zod.run(X,W)}}),XW=q("$ZodDefault",(Q,Y)=>{r.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)return X.value=Y.defaultValue,X;let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>B8(z,Y));return B8(G,Y)}});function B8(Q,Y){if(Q.value===void 0)Q.value=Y.defaultValue;return Q}var WW=q("$ZodPrefault",(Q,Y)=>{r.init(Q,Y),Q._zod.optin="optional",c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);if(X.value===void 0)X.value=Y.defaultValue;return Y.innerType._zod.run(X,W)}}),GW=q("$ZodNonOptional",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"values",()=>{let X=Y.innerType._zod.values;return X?new Set([...X].filter((W)=>W!==void 0)):void 0}),Q._zod.parse=(X,W)=>{let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>K8(z,Q));return K8(G,Q)}});function K8(Q,Y){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:Y});return Q}var zW=q("$ZodCatch",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),c(Q._zod,"values",()=>Y.innerType._zod.values),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>{if(X.value=z.value,z.issues.length)X.value=Y.catchValue({...X,error:{issues:z.issues.map((J)=>S0(J,W,j0()))},input:X.value}),X.issues=[];return X});if(X.value=G.value,G.issues.length)X.value=Y.catchValue({...X,error:{issues:G.issues.map((z)=>S0(z,W,j0()))},input:X.value}),X.issues=[];return X}});var JW=q("$ZodPipe",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"values",()=>Y.in._zod.values),c(Q._zod,"optin",()=>Y.in._zod.optin),c(Q._zod,"optout",()=>Y.out._zod.optout),c(Q._zod,"propValues",()=>Y.in._zod.propValues),Q._zod.parse=(X,W)=>{if(W.direction==="backward"){let z=Y.out._zod.run(X,W);if(z instanceof Promise)return z.then((J)=>X6(J,Y.in,W));return X6(z,Y.in,W)}let G=Y.in._zod.run(X,W);if(G instanceof Promise)return G.then((z)=>X6(z,Y.out,W));return X6(G,Y.out,W)}});function X6(Q,Y,X){if(Q.issues.length)return Q.aborted=!0,Q;return Y._zod.run({value:Q.value,issues:Q.issues},X)}var $W=q("$ZodReadonly",(Q,Y)=>{r.init(Q,Y),c(Q._zod,"propValues",()=>Y.innerType._zod.propValues),c(Q._zod,"values",()=>Y.innerType._zod.values),c(Q._zod,"optin",()=>Y.innerType._zod.optin),c(Q._zod,"optout",()=>Y.innerType._zod.optout),Q._zod.parse=(X,W)=>{if(W.direction==="backward")return Y.innerType._zod.run(X,W);let G=Y.innerType._zod.run(X,W);if(G instanceof Promise)return G.then(D8);return D8(G)}});function D8(Q){return Q.value=Object.freeze(Q.value),Q}var HW=q("$ZodCustom",(Q,Y)=>{G0.init(Q,Y),r.init(Q,Y),Q._zod.parse=(X,W)=>{return X},Q._zod.check=(X)=>{let W=X.value,G=Y.fn(W);if(G instanceof Promise)return G.then((z)=>L8(z,X,W,Q));L8(G,X,W,Q);return}});function L8(Q,Y,X,W){if(!Q){let G={code:"custom",input:X,inst:W,path:[...W._zod.def.path??[]],continue:!W._zod.def.abort};if(W._zod.def.params)G.params=W._zod.def.params;Y.issues.push(T1(G))}}var kH=(Q)=>{let Y=typeof Q;switch(Y){case"number":return Number.isNaN(Q)?"NaN":"number";case"object":{if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Object.getPrototypeOf(Q)!==Object.prototype&&Q.constructor)return Q.constructor.name}}return Y},vH=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function Y(W){return Q[W]??null}let X={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(W)=>{switch(W.code){case"invalid_type":return`Invalid input: expected ${W.expected}, received ${kH(W.input)}`;case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${t4(W.values[0])}`;return`Invalid option: expected one of ${n4(W.values,"|")}`;case"too_big":{let G=W.inclusive?"<=":"<",z=Y(W.origin);if(z)return`Too big: expected ${W.origin??"value"} to have ${G}${W.maximum.toString()} ${z.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${G}${W.maximum.toString()}`}case"too_small":{let G=W.inclusive?">=":">",z=Y(W.origin);if(z)return`Too small: expected ${W.origin} to have ${G}${W.minimum.toString()} ${z.unit}`;return`Too small: expected ${W.origin} to be ${G}${W.minimum.toString()}`}case"invalid_format":{let G=W;if(G.format==="starts_with")return`Invalid string: must start with "${G.prefix}"`;if(G.format==="ends_with")return`Invalid string: must end with "${G.suffix}"`;if(G.format==="includes")return`Invalid string: must include "${G.includes}"`;if(G.format==="regex")return`Invalid string: must match pattern ${G.pattern}`;return`Invalid ${X[G.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${n4(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};function gQ(){return{localeError:vH()}}var EV=Symbol("ZodOutput"),TV=Symbol("ZodInput");class UW{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...Y){let X=Y[0];if(this._map.set(Q,X),X&&typeof X==="object"&&"id"in X){if(this._idmap.has(X.id))throw Error(`ID ${X.id} already exists in the registry`);this._idmap.set(X.id,Q)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let Y=this._map.get(Q);if(Y&&typeof Y==="object"&&"id"in Y)this._idmap.delete(Y.id);return this._map.delete(Q),this}get(Q){let Y=Q._zod.parent;if(Y){let X={...this.get(Y)??{}};delete X.id;let W={...X,...this._map.get(Q)};return Object.keys(W).length?W:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function xH(){return new UW}var W4=xH();function AW(Q,Y){return new Q({type:"string",...I(Y)})}function BW(Q,Y){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...I(Y)})}function uQ(Q,Y){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...I(Y)})}function KW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...I(Y)})}function DW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(Y)})}function LW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(Y)})}function qW(Q,Y){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(Y)})}function FW(Q,Y){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...I(Y)})}function OW(Q,Y){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...I(Y)})}function MW(Q,Y){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(Y)})}function VW(Q,Y){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...I(Y)})}function NW(Q,Y){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(Y)})}function ZW(Q,Y){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...I(Y)})}function wW(Q,Y){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...I(Y)})}function jW(Q,Y){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(Y)})}function bW(Q,Y){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(Y)})}function PW(Q,Y){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(Y)})}function IW(Q,Y){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(Y)})}function EW(Q,Y){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(Y)})}function TW(Q,Y){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...I(Y)})}function SW(Q,Y){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...I(Y)})}function RW(Q,Y){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...I(Y)})}function CW(Q,Y){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...I(Y)})}function kW(Q,Y){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(Y)})}function vW(Q,Y){return new Q({type:"string",format:"date",check:"string_format",...I(Y)})}function xW(Q,Y){return new Q({type:"string",format:"time",check:"string_format",precision:null,...I(Y)})}function _W(Q,Y){return new Q({type:"string",format:"duration",check:"string_format",...I(Y)})}function yW(Q,Y){return new Q({type:"number",checks:[],...I(Y)})}function gW(Q,Y){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...I(Y)})}function uW(Q,Y){return new Q({type:"boolean",...I(Y)})}function hW(Q,Y){return new Q({type:"null",...I(Y)})}function fW(Q){return new Q({type:"unknown"})}function lW(Q,Y){return new Q({type:"never",...I(Y)})}function z6(Q,Y){return new CQ({check:"less_than",...I(Y),value:Q,inclusive:!1})}function G4(Q,Y){return new CQ({check:"less_than",...I(Y),value:Q,inclusive:!0})}function J6(Q,Y){return new kQ({check:"greater_than",...I(Y),value:Q,inclusive:!1})}function z4(Q,Y){return new kQ({check:"greater_than",...I(Y),value:Q,inclusive:!0})}function $6(Q,Y){return new nX({check:"multiple_of",...I(Y),value:Q})}function H6(Q,Y){return new oX({check:"max_length",...I(Y),maximum:Q})}function S1(Q,Y){return new tX({check:"min_length",...I(Y),minimum:Q})}function U6(Q,Y){return new aX({check:"length_equals",...I(Y),length:Q})}function hQ(Q,Y){return new sX({check:"string_format",format:"regex",...I(Y),pattern:Q})}function fQ(Q){return new eX({check:"string_format",format:"lowercase",...I(Q)})}function lQ(Q){return new Q8({check:"string_format",format:"uppercase",...I(Q)})}function mQ(Q,Y){return new Y8({check:"string_format",format:"includes",...I(Y),includes:Q})}function cQ(Q,Y){return new X8({check:"string_format",format:"starts_with",...I(Y),prefix:Q})}function pQ(Q,Y){return new W8({check:"string_format",format:"ends_with",...I(Y),suffix:Q})}function O1(Q){return new G8({check:"overwrite",tx:Q})}function iQ(Q){return O1((Y)=>Y.normalize(Q))}function rQ(){return O1((Q)=>Q.trim())}function nQ(){return O1((Q)=>Q.toLowerCase())}function dQ(){return O1((Q)=>Q.toUpperCase())}function mW(Q,Y,X){return new Q({type:"array",element:Y,...I(X)})}function cW(Q,Y,X){let W=I(X);return W.abort??(W.abort=!0),new Q({type:"custom",check:"custom",fn:Y,...W})}function pW(Q,Y,X){return new Q({type:"custom",check:"custom",fn:Y,...I(X)})}function iW(Q){let Y=_H((X)=>{return X.addIssue=(W)=>{if(typeof W==="string")X.issues.push(T1(W,X.value,Y._zod.def));else{let G=W;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=X.value),G.inst??(G.inst=Y),G.continue??(G.continue=!Y._zod.def.abort),X.issues.push(T1(G))}},Q(X.value,X)});return Y}function _H(Q,Y){let X=new G0({check:"custom",...I(Y)});return X._zod.check=Q,X}function R1(Q){return!!Q._zod}function W1(Q,Y){if(R1(Q))return Q4(Q,Y);return Q.safeParse(Y)}function A6(Q){if(!Q)return;let Y;if(R1(Q))Y=Q._zod?.def?.shape;else Y=Q.shape;if(!Y)return;if(typeof Y==="function")try{return Y()}catch{return}return Y}function rW(Q){if(R1(Q)){let z=Q._zod?.def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}}let X=Q._def;if(X){if(X.value!==void 0)return X.value;if(Array.isArray(X.values)&&X.values.length>0)return X.values[0]}let W=Q.value;if(W!==void 0)return W;return}var $4={};rY($4,{time:()=>aQ,duration:()=>sQ,datetime:()=>oQ,date:()=>tQ,ZodISOTime:()=>oW,ZodISODuration:()=>tW,ZodISODateTime:()=>nW,ZodISODate:()=>dW});var nW=q("ZodISODateTime",(Q,Y)=>{I8.init(Q,Y),o.init(Q,Y)});function oQ(Q){return kW(nW,Q)}var dW=q("ZodISODate",(Q,Y)=>{E8.init(Q,Y),o.init(Q,Y)});function tQ(Q){return vW(dW,Q)}var oW=q("ZodISOTime",(Q,Y)=>{T8.init(Q,Y),o.init(Q,Y)});function aQ(Q){return xW(oW,Q)}var tW=q("ZodISODuration",(Q,Y)=>{S8.init(Q,Y),o.init(Q,Y)});function sQ(Q){return _W(tW,Q)}var aW=(Q,Y)=>{a4.init(Q,Y),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(X)=>HX(Q,X)},flatten:{value:(X)=>$X(Q,X)},addIssue:{value:(X)=>{Q.issues.push(X),Q.message=JSON.stringify(Q.issues,I1,2)}},addIssues:{value:(X)=>{Q.issues.push(...X),Q.message=JSON.stringify(Q.issues,I1,2)}},isEmpty:{get(){return Q.issues.length===0}}})},DN=q("ZodError",aW),Z0=q("ZodError",aW,{Parent:Error});var sW=s4(Z0),eW=e4(Z0),QG=e1(Z0),YG=Y4(Z0),XG=UX(Z0),WG=AX(Z0),GG=BX(Z0),zG=KX(Z0),JG=DX(Z0),$G=LX(Z0),HG=qX(Z0),UG=FX(Z0);var e=q("ZodType",(Q,Y)=>{return r.init(Q,Y),Q.def=Y,Q.type=Y.type,Object.defineProperty(Q,"_def",{value:Y}),Q.check=(...X)=>{return Q.clone(f.mergeDefs(Y,{checks:[...Y.checks??[],...X.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}))},Q.clone=(X,W)=>T0(Q,X,W),Q.brand=()=>Q,Q.register=(X,W)=>{return X.add(Q,W),Q},Q.parse=(X,W)=>sW(Q,X,W,{callee:Q.parse}),Q.safeParse=(X,W)=>QG(Q,X,W),Q.parseAsync=async(X,W)=>eW(Q,X,W,{callee:Q.parseAsync}),Q.safeParseAsync=async(X,W)=>YG(Q,X,W),Q.spa=Q.safeParseAsync,Q.encode=(X,W)=>XG(Q,X,W),Q.decode=(X,W)=>WG(Q,X,W),Q.encodeAsync=async(X,W)=>GG(Q,X,W),Q.decodeAsync=async(X,W)=>zG(Q,X,W),Q.safeEncode=(X,W)=>JG(Q,X,W),Q.safeDecode=(X,W)=>$G(Q,X,W),Q.safeEncodeAsync=async(X,W)=>HG(Q,X,W),Q.safeDecodeAsync=async(X,W)=>UG(Q,X,W),Q.refine=(X,W)=>Q.check(C3(X,W)),Q.superRefine=(X)=>Q.check(k3(X)),Q.overwrite=(X)=>Q.check(O1(X)),Q.optional=()=>s(Q),Q.nullable=()=>KG(Q),Q.nullish=()=>s(KG(Q)),Q.nonoptional=(X)=>P3(Q,X),Q.array=()=>y(Q),Q.or=(X)=>i([Q,X]),Q.and=(X)=>K6(Q,X),Q.transform=(X)=>Q9(Q,OG(X)),Q.default=(X)=>w3(Q,X),Q.prefault=(X)=>b3(Q,X),Q.catch=(X)=>E3(Q,X),Q.pipe=(X)=>Q9(Q,X),Q.readonly=()=>R3(Q),Q.describe=(X)=>{let W=Q.clone();return W4.add(W,{description:X}),W},Object.defineProperty(Q,"description",{get(){return W4.get(Q)?.description},configurable:!0}),Q.meta=(...X)=>{if(X.length===0)return W4.get(Q);let W=Q.clone();return W4.add(W,X[0]),W},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q}),DG=q("_ZodString",(Q,Y)=>{G6.init(Q,Y),e.init(Q,Y);let X=Q._zod.bag;Q.format=X.format??null,Q.minLength=X.minimum??null,Q.maxLength=X.maximum??null,Q.regex=(...W)=>Q.check(hQ(...W)),Q.includes=(...W)=>Q.check(mQ(...W)),Q.startsWith=(...W)=>Q.check(cQ(...W)),Q.endsWith=(...W)=>Q.check(pQ(...W)),Q.min=(...W)=>Q.check(S1(...W)),Q.max=(...W)=>Q.check(H6(...W)),Q.length=(...W)=>Q.check(U6(...W)),Q.nonempty=(...W)=>Q.check(S1(1,...W)),Q.lowercase=(W)=>Q.check(fQ(W)),Q.uppercase=(W)=>Q.check(lQ(W)),Q.trim=()=>Q.check(rQ()),Q.normalize=(...W)=>Q.check(iQ(...W)),Q.toLowerCase=()=>Q.check(nQ()),Q.toUpperCase=()=>Q.check(dQ())}),pH=q("ZodString",(Q,Y)=>{G6.init(Q,Y),DG.init(Q,Y),Q.email=(X)=>Q.check(BW(iH,X)),Q.url=(X)=>Q.check(FW(rH,X)),Q.jwt=(X)=>Q.check(CW($3,X)),Q.emoji=(X)=>Q.check(OW(nH,X)),Q.guid=(X)=>Q.check(uQ(AG,X)),Q.uuid=(X)=>Q.check(KW(B6,X)),Q.uuidv4=(X)=>Q.check(DW(B6,X)),Q.uuidv6=(X)=>Q.check(LW(B6,X)),Q.uuidv7=(X)=>Q.check(qW(B6,X)),Q.nanoid=(X)=>Q.check(MW(dH,X)),Q.guid=(X)=>Q.check(uQ(AG,X)),Q.cuid=(X)=>Q.check(VW(oH,X)),Q.cuid2=(X)=>Q.check(NW(tH,X)),Q.ulid=(X)=>Q.check(ZW(aH,X)),Q.base64=(X)=>Q.check(TW(G3,X)),Q.base64url=(X)=>Q.check(SW(z3,X)),Q.xid=(X)=>Q.check(wW(sH,X)),Q.ksuid=(X)=>Q.check(jW(eH,X)),Q.ipv4=(X)=>Q.check(bW(Q3,X)),Q.ipv6=(X)=>Q.check(PW(Y3,X)),Q.cidrv4=(X)=>Q.check(IW(X3,X)),Q.cidrv6=(X)=>Q.check(EW(W3,X)),Q.e164=(X)=>Q.check(RW(J3,X)),Q.datetime=(X)=>Q.check(oQ(X)),Q.date=(X)=>Q.check(tQ(X)),Q.time=(X)=>Q.check(aQ(X)),Q.duration=(X)=>Q.check(sQ(X))});function D(Q){return AW(pH,Q)}var o=q("ZodStringFormat",(Q,Y)=>{n.init(Q,Y),DG.init(Q,Y)}),iH=q("ZodEmail",(Q,Y)=>{O8.init(Q,Y),o.init(Q,Y)});var AG=q("ZodGUID",(Q,Y)=>{q8.init(Q,Y),o.init(Q,Y)});var B6=q("ZodUUID",(Q,Y)=>{F8.init(Q,Y),o.init(Q,Y)});var rH=q("ZodURL",(Q,Y)=>{M8.init(Q,Y),o.init(Q,Y)});var nH=q("ZodEmoji",(Q,Y)=>{V8.init(Q,Y),o.init(Q,Y)});var dH=q("ZodNanoID",(Q,Y)=>{N8.init(Q,Y),o.init(Q,Y)});var oH=q("ZodCUID",(Q,Y)=>{Z8.init(Q,Y),o.init(Q,Y)});var tH=q("ZodCUID2",(Q,Y)=>{w8.init(Q,Y),o.init(Q,Y)});var aH=q("ZodULID",(Q,Y)=>{j8.init(Q,Y),o.init(Q,Y)});var sH=q("ZodXID",(Q,Y)=>{b8.init(Q,Y),o.init(Q,Y)});var eH=q("ZodKSUID",(Q,Y)=>{P8.init(Q,Y),o.init(Q,Y)});var Q3=q("ZodIPv4",(Q,Y)=>{R8.init(Q,Y),o.init(Q,Y)});var Y3=q("ZodIPv6",(Q,Y)=>{C8.init(Q,Y),o.init(Q,Y)});var X3=q("ZodCIDRv4",(Q,Y)=>{k8.init(Q,Y),o.init(Q,Y)});var W3=q("ZodCIDRv6",(Q,Y)=>{v8.init(Q,Y),o.init(Q,Y)});var G3=q("ZodBase64",(Q,Y)=>{_8.init(Q,Y),o.init(Q,Y)});var z3=q("ZodBase64URL",(Q,Y)=>{y8.init(Q,Y),o.init(Q,Y)});var J3=q("ZodE164",(Q,Y)=>{g8.init(Q,Y),o.init(Q,Y)});var $3=q("ZodJWT",(Q,Y)=>{u8.init(Q,Y),o.init(Q,Y)});var LG=q("ZodNumber",(Q,Y)=>{_Q.init(Q,Y),e.init(Q,Y),Q.gt=(W,G)=>Q.check(J6(W,G)),Q.gte=(W,G)=>Q.check(z4(W,G)),Q.min=(W,G)=>Q.check(z4(W,G)),Q.lt=(W,G)=>Q.check(z6(W,G)),Q.lte=(W,G)=>Q.check(G4(W,G)),Q.max=(W,G)=>Q.check(G4(W,G)),Q.int=(W)=>Q.check(BG(W)),Q.safe=(W)=>Q.check(BG(W)),Q.positive=(W)=>Q.check(J6(0,W)),Q.nonnegative=(W)=>Q.check(z4(0,W)),Q.negative=(W)=>Q.check(z6(0,W)),Q.nonpositive=(W)=>Q.check(G4(0,W)),Q.multipleOf=(W,G)=>Q.check($6(W,G)),Q.step=(W,G)=>Q.check($6(W,G)),Q.finite=()=>Q;let X=Q._zod.bag;Q.minValue=Math.max(X.minimum??Number.NEGATIVE_INFINITY,X.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(X.maximum??Number.POSITIVE_INFINITY,X.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(X.format??"").includes("int")||Number.isSafeInteger(X.multipleOf??0.5),Q.isFinite=!0,Q.format=X.format??null});function m(Q){return yW(LG,Q)}var H3=q("ZodNumberFormat",(Q,Y)=>{h8.init(Q,Y),LG.init(Q,Y)});function BG(Q){return gW(H3,Q)}var U3=q("ZodBoolean",(Q,Y)=>{f8.init(Q,Y),e.init(Q,Y)});function W0(Q){return uW(U3,Q)}var A3=q("ZodNull",(Q,Y)=>{l8.init(Q,Y),e.init(Q,Y)});function Y9(Q){return hW(A3,Q)}var B3=q("ZodUnknown",(Q,Y)=>{m8.init(Q,Y),e.init(Q,Y)});function t(){return fW(B3)}var K3=q("ZodNever",(Q,Y)=>{c8.init(Q,Y),e.init(Q,Y)});function D3(Q){return lW(K3,Q)}var L3=q("ZodArray",(Q,Y)=>{p8.init(Q,Y),e.init(Q,Y),Q.element=Y.element,Q.min=(X,W)=>Q.check(S1(X,W)),Q.nonempty=(X)=>Q.check(S1(1,X)),Q.max=(X,W)=>Q.check(H6(X,W)),Q.length=(X,W)=>Q.check(U6(X,W)),Q.unwrap=()=>Q.element});function y(Q,Y){return mW(L3,Q,Y)}var qG=q("ZodObject",(Q,Y)=>{n8.init(Q,Y),e.init(Q,Y),f.defineLazy(Q,"shape",()=>{return Y.shape}),Q.keyof=()=>q0(Object.keys(Q._zod.def.shape)),Q.catchall=(X)=>Q.clone({...Q._zod.def,catchall:X}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:t()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:D3()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(X)=>{return f.extend(Q,X)},Q.safeExtend=(X)=>{return f.safeExtend(Q,X)},Q.merge=(X)=>f.merge(Q,X),Q.pick=(X)=>f.pick(Q,X),Q.omit=(X)=>f.omit(Q,X),Q.partial=(...X)=>f.partial(MG,Q,X[0]),Q.required=(...X)=>f.required(VG,Q,X[0])});function j(Q,Y){let X={type:"object",shape:Q??{},...f.normalizeParams(Y)};return new qG(X)}function K0(Q,Y){return new qG({type:"object",shape:Q,catchall:t(),...f.normalizeParams(Y)})}var FG=q("ZodUnion",(Q,Y)=>{yQ.init(Q,Y),e.init(Q,Y),Q.options=Y.options});function i(Q,Y){return new FG({type:"union",options:Q,...f.normalizeParams(Y)})}var q3=q("ZodDiscriminatedUnion",(Q,Y)=>{FG.init(Q,Y),d8.init(Q,Y)});function X9(Q,Y,X){return new q3({type:"union",options:Y,discriminator:Q,...f.normalizeParams(X)})}var F3=q("ZodIntersection",(Q,Y)=>{o8.init(Q,Y),e.init(Q,Y)});function K6(Q,Y){return new F3({type:"intersection",left:Q,right:Y})}var O3=q("ZodRecord",(Q,Y)=>{t8.init(Q,Y),e.init(Q,Y),Q.keyType=Y.keyType,Q.valueType=Y.valueType});function a(Q,Y,X){return new O3({type:"record",keyType:Q,valueType:Y,...f.normalizeParams(X)})}var eQ=q("ZodEnum",(Q,Y)=>{a8.init(Q,Y),e.init(Q,Y),Q.enum=Y.entries,Q.options=Object.values(Y.entries);let X=new Set(Object.keys(Y.entries));Q.extract=(W,G)=>{let z={};for(let J of W)if(X.has(J))z[J]=Y.entries[J];else throw Error(`Key ${J} not found in enum`);return new eQ({...Y,checks:[],...f.normalizeParams(G),entries:z})},Q.exclude=(W,G)=>{let z={...Y.entries};for(let J of W)if(X.has(J))delete z[J];else throw Error(`Key ${J} not found in enum`);return new eQ({...Y,checks:[],...f.normalizeParams(G),entries:z})}});function q0(Q,Y){let X=Array.isArray(Q)?Object.fromEntries(Q.map((W)=>[W,W])):Q;return new eQ({type:"enum",entries:X,...f.normalizeParams(Y)})}var M3=q("ZodLiteral",(Q,Y)=>{s8.init(Q,Y),e.init(Q,Y),Q.values=new Set(Y.values),Object.defineProperty(Q,"value",{get(){if(Y.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return Y.values[0]}})});function b(Q,Y){return new M3({type:"literal",values:Array.isArray(Q)?Q:[Q],...f.normalizeParams(Y)})}var V3=q("ZodTransform",(Q,Y)=>{e8.init(Q,Y),e.init(Q,Y),Q._zod.parse=(X,W)=>{if(W.direction==="backward")throw new d1(Q.constructor.name);X.addIssue=(z)=>{if(typeof z==="string")X.issues.push(f.issue(z,X.value,Y));else{let J=z;if(J.fatal)J.continue=!1;J.code??(J.code="custom"),J.input??(J.input=X.value),J.inst??(J.inst=Q),X.issues.push(f.issue(J))}};let G=Y.transform(X.value,X);if(G instanceof Promise)return G.then((z)=>{return X.value=z,X});return X.value=G,X}});function OG(Q){return new V3({type:"transform",transform:Q})}var MG=q("ZodOptional",(Q,Y)=>{QW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function s(Q){return new MG({type:"optional",innerType:Q})}var N3=q("ZodNullable",(Q,Y)=>{YW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function KG(Q){return new N3({type:"nullable",innerType:Q})}var Z3=q("ZodDefault",(Q,Y)=>{XW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function w3(Q,Y){return new Z3({type:"default",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var j3=q("ZodPrefault",(Q,Y)=>{WW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function b3(Q,Y){return new j3({type:"prefault",innerType:Q,get defaultValue(){return typeof Y==="function"?Y():f.shallowClone(Y)}})}var VG=q("ZodNonOptional",(Q,Y)=>{GW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function P3(Q,Y){return new VG({type:"nonoptional",innerType:Q,...f.normalizeParams(Y)})}var I3=q("ZodCatch",(Q,Y)=>{zW.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function E3(Q,Y){return new I3({type:"catch",innerType:Q,catchValue:typeof Y==="function"?Y:()=>Y})}var T3=q("ZodPipe",(Q,Y)=>{JW.init(Q,Y),e.init(Q,Y),Q.in=Y.in,Q.out=Y.out});function Q9(Q,Y){return new T3({type:"pipe",in:Q,out:Y})}var S3=q("ZodReadonly",(Q,Y)=>{$W.init(Q,Y),e.init(Q,Y),Q.unwrap=()=>Q._zod.def.innerType});function R3(Q){return new S3({type:"readonly",innerType:Q})}var NG=q("ZodCustom",(Q,Y)=>{HW.init(Q,Y),e.init(Q,Y)});function ZG(Q,Y){return cW(NG,Q??(()=>!0),Y)}function C3(Q,Y={}){return pW(NG,Q,Y)}function k3(Q){return iW(Q)}function W9(Q,Y){return Q9(OG(Q),Y)}j0(gQ());var G9="2025-11-25";var wG=[G9,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],G1="io.modelcontextprotocol/related-task",L6="2.0",z0=ZG((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),jG=i([D(),m().int()]),bG=D(),HZ=K0({ttl:i([m(),Y9()]).optional(),pollInterval:m().optional()}),v3=j({ttl:m().optional()}),x3=j({taskId:D()}),z9=K0({progressToken:jG.optional(),[G1]:x3.optional()}),w0=j({_meta:z9.optional()}),H4=w0.extend({task:v3.optional()}),PG=(Q)=>H4.safeParse(Q).success,J0=j({method:D(),params:w0.loose().optional()}),b0=j({_meta:z9.optional()}),P0=j({method:D(),params:b0.loose().optional()}),$0=K0({_meta:z9.optional()}),q6=i([D(),m().int()]),IG=j({jsonrpc:b(L6),id:q6,...J0.shape}).strict(),J9=(Q)=>IG.safeParse(Q).success,EG=j({jsonrpc:b(L6),...P0.shape}).strict(),TG=(Q)=>EG.safeParse(Q).success,$9=j({jsonrpc:b(L6),id:q6,result:$0}).strict(),U4=(Q)=>$9.safeParse(Q).success;var g;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(g||(g={}));var H9=j({jsonrpc:b(L6),id:q6.optional(),error:j({code:m().int(),message:D(),data:t().optional()})}).strict();var SG=(Q)=>H9.safeParse(Q).success;var UZ=i([IG,EG,$9,H9]),AZ=i([$9,H9]),F6=$0.strict(),_3=b0.extend({requestId:q6.optional(),reason:D().optional()}),O6=P0.extend({method:b("notifications/cancelled"),params:_3}),y3=j({src:D(),mimeType:D().optional(),sizes:y(D()).optional(),theme:q0(["light","dark"]).optional()}),A4=j({icons:y(y3).optional()}),C1=j({name:D(),title:D().optional()}),RG=C1.extend({...C1.shape,...A4.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),g3=K6(j({applyDefaults:W0().optional()}),a(D(),t())),u3=W9((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},K6(j({form:g3.optional(),url:z0.optional()}),a(D(),t()).optional())),h3=K0({list:z0.optional(),cancel:z0.optional(),requests:K0({sampling:K0({createMessage:z0.optional()}).optional(),elicitation:K0({create:z0.optional()}).optional()}).optional()}),f3=K0({list:z0.optional(),cancel:z0.optional(),requests:K0({tools:K0({call:z0.optional()}).optional()}).optional()}),l3=j({experimental:a(D(),z0).optional(),sampling:j({context:z0.optional(),tools:z0.optional()}).optional(),elicitation:u3.optional(),roots:j({listChanged:W0().optional()}).optional(),tasks:h3.optional()}),m3=w0.extend({protocolVersion:D(),capabilities:l3,clientInfo:RG}),U9=J0.extend({method:b("initialize"),params:m3});var c3=j({experimental:a(D(),z0).optional(),logging:z0.optional(),completions:z0.optional(),prompts:j({listChanged:W0().optional()}).optional(),resources:j({subscribe:W0().optional(),listChanged:W0().optional()}).optional(),tools:j({listChanged:W0().optional()}).optional(),tasks:f3.optional()}),p3=$0.extend({protocolVersion:D(),capabilities:c3,serverInfo:RG,instructions:D().optional()}),A9=P0.extend({method:b("notifications/initialized"),params:b0.optional()});var M6=J0.extend({method:b("ping"),params:w0.optional()}),i3=j({progress:m(),total:s(m()),message:s(D())}),r3=j({...b0.shape,...i3.shape,progressToken:jG}),V6=P0.extend({method:b("notifications/progress"),params:r3}),n3=w0.extend({cursor:bG.optional()}),B4=J0.extend({params:n3.optional()}),K4=$0.extend({nextCursor:bG.optional()}),d3=q0(["working","input_required","completed","failed","cancelled"]),D4=j({taskId:D(),status:d3,ttl:i([m(),Y9()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:s(m()),statusMessage:s(D())}),k1=$0.extend({task:D4}),o3=b0.merge(D4),L4=P0.extend({method:b("notifications/tasks/status"),params:o3}),N6=J0.extend({method:b("tasks/get"),params:w0.extend({taskId:D()})}),Z6=$0.merge(D4),w6=J0.extend({method:b("tasks/result"),params:w0.extend({taskId:D()})}),BZ=$0.loose(),j6=B4.extend({method:b("tasks/list")}),b6=K4.extend({tasks:y(D4)}),P6=J0.extend({method:b("tasks/cancel"),params:w0.extend({taskId:D()})}),CG=$0.merge(D4),kG=j({uri:D(),mimeType:s(D()),_meta:a(D(),t()).optional()}),vG=kG.extend({text:D()}),B9=D().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),xG=kG.extend({blob:B9}),q4=q0(["user","assistant"]),v1=j({audience:y(q4).optional(),priority:m().min(0).max(1).optional(),lastModified:$4.datetime({offset:!0}).optional()}),_G=j({...C1.shape,...A4.shape,uri:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),t3=j({...C1.shape,...A4.shape,uriTemplate:D(),description:s(D()),mimeType:s(D()),annotations:v1.optional(),_meta:s(K0({}))}),K9=B4.extend({method:b("resources/list")}),a3=K4.extend({resources:y(_G)}),s3=B4.extend({method:b("resources/templates/list")}),e3=K4.extend({resourceTemplates:y(t3)}),D9=w0.extend({uri:D()}),QU=D9,L9=J0.extend({method:b("resources/read"),params:QU}),YU=$0.extend({contents:y(i([vG,xG]))}),XU=P0.extend({method:b("notifications/resources/list_changed"),params:b0.optional()}),WU=D9,GU=J0.extend({method:b("resources/subscribe"),params:WU}),zU=D9,JU=J0.extend({method:b("resources/unsubscribe"),params:zU}),$U=b0.extend({uri:D()}),HU=P0.extend({method:b("notifications/resources/updated"),params:$U}),UU=j({name:D(),description:s(D()),required:s(W0())}),AU=j({...C1.shape,...A4.shape,description:s(D()),arguments:s(y(UU)),_meta:s(K0({}))}),BU=B4.extend({method:b("prompts/list")}),KU=K4.extend({prompts:y(AU)}),DU=w0.extend({name:D(),arguments:a(D(),D()).optional()}),LU=J0.extend({method:b("prompts/get"),params:DU}),q9=j({type:b("text"),text:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),F9=j({type:b("image"),data:B9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),O9=j({type:b("audio"),data:B9,mimeType:D(),annotations:v1.optional(),_meta:a(D(),t()).optional()}),qU=j({type:b("tool_use"),name:D(),id:D(),input:a(D(),t()),_meta:a(D(),t()).optional()}),FU=j({type:b("resource"),resource:i([vG,xG]),annotations:v1.optional(),_meta:a(D(),t()).optional()}),OU=_G.extend({type:b("resource_link")}),M9=i([q9,F9,O9,OU,FU]),MU=j({role:q4,content:M9}),VU=$0.extend({description:D().optional(),messages:y(MU)}),NU=P0.extend({method:b("notifications/prompts/list_changed"),params:b0.optional()}),ZU=j({title:D().optional(),readOnlyHint:W0().optional(),destructiveHint:W0().optional(),idempotentHint:W0().optional(),openWorldHint:W0().optional()}),wU=j({taskSupport:q0(["required","optional","forbidden"]).optional()}),yG=j({...C1.shape,...A4.shape,description:D().optional(),inputSchema:j({type:b("object"),properties:a(D(),z0).optional(),required:y(D()).optional()}).catchall(t()),outputSchema:j({type:b("object"),properties:a(D(),z0).optional(),required:y(D()).optional()}).catchall(t()).optional(),annotations:ZU.optional(),execution:wU.optional(),_meta:a(D(),t()).optional()}),V9=B4.extend({method:b("tools/list")}),jU=K4.extend({tools:y(yG)}),I6=$0.extend({content:y(M9).default([]),structuredContent:a(D(),t()).optional(),isError:W0().optional()}),KZ=I6.or($0.extend({toolResult:t()})),bU=H4.extend({name:D(),arguments:a(D(),t()).optional()}),F4=J0.extend({method:b("tools/call"),params:bU}),PU=P0.extend({method:b("notifications/tools/list_changed"),params:b0.optional()}),DZ=j({autoRefresh:W0().default(!0),debounceMs:m().int().nonnegative().default(300)}),O4=q0(["debug","info","notice","warning","error","critical","alert","emergency"]),IU=w0.extend({level:O4}),N9=J0.extend({method:b("logging/setLevel"),params:IU}),EU=b0.extend({level:O4,logger:D().optional(),data:t()}),TU=P0.extend({method:b("notifications/message"),params:EU}),SU=j({name:D().optional()}),RU=j({hints:y(SU).optional(),costPriority:m().min(0).max(1).optional(),speedPriority:m().min(0).max(1).optional(),intelligencePriority:m().min(0).max(1).optional()}),CU=j({mode:q0(["auto","required","none"]).optional()}),kU=j({type:b("tool_result"),toolUseId:D().describe("The unique identifier for the corresponding tool call."),content:y(M9).default([]),structuredContent:j({}).loose().optional(),isError:W0().optional(),_meta:a(D(),t()).optional()}),vU=X9("type",[q9,F9,O9]),D6=X9("type",[q9,F9,O9,qU,kU]),xU=j({role:q4,content:i([D6,y(D6)]),_meta:a(D(),t()).optional()}),_U=H4.extend({messages:y(xU),modelPreferences:RU.optional(),systemPrompt:D().optional(),includeContext:q0(["none","thisServer","allServers"]).optional(),temperature:m().optional(),maxTokens:m().int(),stopSequences:y(D()).optional(),metadata:z0.optional(),tools:y(yG).optional(),toolChoice:CU.optional()}),yU=J0.extend({method:b("sampling/createMessage"),params:_U}),Z9=$0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens"]).or(D())),role:q4,content:vU}),w9=$0.extend({model:D(),stopReason:s(q0(["endTurn","stopSequence","maxTokens","toolUse"]).or(D())),role:q4,content:i([D6,y(D6)])}),gU=j({type:b("boolean"),title:D().optional(),description:D().optional(),default:W0().optional()}),uU=j({type:b("string"),title:D().optional(),description:D().optional(),minLength:m().optional(),maxLength:m().optional(),format:q0(["email","uri","date","date-time"]).optional(),default:D().optional()}),hU=j({type:q0(["number","integer"]),title:D().optional(),description:D().optional(),minimum:m().optional(),maximum:m().optional(),default:m().optional()}),fU=j({type:b("string"),title:D().optional(),description:D().optional(),enum:y(D()),default:D().optional()}),lU=j({type:b("string"),title:D().optional(),description:D().optional(),oneOf:y(j({const:D(),title:D()})),default:D().optional()}),mU=j({type:b("string"),title:D().optional(),description:D().optional(),enum:y(D()),enumNames:y(D()).optional(),default:D().optional()}),cU=i([fU,lU]),pU=j({type:b("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:j({type:b("string"),enum:y(D())}),default:y(D()).optional()}),iU=j({type:b("array"),title:D().optional(),description:D().optional(),minItems:m().optional(),maxItems:m().optional(),items:j({anyOf:y(j({const:D(),title:D()}))}),default:y(D()).optional()}),rU=i([pU,iU]),nU=i([mU,cU,rU]),dU=i([nU,gU,uU,hU]),oU=H4.extend({mode:b("form").optional(),message:D(),requestedSchema:j({type:b("object"),properties:a(D(),dU),required:y(D()).optional()})}),tU=H4.extend({mode:b("url"),message:D(),elicitationId:D(),url:D().url()}),aU=i([oU,tU]),sU=J0.extend({method:b("elicitation/create"),params:aU}),eU=b0.extend({elicitationId:D()}),QA=P0.extend({method:b("notifications/elicitation/complete"),params:eU}),E6=$0.extend({action:q0(["accept","decline","cancel"]),content:W9((Q)=>Q===null?void 0:Q,a(D(),i([D(),m(),W0(),y(D())])).optional())}),YA=j({type:b("ref/resource"),uri:D()});var XA=j({type:b("ref/prompt"),name:D()}),WA=w0.extend({ref:i([XA,YA]),argument:j({name:D(),value:D()}),context:j({arguments:a(D(),D()).optional()}).optional()}),GA=J0.extend({method:b("completion/complete"),params:WA});var zA=$0.extend({completion:K0({values:y(D()).max(100),total:s(m().int()),hasMore:s(W0())})}),JA=j({uri:D().startsWith("file://"),name:D().optional(),_meta:a(D(),t()).optional()}),$A=J0.extend({method:b("roots/list"),params:w0.optional()}),j9=$0.extend({roots:y(JA)}),HA=P0.extend({method:b("notifications/roots/list_changed"),params:b0.optional()}),LZ=i([M6,U9,GA,N9,LU,BU,K9,s3,L9,GU,JU,F4,V9,N6,w6,j6,P6]),qZ=i([O6,V6,A9,HA,L4]),FZ=i([F6,Z9,w9,E6,j9,Z6,b6,k1]),OZ=i([M6,yU,sU,$A,N6,w6,j6,P6]),MZ=i([O6,V6,TU,HU,XU,PU,NU,L4,QA]),VZ=i([F6,p3,zA,VU,KU,a3,e3,YU,I6,jU,Z6,b6,k1]);class k extends Error{constructor(Q,Y,X){super(`MCP error ${Q}: ${Y}`);this.code=Q,this.data=X,this.name="McpError"}static fromError(Q,Y,X){if(Q===g.UrlElicitationRequired&&X){let W=X;if(W.elicitations)return new gG(W.elicitations,Y)}return new k(Q,Y,X)}}class gG extends k{constructor(Q,Y=`URL elicitation${Q.length>1?"s":""} required`){super(g.UrlElicitationRequired,Y,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function z1(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var UA=Symbol("Let zodToJsonSchema decide on which parser to use");var sZ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b9(Q){let X=A6(Q)?.method;if(!X)throw Error("Schema is missing a method literal");let W=rW(X);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function P9(Q,Y){let X=W1(Q,Y);if(!X.success)throw X.error;return X.data}var qA=60000;class I9{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(O6,(Y)=>{this._oncancel(Y)}),this.setNotificationHandler(V6,(Y)=>{this._onprogress(Y)}),this.setRequestHandler(M6,(Y)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(N6,async(Y,X)=>{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(w6,async(Y,X)=>{let W=async()=>{let G=Y.params.taskId;if(this._taskMessageQueue){let J;while(J=await this._taskMessageQueue.dequeue(G,X.sessionId)){if(J.type==="response"||J.type==="error"){let $=J.message,H=$.id,U=this._requestResolvers.get(H);if(U)if(this._requestResolvers.delete(H),J.type==="response")U($);else{let A=$,B=new k(A.error.code,A.error.message,A.error.data);U(B)}else{let A=J.type==="response"?"Response":"Error";this._onerror(Error(`${A} handler missing for request ${H}`))}continue}await this._transport?.send(J.message,{relatedRequestId:X.requestId})}}let z=await this._taskStore.getTask(G,X.sessionId);if(!z)throw new k(g.InvalidParams,`Task not found: ${G}`);if(!z1(z.status))return await this._waitForTaskUpdate(G,X.signal),await W();if(z1(z.status)){let J=await this._taskStore.getTaskResult(G,X.sessionId);return this._clearTaskQueue(G),{...J,_meta:{...J._meta,[G1]:{taskId:G}}}}return await W()};return await W()}),this.setRequestHandler(j6,async(Y,X)=>{try{let{tasks:W,nextCursor:G}=await this._taskStore.listTasks(Y.params?.cursor,X.sessionId);return{tasks:W,nextCursor:G,_meta:{}}}catch(W){throw new k(g.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(P6,async(Y,X)=>{try{let W=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!W)throw new k(g.InvalidParams,`Task not found: ${Y.params.taskId}`);if(z1(W.status))throw new k(g.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Y.params.taskId,"cancelled","Client cancelled task execution.",X.sessionId),this._clearTaskQueue(Y.params.taskId);let G=await this._taskStore.getTask(Y.params.taskId,X.sessionId);if(!G)throw new k(g.InvalidParams,`Task not found after cancellation: ${Y.params.taskId}`);return{_meta:{},...G}}catch(W){if(W instanceof k)throw W;throw new k(g.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,Y,X,W,G=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(W,Y),startTime:Date.now(),timeout:Y,maxTotalTimeout:X,resetTimeoutOnProgress:G,onTimeout:W})}_resetTimeout(Q){let Y=this._timeoutInfo.get(Q);if(!Y)return!1;let X=Date.now()-Y.startTime;if(Y.maxTotalTimeout&&X>=Y.maxTotalTimeout)throw this._timeoutInfo.delete(Q),k.fromError(g.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Y.maxTotalTimeout,totalElapsed:X});return clearTimeout(Y.timeoutId),Y.timeoutId=setTimeout(Y.onTimeout,Y.timeout),!0}_cleanupTimeout(Q){let Y=this._timeoutInfo.get(Q);if(Y)clearTimeout(Y.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){this._transport=Q;let Y=this.transport?.onclose;this._transport.onclose=()=>{Y?.(),this._onclose()};let X=this.transport?.onerror;this._transport.onerror=(G)=>{X?.(G),this._onerror(G)};let W=this._transport?.onmessage;this._transport.onmessage=(G,z)=>{if(W?.(G,z),U4(G)||SG(G))this._onresponse(G);else if(J9(G))this._onrequest(G,z);else if(TG(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let Y=k.fromError(g.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let X of Q.values())X(Y)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let Y=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(Y===void 0)return;Promise.resolve().then(()=>Y(Q)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(Q,Y){let X=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,W=this._transport,G=Q.params?._meta?.[G1]?.taskId;if(X===void 0){let U={jsonrpc:"2.0",id:Q.id,error:{code:g.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:U,timestamp:Date.now()},W?.sessionId).catch((A)=>this._onerror(Error(`Failed to enqueue error response: ${A}`)));else W?.send(U).catch((A)=>this._onerror(Error(`Failed to send an error response: ${A}`)));return}let z=new AbortController;this._requestHandlerAbortControllers.set(Q.id,z);let J=PG(Q.params)?Q.params.task:void 0,$=this._taskStore?this.requestTaskStore(Q,W?.sessionId):void 0,H={signal:z.signal,sessionId:W?.sessionId,_meta:Q.params?._meta,sendNotification:async(U)=>{let A={relatedRequestId:Q.id};if(G)A.relatedTask={taskId:G};await this.notification(U,A)},sendRequest:async(U,A,B)=>{let K={...B,relatedRequestId:Q.id};if(G&&!K.relatedTask)K.relatedTask={taskId:G};let L=K.relatedTask?.taskId??G;if(L&&$)await $.updateTaskStatus(L,"input_required");return await this.request(U,A,K)},authInfo:Y?.authInfo,requestId:Q.id,requestInfo:Y?.requestInfo,taskId:G,taskStore:$,taskRequestedTtl:J?.ttl,closeSSEStream:Y?.closeSSEStream,closeStandaloneSSEStream:Y?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(J)this.assertTaskHandlerCapability(Q.method)}).then(()=>X(Q,H)).then(async(U)=>{if(z.signal.aborted)return;let A={result:U,jsonrpc:"2.0",id:Q.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)},async(U)=>{if(z.signal.aborted)return;let A={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(U.code)?U.code:g.InternalError,message:U.message??"Internal error",...U.data!==void 0&&{data:U.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:A,timestamp:Date.now()},W?.sessionId);else await W?.send(A)}).catch((U)=>this._onerror(Error(`Failed to send response: ${U}`))).finally(()=>{this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:Y,...X}=Q.params,W=Number(Y),G=this._progressHandlers.get(W);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let z=this._responseHandlers.get(W),J=this._timeoutInfo.get(W);if(J&&z&&J.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch($){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),z($);return}G(X)}_onresponse(Q){let Y=Number(Q.id),X=this._requestResolvers.get(Y);if(X){if(this._requestResolvers.delete(Y),U4(Q))X(Q);else{let z=new k(Q.error.code,Q.error.message,Q.error.data);X(z)}return}let W=this._responseHandlers.get(Y);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(Y),this._cleanupTimeout(Y);let G=!1;if(U4(Q)&&Q.result&&typeof Q.result==="object"){let z=Q.result;if(z.task&&typeof z.task==="object"){let J=z.task;if(typeof J.taskId==="string")G=!0,this._taskProgressTokens.set(J.taskId,Y)}}if(!G)this._progressHandlers.delete(Y);if(U4(Q))W(Q);else{let z=k.fromError(Q.error.code,Q.error.message,Q.error.data);W(z)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,Y,X){let{task:W}=X??{};if(!W){try{yield{type:"result",result:await this.request(Q,Y,X)}}catch(z){yield{type:"error",error:z instanceof k?z:new k(g.InternalError,String(z))}}return}let G;try{let z=await this.request(Q,k1,X);if(z.task)G=z.task.taskId,yield{type:"taskCreated",task:z.task};else throw new k(g.InternalError,"Task creation did not return a task");while(!0){let J=await this.getTask({taskId:G},X);if(yield{type:"taskStatus",task:J},z1(J.status)){if(J.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};else if(J.status==="failed")yield{type:"error",error:new k(g.InternalError,`Task ${G} failed`)};else if(J.status==="cancelled")yield{type:"error",error:new k(g.InternalError,`Task ${G} was cancelled`)};return}if(J.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},Y,X)};return}let $=J.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,$)),X?.signal?.throwIfAborted()}}catch(z){yield{type:"error",error:z instanceof k?z:new k(g.InternalError,String(z))}}}request(Q,Y,X){let{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z,task:J,relatedTask:$}=X??{};return new Promise((H,U)=>{let A=(V)=>{U(V)};if(!this._transport){A(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),J)this.assertTaskCapability(Q.method)}catch(V){A(V);return}X?.signal?.throwIfAborted();let B=this._requestMessageId++,K={...Q,jsonrpc:"2.0",id:B};if(X?.onprogress)this._progressHandlers.set(B,X.onprogress),K.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:B}};if(J)K.params={...K.params,task:J};if($)K.params={...K.params,_meta:{...K.params?._meta||{},[G1]:$}};let L=(V)=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(V)}},{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((E)=>this._onerror(Error(`Failed to send cancellation: ${E}`)));let S=V instanceof k?V:new k(g.RequestTimeout,String(V));U(S)};this._responseHandlers.set(B,(V)=>{if(X?.signal?.aborted)return;if(V instanceof Error)return U(V);try{let S=W1(Y,V.result);if(!S.success)U(S.error);else H(S.data)}catch(S){U(S)}}),X?.signal?.addEventListener("abort",()=>{L(X?.signal?.reason)});let O=X?.timeout??qA,M=()=>L(k.fromError(g.RequestTimeout,"Request timed out",{timeout:O}));this._setupTimeout(B,O,X?.maxTotalTimeout,M,X?.resetTimeoutOnProgress??!1);let N=$?.taskId;if(N){let V=(S)=>{let E=this._responseHandlers.get(B);if(E)E(S);else this._onerror(Error(`Response handler missing for side-channeled request ${B}`))};this._requestResolvers.set(B,V),this._enqueueTaskMessage(N,{type:"request",message:K,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(B),U(S)})}else this._transport.send(K,{relatedRequestId:W,resumptionToken:G,onresumptiontoken:z}).catch((V)=>{this._cleanupTimeout(B),U(V)})})}async getTask(Q,Y){return this.request({method:"tasks/get",params:Q},Z6,Y)}async getTaskResult(Q,Y,X){return this.request({method:"tasks/result",params:Q},Y,X)}async listTasks(Q,Y){return this.request({method:"tasks/list",params:Q},b6,Y)}async cancelTask(Q,Y){return this.request({method:"tasks/cancel",params:Q},CG,Y)}async notification(Q,Y){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let X=Y?.relatedTask?.taskId;if(X){let J={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[G1]:Y.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:J,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!Y?.relatedRequestId&&!Y?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let J={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[G1]:Y.relatedTask}}};this._transport?.send(J,Y).catch(($)=>this._onerror($))});return}let z={...Q,jsonrpc:"2.0"};if(Y?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[G1]:Y.relatedTask}}};await this._transport.send(z,Y)}setRequestHandler(Q,Y){let X=b9(Q);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(W,G)=>{let z=P9(Q,W);return Promise.resolve(Y(z,G))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,Y){let X=b9(Q);this._notificationHandlers.set(X,(W)=>{let G=P9(Q,W);return Promise.resolve(Y(G))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let Y=this._taskProgressTokens.get(Q);if(Y!==void 0)this._progressHandlers.delete(Y),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,Y,X){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,Y,X,W)}async _clearTaskQueue(Q,Y){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll(Q,Y);for(let W of X)if(W.type==="request"&&J9(W.message)){let G=W.message.id,z=this._requestResolvers.get(G);if(z)z(new k(g.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,Y){let X=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask(Q);if(W?.pollInterval)X=W.pollInterval}catch{}return new Promise((W,G)=>{if(Y.aborted){G(new k(g.InvalidRequest,"Request cancelled"));return}let z=setTimeout(W,X);Y.addEventListener("abort",()=>{clearTimeout(z),G(new k(g.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,Y){let X=this._taskStore;if(!X)throw Error("No task store configured");return{createTask:async(W)=>{if(!Q)throw Error("No request provided");return await X.createTask(W,Q.id,{method:Q.method,params:Q.params},Y)},getTask:async(W)=>{let G=await X.getTask(W,Y);if(!G)throw new k(g.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(W,G,z)=>{await X.storeTaskResult(W,G,z,Y);let J=await X.getTask(W,Y);if(J){let $=L4.parse({method:"notifications/tasks/status",params:J});if(await this.notification($),z1(J.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return X.getTaskResult(W,Y)},updateTaskStatus:async(W,G,z)=>{let J=await X.getTask(W,Y);if(!J)throw new k(g.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(z1(J.status))throw new k(g.InvalidParams,`Cannot update task "${W}" from terminal status "${J.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(W,G,z,Y);let $=await X.getTask(W,Y);if($){let H=L4.parse({method:"notifications/tasks/status",params:$});if(await this.notification(H),z1($.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return X.listTasks(W,Y)}}}}function uG(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function hG(Q,Y){let X={...Q};for(let W in Y){let G=W,z=Y[G];if(z===void 0)continue;let J=X[G];if(uG(J)&&uG(z))X[G]={...J,...z};else X[G]=z}return X}var F5=iY(NY(),1),O5=iY(q5(),1);function bM(){let Q=new F5.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return O5.default(Q),Q}class RY{constructor(Q){this._ajv=Q??bM()}getValidator(Q){let Y="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(X)=>{if(Y(X))return{valid:!0,data:X,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Y.errors)}}}}class CY{constructor(Q){this._server=Q}requestStream(Q,Y,X){return this._server.requestStream(Q,Y,X)}async getTask(Q,Y){return this._server.getTask({taskId:Q},Y)}async getTaskResult(Q,Y,X){return this._server.getTaskResult({taskId:Q},Y,X)}async listTasks(Q,Y){return this._server.listTasks(Q?{cursor:Q}:void 0,Y)}async cancelTask(Q,Y){return this._server.cancelTask({taskId:Q},Y)}}function M5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"tools/call":if(!Q.tools?.call)throw Error(`${X} does not support task creation for tools/call (required for ${Y})`);break;default:break}}function V5(Q,Y,X){if(!Q)throw Error(`${X} does not support task creation (required for ${Y})`);switch(Y){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${X} does not support task creation for sampling/createMessage (required for ${Y})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${X} does not support task creation for elicitation/create (required for ${Y})`);break;default:break}}class kY extends I9{constructor(Q,Y){super(Y);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(O4.options.map((X,W)=>[X,W])),this.isMessageIgnored=(X,W)=>{let G=this._loggingLevels.get(W);return G?this.LOG_LEVEL_SEVERITY.get(X)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=Y?.capabilities??{},this._instructions=Y?.instructions,this._jsonSchemaValidator=Y?.jsonSchemaValidator??new RY,this.setRequestHandler(U9,(X)=>this._oninitialize(X)),this.setNotificationHandler(A9,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(N9,async(X,W)=>{let G=W.sessionId||W.requestInfo?.headers["mcp-session-id"]||void 0,{level:z}=X.params,J=O4.safeParse(z);if(J.success)this._loggingLevels.set(G,J.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new CY(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=hG(this._capabilities,Q)}setRequestHandler(Q,Y){let W=A6(Q)?.method;if(!W)throw Error("Schema is missing a method literal");let G;if(R1(W)){let J=W;G=J._zod?.def?.value??J.value}else{let J=W;G=J._def?.value??J.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let J=async($,H)=>{let U=W1(F4,$);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new k(g.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:A}=U.data,B=await Promise.resolve(Y($,H));if(A.task){let L=W1(k1,B);if(!L.success){let O=L.error instanceof Error?L.error.message:String(L.error);throw new k(g.InvalidParams,`Invalid task creation result: ${O}`)}return L.data}let K=W1(I6,B);if(!K.success){let L=K.error instanceof Error?K.error.message:String(K.error);throw new k(g.InvalidParams,`Invalid tools/call result: ${L}`)}return K.data};return super.setRequestHandler(Q,J)}return super.setRequestHandler(Q,Y)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){V5(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;M5(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let Y=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:wG.includes(Y)?Y:G9,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},F6)}async createMessage(Q,Y){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let X=Q.messages[Q.messages.length-1],W=Array.isArray(X.content)?X.content:[X.content],G=W.some((H)=>H.type==="tool_result"),z=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,J=z?Array.isArray(z.content)?z.content:[z.content]:[],$=J.some((H)=>H.type==="tool_use");if(G){if(W.some((H)=>H.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!$)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if($){let H=new Set(J.filter((A)=>A.type==="tool_use").map((A)=>A.id)),U=new Set(W.filter((A)=>A.type==="tool_result").map((A)=>A.toolUseId));if(H.size!==U.size||![...H].every((A)=>U.has(A)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},w9,Y);return this.request({method:"sampling/createMessage",params:Q},Z9,Y)}async elicitInput(Q,Y){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let W=Q;return this.request({method:"elicitation/create",params:W},E6,Y)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let W=Q.mode==="form"?Q:{...Q,mode:"form"},G=await this.request({method:"elicitation/create",params:W},E6,Y);if(G.action==="accept"&&G.content&&W.requestedSchema)try{let J=this._jsonSchemaValidator.getValidator(W.requestedSchema)(G.content);if(!J.valid)throw new k(g.InvalidParams,`Elicitation response content does not match requested schema: ${J.errorMessage}`)}catch(z){if(z instanceof k)throw z;throw new k(g.InternalError,`Error validating elicitation response: ${z instanceof Error?z.message:String(z)}`)}return G}}}createElicitationCompletionNotifier(Q,Y){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},Y)}async listRoots(Q,Y){return this.request({method:"roots/list",params:Q},j9,Y)}async sendLoggingMessage(Q,Y){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,Y))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var N5={name:"@sequenzy/mcp",version:"0.0.54",mcpName:"io.github.sequenzy/mcp",description:"Sequenzy MCP server for AI-powered email marketing automation",type:"module",bin:{"sequenzy-mcp":"dist/index.js"},main:"./dist/index.js",exports:{".":"./dist/index.js","./server":"./dist/server.js","./runtime":"./dist/runtime.js","./server.json":"./server.json"},scripts:{dev:"bun --watch src/index.ts",build:"bun build src/index.ts src/server.ts src/runtime.ts --outdir dist --target node --minify",start:"node dist/index.js","type-check":"tsc --noEmit",test:"bun test","test:watch":"bun test --watch",prepublishOnly:"bun run build"},dependencies:{"@modelcontextprotocol/sdk":"^1.0.0"},devDependencies:{"@types/bun":"latest","@types/node":"^22.0.0","bun-types":"latest",typescript:"^5.8.0"},files:["dist","server.json"],keywords:["sequenzy","email","mcp","ai","claude","automation"],license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sequenzy/mcp.git"},homepage:"https://sequenzy.com",bugs:{url:"https://github.com/Sequenzy/mcp/issues"}};var vY=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],Z5={dashboard:"/dashboard/company/{companyId}",campaigns:"/dashboard/company/{companyId}/campaign",campaign:"/dashboard/company/{companyId}/campaign/{campaignId}",campaignPreview:"/dashboard/company/{companyId}/campaign/{campaignId}?step=review",campaignList:"/dashboard/company/{companyId}/campaign/list/{status}",sequences:"/dashboard/company/{companyId}/sequences",sequence:"/dashboard/company/{companyId}/sequences/{sequenceId}",sequenceList:"/dashboard/company/{companyId}/sequences/list/{status}",settings:"/dashboard/company/{companyId}/settings",settingsTab:"/dashboard/company/{companyId}/settings?tab={tab}",emails:"/dashboard/company/{companyId}/emails",email:"/dashboard/company/{companyId}/emails/{emailId}",subscribers:"/dashboard/company/{companyId}/subscribers",sentEmails:"/dashboard/company/{companyId}/sent-emails",emailSend:"/dashboard/company/{companyId}/sent-emails/{emailSendId}",segments:"/dashboard/company/{companyId}/segments",metrics:"/dashboard/company/{companyId}/metrics",transactional:"/dashboard/company/{companyId}/transactional",transactionalEmail:"/dashboard/company/{companyId}/transactional/{transactionalId}",domain:"/dashboard/company/{companyId}/settings/domain/{domainId}",domainVerify:"/dashboard/company/{companyId}/settings/domain/{domainId}/verify"};function IM(Q){let X=(Q??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return X.length>0?X:"https://sequenzy.com"}function f0(Q){let Y=Q?.trim();return Y?Y:void 0}function a0(Q){return encodeURIComponent(Q)}function Y0(Q,Y){return`${Q}${Y}`}function X0(Q,Y=""){return`/dashboard/company/${a0(Q)}${Y}`}function w5(Q,Y,X){return Y0(Q,`${X0(Y,"/settings")}?tab=${encodeURIComponent(X)}`)}function EM(Q,Y){let X=vY.map((W)=>[W,Y?w5(Q,Y,W):""]);return Object.fromEntries(X)}function D1(Q={},Y){let X=IM(Y),W=f0(Q.companyId),G={},z=EM(X,W);if(!W)return{appUrl:X,routeTemplates:Z5,settingsTabValues:vY,urls:G,settingsUrls:z};G.dashboard=Y0(X,X0(W)),G.campaigns=Y0(X,X0(W,"/campaign")),G.sequences=Y0(X,X0(W,"/sequences")),G.settings=Y0(X,X0(W,"/settings")),G.emails=Y0(X,X0(W,"/emails")),G.subscribers=Y0(X,X0(W,"/subscribers")),G.sentEmails=Y0(X,X0(W,"/sent-emails")),G.segments=Y0(X,X0(W,"/segments")),G.metrics=Y0(X,X0(W,"/metrics")),G.transactional=Y0(X,X0(W,"/transactional"));let J=f0(Q.campaignId);if(J)G.campaign=Y0(X,X0(W,`/campaign/${a0(J)}`)),G.campaignPreview=`${G.campaign}?step=review`;let $=f0(Q.sequenceId);if($)G.sequence=Y0(X,X0(W,`/sequences/${a0($)}`));let H=f0(Q.emailId)??f0(Q.templateId);if(H)G.email=Y0(X,X0(W,`/emails/${a0(H)}`)),G.template=G.email;let U=f0(Q.transactionalId);if(U)G.transactionalEmail=Y0(X,X0(W,`/transactional/${a0(U)}`));let A=f0(Q.emailSendId);if(A)G.emailSend=Y0(X,X0(W,`/sent-emails/${a0(A)}`));let B=f0(Q.domainId);if(B)G.domain=Y0(X,X0(W,`/settings/domain/${a0(B)}`)),G.domainVerify=`${G.domain}/verify`;let K=f0(Q.status);if(K)G.campaignList=Y0(X,X0(W,`/campaign/list/${a0(K)}`)),G.sequenceList=Y0(X,X0(W,`/sequences/list/${a0(K)}`));let L=f0(Q.settingsTab);if(L)G.settingsTab=w5(X,W,L);return{appUrl:X,routeTemplates:Z5,settingsTabValues:vY,urls:G,settingsUrls:z}}var j5=[{uri:"sequenzy://dashboard",name:"Dashboard Overview",description:"Live overview stats for the last 7 days",mimeType:"application/json"},{uri:"sequenzy://company",name:"Current Company",description:"The currently selected company, including localization settings",mimeType:"application/json"},{uri:"sequenzy://campaigns/recent",name:"Recent Campaigns",description:"Last 10 campaigns with status and basic stats",mimeType:"application/json"},{uri:"sequenzy://subscribers/recent",name:"Recent Subscribers",description:"Most recently added subscribers",mimeType:"application/json"},{uri:"sequenzy://subscribers/engaged",name:"Engaged Subscribers",description:"Most active/engaged subscribers",mimeType:"application/json"},{uri:"sequenzy://sequences",name:"Sequences",description:"All email sequences with status",mimeType:"application/json"},{uri:"sequenzy://templates",name:"Templates",description:"All available email templates with localization status",mimeType:"application/json"},{uri:"sequenzy://segments",name:"Segments",description:"All defined segments with subscriber counts",mimeType:"application/json"},{uri:"sequenzy://tags",name:"Tags",description:"All tags with usage counts",mimeType:"application/json"},{uri:"sequenzy://health",name:"Deliverability Health",description:"Email deliverability metrics and health status",mimeType:"application/json"},{uri:"sequenzy://app-routes",name:"Dashboard URL Routes",description:"Route templates and settings tabs for building Sequenzy dashboard links",mimeType:"application/json"}];async function b5(Q){try{let Y;switch(Q){case"sequenzy://dashboard":Y=await F("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let X=await F("GET","/api/v1/account"),W=q1()??X.currentCompanyId;if(!W)throw Error("No company available. Create or select a company first.");Y=await F("GET",`/api/v1/companies/${W}`);break}case"sequenzy://campaigns/recent":Y=await F("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":Y=await F("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":Y=await F("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":Y=await F("GET","/api/v1/sequences");break;case"sequenzy://templates":Y=await F("GET","/api/v1/templates");break;case"sequenzy://segments":Y=await F("GET","/api/v1/segments");break;case"sequenzy://tags":Y=await F("GET","/api/v1/tags");break;case"sequenzy://health":Y=await F("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":Y=D1();break;default:throw Error(`Unknown resource: ${Q}`)}return{contents:[{uri:Q,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(Y){return{contents:[{uri:Q,mimeType:"text/plain",text:P1(Y)}]}}}import{readFileSync as TM,statSync as SM}from"node:fs";import{basename as RM}from"node:path";var m4="Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Use this for editor-compatible content, including conditional and repeat blocks. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.",i1="Replacement Sequenzy email blocks. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`.",k5="Sequenzy email blocks. Provide blocks or html for email steps. Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`. Blocks can include repeat blocks over array variables such as items.",P5=500,LQ=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],qQ=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.complained","email.opened","email.clicked","email.unsubscribed","subscriber.invalid","subscriber.updated","subscriber.unsubscribed","sequence.finished","sequence.failed"],gY={status:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains"],emailProvider:["is","is_not","is_empty","is_not_empty"],added:["less_than","more_than"],firstName:["contains","not_contains","is_empty","is_not_empty"],lastName:["contains","not_contains","is_empty","is_not_empty"],list:["is","is_not","is_empty","is_not_empty"],emailSent:["is","is_not","at_least","less_than_count"],emailDelivered:["is","is_not","at_least","less_than_count"],emailOpened:["is","is_not","at_least","less_than_count"],emailClicked:["is","is_not","at_least","less_than_count"],emailBounced:["is","is_temporary_bounce","is_permanent_bounce","is_not","at_least","less_than_count"],emailComplained:["is","is_not","at_least","less_than_count"],attribute:["is","is_not","is_empty","is_not_empty","gte","lte","gt","lt","contains","not_contains"],event:["is","is_not","at_least","less_than_count"],segment:["is","is_not"],stripeProduct:["is","is_not","at_least","less_than_count"],stripeCurrentProduct:["is","is_not","gte","lte","gt","lt"],stripeTrialProduct:["is","is_not","gte","lte","gt","lt"]},CM=Object.entries(gY).map(([Q,Y])=>`${Q}: ${Y.join(", ")}`).join("; "),I5={type:"object",properties:{id:{type:"string",description:"Optional filter ID. Any stable string works; one will be generated if omitted."},field:{type:"string",enum:["status","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct"],description:"Filter field. Use `event` for custom subscriber events, `segment` for saved segment membership, and `stripeProduct`/`stripeCurrentProduct`/`stripeTrialProduct` for Stripe product-based segments. Engagement fields (`emailSent`, `emailDelivered`, `emailOpened`, `emailClicked`, `emailBounced`, `emailComplained`) accept a time range as the value or a specific campaign via `campaign:<campaign_id>`."},operator:{type:"string",enum:["is","is_not","is_empty","is_not_empty","contains","not_contains","less_than","more_than","is_temporary_bounce","is_permanent_bounce","at_least","less_than_count","gte","lte","gt","lt"],description:`Filter operator. Allowed operators by field: ${CM}.`},value:{type:"string",description:"Filter value. For custom attribute empty checks, use `attributeName:` such as `last_logged_in:`. Event examples: `saas.purchase:30d`, `saas.purchase:all`, or `saas.purchase:5:30d` for thresholds. Segment values are segment IDs. Stripe product examples: `prod_123` for bought/didn't buy/current/trialing, `prod_123:3` for payment thresholds, `prod_123:is_canceled` for products set to cancel, `prod_123:cancels_at:2026-05-26`, `prod_123:end_at:2026-05-26`, or `prod_123:start_at:7 days ago` for product-scoped dates. Engagement examples: `7d`, `30d`, `90d`, `180d`, `all` for rolling time windows, or `campaign:<campaign_id>` to scope to a specific sent campaign (use `list_campaigns` to find IDs)."}},required:["field","operator","value"],additionalProperties:!1},E5={type:"object",properties:{kind:{type:"string",enum:["group"]},id:{type:"string",description:"Stable group ID. Any string works; one will be generated if omitted."},joinOperator:{type:"string",enum:["and","or"],description:"How children in this group combine."},children:{type:"array",minItems:1,items:{type:"object",description:'Either a filter leaf (`kind: "filter"`) or another group (`kind: "group"`).'}}},required:["kind","joinOperator","children"],additionalProperties:!0};function uY(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(typeof Y!=="object"||Y===null)return Y;let X=Y;if(typeof X.id==="string"&&X.id.trim()!=="")return X;return{...X,id:crypto.randomUUID()}})}function hY(Q){if(typeof Q!=="object"||Q===null)return Q;let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=uY([Y]);return Array.isArray(X)?X[0]:Y}if(Y.kind!=="group")return Q;return{...Y,id:typeof Y.id==="string"&&Y.id.trim()!==""?Y.id:crypto.randomUUID(),children:Array.isArray(Y.children)?Y.children.map(hY):[]}}function kM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(0,Y).trim().length>0}function vM(Q){let Y=Q.indexOf(":");return Y!==-1&&Q.substring(Y+1).trim().length>0}function T5(Q){if(Q==="all")return!0;let Y=Q.match(/^(\d+)d$/);if(!Y?.[1])return!1;let X=Number.parseInt(Y[1],10);return Number.isInteger(X)&&X>0}function xM(Q,Y){let X=Y.split(":");if(Q==="at_least"||Q==="less_than_count"){if(X.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let z=X.slice(0,-2).join(":").trim(),J=X.at(-2),$=X.at(-1),H=J===void 0?Number.NaN:Number.parseInt(J,10);return z&&Number.isInteger(H)&&H>0&&$!==void 0&&T5($)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(X.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let W=X.slice(0,-1).join(":").trim(),G=X.at(-1);return W&&G!==void 0&&T5(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function _M(Q){let Y=Q.indexOf(":");if(Y===-1)return{productId:Q,subfilter:null,rawValue:null};let X=Q.substring(0,Y),W=Q.substring(Y+1),G=W.indexOf(":");if(G===-1)return{productId:X,subfilter:W,rawValue:null};return{productId:X,subfilter:W.substring(0,G),rawValue:W.substring(G+1)}}function yM(Q){return Q.trim().toLowerCase().replace(/[-\s]+/g,"_")}function gM(Q){return["is_canceled","is_cancelled","canceled","cancelled","will_cancel","cancel_at_period_end","is_not_canceled","is_not_cancelled","not_canceled","not_cancelled","will_not_cancel"].includes(Q)}function uM(Q,Y){if(Y==="cancels_at"||Y==="cancel_at"||Y==="cancellation_at")return!0;if(Q==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(Y);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(Y)}function hM(Q){return["is","is_not","gte","lte","gt","lt"].includes(Q)}function fM(Q,Y,X){if(Q==="stripeProduct"){if(Y!=="at_least"&&Y!=="less_than_count")return null;let $=X.indexOf(":");if($===-1)return null;let H=X.substring(0,$).trim(),U=Number.parseInt(X.substring($+1).trim(),10);return H&&Number.isInteger(U)&&U>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(Q!=="stripeCurrentProduct"&&Q!=="stripeTrialProduct")return null;let{productId:W,subfilter:G,rawValue:z}=_M(X);if(!W.trim())return"Stripe product filters must include a product ID.";if(!G)return Y==="is"||Y==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let J=yM(G);if(gM(J))return Y==="is"||Y==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!uM(Q,J))return`Unsupported Stripe product subfilter "${G}".`;if(!hM(Y))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return z?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}function lY(Q){if(typeof Q!=="object"||Q===null)return"Segment filters must be objects.";let Y=Q,X=Y.field,W=Y.operator,G=Y.value;if(typeof X!=="string"||!(X in gY))return`Unsupported segment filter field "${String(X)}".`;if(typeof W!=="string")return`Segment filter "${X}" must include an operator.`;let z=gY[X];if(!z.includes(W))return`Operator "${W}" is not supported for ${X} filters. Use one of: ${z.join(", ")}.`;if(W!=="is_empty"&&W!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${X}" must include a value.`;if(X==="attribute"&&typeof G==="string"){if(!kM(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(W!=="is_empty"&&W!=="is_not_empty"&&!vM(G))return'Attribute filters must include a value after "attributeName:".'}if(X==="event"&&typeof G==="string"){let J=xM(W,G);if(J)return J}if((X==="stripeProduct"||X==="stripeCurrentProduct"||X==="stripeTrialProduct")&&typeof G==="string"){let J=fM(X,W,G);if(J)return J}if(X==="tag"&&(W==="contains"||W==="not_contains")){if(!(typeof G==="string"&&G.split(",").map(($)=>$.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function mY(Q){if(typeof Q!=="object"||Q===null)return[];let Y=Q;if(Y.kind==="filter"||"field"in Y||"operator"in Y||"value"in Y){let X=lY(Y);return X?[X]:[]}if(Array.isArray(Y.children))return Y.children.flatMap(mY);return[]}function b1(Q,Y,X){if(Y.html!==void 0&&Y.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`, not both.`);if(Y.blocks!==void 0&&!Array.isArray(Y.blocks))throw Error(`\`blocks\` must be an array when calling \`${Q}\`.`);if(X?.requireContent&&Y.html===void 0&&Y.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${Q}\`.`)}function DQ(Q,Y){if(Y.labels===void 0)return;if(!Array.isArray(Y.labels))throw Error(`\`labels\` must be an array when calling \`${Q}\`.`);if(Y.labels.some((X)=>typeof X!=="string"||X.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${Q}\`.`)}function lM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!Y&&!X)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `create_segment`.");let W=Y?Q.filters.flatMap((G)=>{let z=lY(G);return z?[z]:[]}):mY(Q.root);if(W.length>0)throw Error(W[0]??"Invalid segment filter in `create_segment`.")}function mM(Q){let Y=Q.filters!==void 0,X=Q.root!==void 0;if(Y&&X)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(Q.name===void 0&&Q.filterJoinOperator===void 0&&!Y&&!X)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(Y){if(!Array.isArray(Q.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(Q.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(X&&(typeof Q.root!=="object"||Q.root===null))throw Error("`root` must be an object when calling `update_segment`.");let W=Y?Q.filters.flatMap((G)=>{let z=lY(G);return z?[z]:[]}):X?mY(Q.root):[];if(W.length>0)throw Error(W[0]??"Invalid segment filter in `update_segment`.")}function cM(Q){if(Q.clearEnrollmentFieldPath===!0&&Q.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");let Y={...Q};if(delete Y.clearEnrollmentFieldPath,Q.clearEnrollmentFieldPath===!0)Y.enrollmentFieldPath=null;return Y}function pM(Q){let Y=Z(Q,"subscriberId"),X=Q.fieldValues,W=X===void 0?void 0:Array.isArray(X)?X:void 0;if(X!==void 0&&W===void 0)throw Error("`fieldValues` must be an array when calling `cancel_sequence_enrollments`.");let G=W?.map(($)=>typeof $==="string"?$.trim():"").filter(($)=>$.length>0)??[];if(W?.some(($)=>typeof $!=="string")||W!==void 0&&G.length===0)throw Error("`fieldValues` must contain at least one non-empty string when calling `cancel_sequence_enrollments`.");if(Y!==void 0===G.length>0)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `subscriberId` or `fieldValues`.");let z=Z(Q,"fieldPath"),J=Z(Q,"reason");return{...Y!==void 0&&{subscriberId:Y},...z!==void 0&&{fieldPath:z},...G.length>0&&{fieldValues:G},...typeof Q.dryRun==="boolean"&&{dryRun:Q.dryRun},...J!==void 0&&{reason:J}}}function iM(Q){b1("create_campaign",Q),DQ("create_campaign",Q);let Y=Z(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0,G=Q.templateId!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(Y&&(X||W||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!Y&&Z(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function rM(Q){if(Z(Q,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(Q.targetLists!==void 0&&!B0(Q.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(Q.sendTimeOptimization!==void 0){if(typeof Q.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(Q.spreadOverHours!==void 0){if(typeof Q.spreadOverHours!=="number"||!Number.isInteger(Q.spreadOverHours)||Q.spreadOverHours<1||Q.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}}function nM(Q){b1("create_transactional_email",Q);let Y=Z(Q,"prompt")!==void 0,X=Q.html!==void 0,W=Q.blocks!==void 0;if(Q.prompt!==void 0&&!Y)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(Y&&(X||W))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!Y&&(Q.style!==void 0||Q.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!Y&&!X&&!W)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!Y&&Z(Q,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var S5={type:"object",description:"A step to create inside a branch path. Use type:'delay' for a standalone delay, type:'email' for an email, or type:'create_discount' for a discount action.",properties:{type:{type:"string",enum:["email","delay","create_discount","discount","webhook"],description:"Branch path step type. Omit for email steps; use delay for standalone waits."},nodeType:{type:"string",enum:["logic_delay","action_email","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","action_webhook"],description:"Advanced branch path node type. Prefer type unless creating a non-email action."},config:{type:"object",description:"Config for advanced nodeType steps such as tag/list/webhook/wait-for-event actions.",additionalProperties:!0},subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:k5,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps."},delay:{type:"object",description:"Delay before this step, or the delay duration when type is delay.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}}},delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:"Discount configuration for create_discount steps. Same shape as create_sequence steps.",additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"}},additionalProperties:!1};function dM(Q){if(!Q||typeof Q!=="object")return null;let Y=Q;if(Y.success!==!1)return null;if(typeof Y.error==="string")return Error(Y.error);if(Y.error&&typeof Y.error==="object"&&typeof Y.error.message==="string")return Error(Y.error.message);if(typeof Y.message==="string")return Error(Y.message);return Error("The tool returned an unsuccessful response.")}function B0(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function R5(Q){return Q.trim().toLowerCase().replace(/\s+/g,"-")}function oM(Q){let Y=new URLSearchParams;if(typeof Q.query==="string"&&Q.query.trim()!=="")Y.set("query",Q.query.trim());if(Array.isArray(Q.tags)&&Q.tags.length>0)Y.set("tags",Q.tags.filter((X)=>typeof X==="string"&&X.trim()!=="").join(","));if(typeof Q.list==="string"&&Q.list.trim()!=="")Y.set("list",Q.list.trim());if(typeof Q.listId==="string"&&Q.listId.trim()!=="")Y.set("listId",Q.listId.trim());if(typeof Q.listName==="string"&&Q.listName.trim()!=="")Y.set("listName",Q.listName.trim());if(typeof Q.segmentId==="string"&&Q.segmentId.trim()!=="")Y.set("segmentId",Q.segmentId);if(typeof Q.status==="string"&&Q.status.trim()!=="")Y.set("status",Q.status.trim());return Y.set("page",String(Q.page)),Y.set("limit",String(Q.pageSize)),Y}async function tM(Q,Y){let X=typeof Q.limit==="number"&&Number.isFinite(Q.limit)?Math.max(1,Math.trunc(Q.limit)):void 0,W=Math.min(100,Math.max(1,X??100)),G=[],z=1,J=0,$=0,H=0;while(!0){let A=oM({query:Q.query,tags:Q.tags,list:Q.list,listId:Q.listId,listName:Q.listName,segmentId:Q.segmentId,status:Q.status,page:z,pageSize:W}),B=await F("GET",`/api/v1/subscribers?${A.toString()}`,void 0,Y);J=B.pagination?.total??B.subscribers.length,$=B.pagination?.totalPages??1,H+=1,G.push(...B.subscribers??[]);let K=X!==void 0&&G.length>=X,L=B.pagination?z>=B.pagination.totalPages:(B.subscribers??[]).length<W;if(K||L)break;z+=1}let U=X!==void 0?G.slice(0,X):G;return{success:!0,subscribers:U,pagination:{page:1,limit:W,total:J,totalPages:$,fetchedPages:H},returned:U.length,truncated:X!==void 0&&J>0&&U.length<J}}function aM(Q){let Y=typeof Q.email==="string"&&Q.email.trim()!==""?Q.email.trim():void 0,X=typeof Q.externalId==="string"&&Q.externalId.trim()!==""?Q.externalId.trim():void 0;return{...Y?{email:Y}:{},...X?{externalId:X}:{}}}function c4(Q,Y){let X=aM(Y);if(!X.email&&!X.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${Q}\`.`);return X}function fY(Q){if(Q.email)return`/api/v1/subscribers/${encodeURIComponent(Q.email)}`;return`/api/v1/subscribers/external?externalId=${encodeURIComponent(String(Q.externalId))}`}async function xY(Q,Y){return F("GET",fY(Q),void 0,Y)}function Z(Q,Y){let X=Q[Y];if(typeof X!=="string")return;let W=X.trim();return W.length>0?W:void 0}function x(Q,Y,X){let W=Z(Y,X);if(W===void 0)throw Error(`\`${X}\` is required when calling \`${Q}\`.`);return W}function s0(Q,Y,X,W){let G=Z(Y,X);if(G===void 0)return;if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function _Y(Q,Y,X,W){let G=x(Q,Y,X);if(!W.includes(G))throw Error(`\`${X}\` must be one of ${W.join(", ")} when calling \`${Q}\`.`);return G}function p4(Q,Y,X,W,G){let z=Y[X];if(z===void 0)return;if(typeof z!=="number"||!Number.isInteger(z)||z<W||z>G)throw Error(`\`${X}\` must be an integer between ${W} and ${G} when calling \`${Q}\`.`);return z}function C5(Q,Y){if(Y.events===void 0)return;if(!Array.isArray(Y.events))throw Error(`\`events\` must be an array when calling \`${Q}\`.`);let X=Y.events.map((W,G)=>{if(typeof W!=="string"||!qQ.includes(W))throw Error(`\`events\` item ${G+1} must be one of ${qQ.join(", ")} when calling \`${Q}\`.`);return W});if(X.length===0)throw Error(`\`events\` must include at least one event type when calling \`${Q}\`.`);return X}function yY(Q,Y){if(!Array.isArray(Y.emails))throw Error(`\`emails\` must be an array when calling \`${Q}\`.`);let X=[];if(Y.emails.forEach((W,G)=>{if(typeof W!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${Q}\`.`);let z=W.trim();if(z.length>0)X.push(z)}),X.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${Q}\`.`);if(X.length>P5)throw Error(`\`emails\` must include no more than ${P5} email addresses when calling \`${Q}\`. Split larger batches into multiple calls.`);return X}var sM={pdf:"application/pdf",epub:"application/epub+zip",zip:"application/zip",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",txt:"text/plain",csv:"text/csv"};function eM(Q){let Y=Q.split(".").pop()?.toLowerCase()??"";return sM[Y]??null}var QV=104857600;async function YV(Q,Y){if(!dY())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. Host the file somewhere public and pass `url` instead.");let X=eM(Q);if(!X)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let W=SM(Q).size;if(W>QV)throw Error(`File is too large (${Math.round(W/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=TM(Q),z=await F("POST","/api/v1/products/delivery/upload-url",{filename:RM(Q),contentType:X,fileSizeBytes:W},Y),J=await fetch(z.uploadUrl,{method:"PUT",headers:{"Content-Type":X},body:G});if(!J.ok)throw Error(`File upload failed (${J.status})`);return{url:z.publicUrl,fileName:z.fileName,fileSizeBytes:W,mimeType:X}}async function v5(Q){let Y=Z(Q,"companyId");if(Y)return Y;let X=q1();if(X)return X;try{return(await F("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}function i4(Q,Y){if(!B0(Q)||!Y)return Q;return{...Q,url:Y}}function x5(Q,Y){if(!B0(Q))return Q;return{...Q,...Y.campaign!==void 0&&{url:Y.campaign},...Y.campaignPreview!==void 0&&{previewUrl:Y.campaignPreview}}}function KQ(Q,Y,X){if(!Array.isArray(Q)||!Y)return Q;return Q.map((W)=>{if(!B0(W))return W;let G=Z(W,"id");if(!G)return W;let z=D1({companyId:Y,...X==="campaign"&&{campaignId:G},...X==="sequence"&&{sequenceId:G},...X==="template"&&{emailId:G},...X==="transactional"&&{transactionalId:G}});if(X==="campaign")return x5(W,z.urls);let J=X==="sequence"?z.urls.sequence:X==="template"?z.urls.email:z.urls.transactionalEmail;return i4(W,J)})}function XV(Q){if(!Array.isArray(Q))return Q;return Q.map((Y)=>{if(!B0(Y))return Y;let X=Z(Y,"id");if(!X)return Y;let W=D1({companyId:X});return{...Y,url:W.urls.dashboard,settingsUrl:W.urls.settings}})}var WV=new Set(["get_account","select_company","create_company","get_company","list_campaigns","get_campaign","get_email_send","create_campaign","update_campaign","schedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","list_sequences","get_sequence","create_sequence","update_sequence","enable_sequence","disable_sequence","cancel_sequence_enrollments","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","list_templates","get_template","create_template","update_template","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function GV(Q,Y,X){if(!B0(X)||!WV.has(Q))return X;let W=B0(X.company)?X.company:void 0,z=Z(X,"selectedCompanyId")??Z(X,"currentCompanyId")??Z(X,"companyId")??(W?Z(W,"id"):void 0)??(W?Z(W,"companyId"):void 0)??await v5(Y);if(!z)return X;let J=B0(X.campaign)?X.campaign:void 0,$=B0(X.sequence)?X.sequence:void 0,H=B0(X.template)?X.template:void 0,U=B0(X.transactional)&&!Array.isArray(X.transactional)?X.transactional:void 0,A={companyId:z,campaignId:Z(Y,"campaignId")??Z(X,"campaignId")??(J?Z(J,"id"):void 0),sequenceId:Z(Y,"sequenceId")??Z(X,"sequenceId")??($?Z($,"id"):void 0),emailId:Z(X,"templateId")??(H?Z(H,"id"):void 0)??(U?Z(U,"emailId"):void 0)??Z(Y,"templateId"),transactionalId:Z(Y,"transactionalId")??(U?Z(U,"id"):void 0)??Z(Y,"idOrSlug"),emailSendId:Z(Y,"emailSendId")??Z(X,"emailSendId")??(B0(X.emailSend)?Z(X.emailSend,"id"):void 0),status:Z(Y,"status")},B=D1(A),K=W?D1({companyId:z}):void 0;return{...X,...Array.isArray(X.companies)&&{companies:XV(X.companies)},...Array.isArray(X.campaigns)&&{campaigns:KQ(X.campaigns,z,"campaign")},...Array.isArray(X.sequences)&&{sequences:KQ(X.sequences,z,"sequence")},...Array.isArray(X.templates)&&{templates:KQ(X.templates,z,"template")},...Array.isArray(X.transactional)&&{transactional:KQ(X.transactional,z,"transactional")},...W&&K!==void 0&&{company:{...W,url:K.urls.dashboard,settingsUrl:K.urls.settings}},...J&&B.urls.campaign!==void 0&&{campaign:x5(J,B.urls)},...$&&B.urls.sequence!==void 0&&{sequence:i4($,B.urls.sequence)},...H&&B.urls.email!==void 0&&{template:i4(H,B.urls.email)},...U&&B.urls.transactionalEmail!==void 0&&{transactional:i4(U,B.urls.transactionalEmail)},...B0(X.emailSend)&&B.urls.emailSend!==void 0&&{emailSend:i4(X.emailSend,B.urls.emailSend)},appUrls:B.urls}}var _5=[{name:"get_account",description:`Get current account information including available companies. IMPORTANT: If you have access to multiple companies, you MUST either:
29
29
  1. Call select_company first to choose which company to work with, OR
30
30
  2. Pass companyId explicitly in each tool call
31
31
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sequenzy/mcp",
3
- "version": "0.0.53",
3
+ "version": "0.0.54",
4
4
  "mcpName": "io.github.sequenzy/mcp",
5
5
  "description": "Sequenzy MCP server for AI-powered email marketing automation",
6
6
  "type": "module",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/Sequenzy/mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.0.53",
9
+ "version": "0.0.54",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@sequenzy/mcp",
14
- "version": "0.0.53",
14
+ "version": "0.0.54",
15
15
  "runtime": "node",
16
16
  "transport": {
17
17
  "type": "stdio"