@sequenzy/mcp 0.0.149 → 0.0.150
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 +2 -2
- package/dist/server.js +2 -2
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -26,11 +26,11 @@ var Kz=Object.create;var{getPrototypeOf:Zz,defineProperty:V$,getOwnPropertyNames
|
|
|
26
26
|
newResult[${k}] = ${v}.value;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
`)}B.write("payload.value = newResult;"),B.write("return payload;");let S=B.compile();return(C,v)=>S(U,C,v)},J,w=u1,Y=!_4.jitless,H=Y&&N$.value,z=W.catchall,F;$._zod.parse=(U,B)=>{F??(F=X.value);let K=U.value;if(!w(K))return U.issues.push({expected:"object",code:"invalid_type",input:K,inst:$}),U;if(Y&&H&&B?.async===!1&&B.jitless!==!0){if(!J)J=G(W.shape);if(U=J(U,B),!z)return U;return _G([],K,U,B,F,$)}return Q(U,B)}});function rX($,W,Q,X){for(let J of $)if(J.issues.length===0)return W.value=J.value,W;let G=$.filter((J)=>!N1(J));if(G.length===1)return W.value=G[0].value,G[0];return W.issues.push({code:"invalid_union",input:W.value,inst:Q,errors:$.map((J)=>J.issues.map((w)=>n0(w,X,f0())))}),W}var f$=V("$ZodUnion",($,W)=>{$0.init($,W),s($._zod,"optin",()=>W.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),s($._zod,"optout",()=>W.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),s($._zod,"values",()=>{if(W.options.every((G)=>G._zod.values))return new Set(W.options.flatMap((G)=>Array.from(G._zod.values)));return}),s($._zod,"pattern",()=>{if(W.options.every((G)=>G._zod.pattern)){let G=W.options.map((J)=>J._zod.pattern);return new RegExp(`^(${G.map((J)=>_6(J.source)).join("|")})$`)}return});let Q=W.options.length===1,X=W.options[0]._zod.run;$._zod.parse=(G,J)=>{if(Q)return X(G,J);let w=!1,Y=[];for(let b of W.options){let H=b._zod.run({value:G.value,issues:[]},J);if(H instanceof Promise)Y.push(H),w=!0;else{if(H.issues.length===0)return H;Y.push(H)}}if(!w)return rX(Y,G,$,J);return Promise.all(Y).then((b)=>{return rX(b,G,$,J)})}}),hG=V("$ZodDiscriminatedUnion",($,W)=>{f$.init($,W);let Q=$._zod.parse;s($._zod,"propValues",()=>{let G={};for(let J of W.options){let w=J._zod.propValues;if(!w||Object.keys(w).length===0)throw Error(`Invalid discriminated union option at index "${W.options.indexOf(J)}"`);for(let[Y,b]of Object.entries(w)){if(!G[Y])G[Y]=new Set;for(let H of b)G[Y].add(H)}}return G});let X=$6(()=>{let G=W.options,J=new Map;for(let w of G){let Y=w._zod.propValues?.[W.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${W.options.indexOf(w)}"`);for(let b of Y){if(J.has(b))throw Error(`Duplicate discriminator value "${String(b)}"`);J.set(b,w)}}return J});$._zod.parse=(G,J)=>{let w=G.value;if(!u1(w))return G.issues.push({code:"invalid_type",expected:"object",input:w,inst:$}),G;let Y=X.value.get(w?.[W.discriminator]);if(Y)return Y._zod.run(G,J);if(W.unionFallback)return Q(G,J);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:W.discriminator,input:w,path:[W.discriminator],inst:$}),G}}),yG=V("$ZodIntersection",($,W)=>{$0.init($,W),$._zod.parse=(Q,X)=>{let G=Q.value,J=W.left._zod.run({value:G,issues:[]},X),w=W.right._zod.run({value:G,issues:[]},X);if(J instanceof Promise||w instanceof Promise)return Promise.all([J,w]).then(([b,H])=>{return sX(Q,b,H)});return sX(Q,J,w)}});function h$($,W){if($===W)return{valid:!0,data:$};if($ instanceof Date&&W instanceof Date&&+$===+W)return{valid:!0,data:$};if(I1($)&&I1(W)){let Q=Object.keys(W),X=Object.keys($).filter((J)=>Q.indexOf(J)!==-1),G={...$,...W};for(let J of X){let w=h$($[J],W[J]);if(!w.valid)return{valid:!1,mergeErrorPath:[J,...w.mergeErrorPath]};G[J]=w.data}return{valid:!0,data:G}}if(Array.isArray($)&&Array.isArray(W)){if($.length!==W.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let X=0;X<$.length;X++){let G=$[X],J=W[X],w=h$(G,J);if(!w.valid)return{valid:!1,mergeErrorPath:[X,...w.mergeErrorPath]};Q.push(w.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function sX($,W,Q){if(W.issues.length)$.issues.push(...W.issues);if(Q.issues.length)$.issues.push(...Q.issues);if(N1($))return $;let X=h$(W.value,Q.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}var fG=V("$ZodRecord",($,W)=>{$0.init($,W),$._zod.parse=(Q,X)=>{let G=Q.value;if(!I1(G))return Q.issues.push({expected:"record",code:"invalid_type",input:G,inst:$}),Q;let J=[];if(W.keyType._zod.values){let w=W.keyType._zod.values;Q.value={};for(let b of w)if(typeof b==="string"||typeof b==="number"||typeof b==="symbol"){let H=W.valueType._zod.run({value:G[b],issues:[]},X);if(H instanceof Promise)J.push(H.then((z)=>{if(z.issues.length)Q.issues.push(...H1(b,z.issues));Q.value[b]=z.value}));else{if(H.issues.length)Q.issues.push(...H1(b,H.issues));Q.value[b]=H.value}}let Y;for(let b in G)if(!w.has(b))Y=Y??[],Y.push(b);if(Y&&Y.length>0)Q.issues.push({code:"unrecognized_keys",input:G,inst:$,keys:Y})}else{Q.value={};for(let w of Reflect.ownKeys(G)){if(w==="__proto__")continue;let Y=W.keyType._zod.run({value:w,issues:[]},X);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){Q.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((H)=>n0(H,X,f0())),input:w,path:[w],inst:$}),Q.value[Y.value]=Y.value;continue}let b=W.valueType._zod.run({value:G[w],issues:[]},X);if(b instanceof Promise)J.push(b.then((H)=>{if(H.issues.length)Q.issues.push(...H1(w,H.issues));Q.value[Y.value]=H.value}));else{if(b.issues.length)Q.issues.push(...H1(w,b.issues));Q.value[Y.value]=b.value}}}if(J.length)return Promise.all(J).then(()=>Q);return Q}});var uG=V("$ZodEnum",($,W)=>{$0.init($,W);let Q=q$(W.entries),X=new Set(Q);$._zod.values=X,$._zod.pattern=new RegExp(`^(${Q.filter((G)=>E$.has(typeof G)).map((G)=>typeof G==="string"?b1(G):G.toString()).join("|")})$`),$._zod.parse=(G,J)=>{let w=G.value;if(X.has(w))return G;return G.issues.push({code:"invalid_value",values:Q,input:w,inst:$}),G}}),cG=V("$ZodLiteral",($,W)=>{if($0.init($,W),W.values.length===0)throw Error("Cannot create literal schema with no valid values");$._zod.values=new Set(W.values),$._zod.pattern=new RegExp(`^(${W.values.map((Q)=>typeof Q==="string"?b1(Q):Q?b1(Q.toString()):String(Q)).join("|")})$`),$._zod.parse=(Q,X)=>{let G=Q.value;if($._zod.values.has(G))return Q;return Q.issues.push({code:"invalid_value",values:W.values,input:G,inst:$}),Q}});var mG=V("$ZodTransform",($,W)=>{$0.init($,W),$._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new C6($.constructor.name);let G=W.transform(Q.value,Q);if(X.async)return(G instanceof Promise?G:Promise.resolve(G)).then((w)=>{return Q.value=w,Q});if(G instanceof Promise)throw new Y1;return Q.value=G,Q}});function aX($,W){if($.issues.length&&W===void 0)return{issues:[],value:void 0};return $}var lG=V("$ZodOptional",($,W)=>{$0.init($,W),$._zod.optin="optional",$._zod.optout="optional",s($._zod,"values",()=>{return W.innerType._zod.values?new Set([...W.innerType._zod.values,void 0]):void 0}),s($._zod,"pattern",()=>{let Q=W.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)})?$`):void 0}),$._zod.parse=(Q,X)=>{if(W.innerType._zod.optin==="optional"){let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>aX(J,Q.value));return aX(G,Q.value)}if(Q.value===void 0)return Q;return W.innerType._zod.run(Q,X)}}),gG=V("$ZodNullable",($,W)=>{$0.init($,W),s($._zod,"optin",()=>W.innerType._zod.optin),s($._zod,"optout",()=>W.innerType._zod.optout),s($._zod,"pattern",()=>{let Q=W.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)}|null)$`):void 0}),s($._zod,"values",()=>{return W.innerType._zod.values?new Set([...W.innerType._zod.values,null]):void 0}),$._zod.parse=(Q,X)=>{if(Q.value===null)return Q;return W.innerType._zod.run(Q,X)}}),pG=V("$ZodDefault",($,W)=>{$0.init($,W),$._zod.optin="optional",s($._zod,"values",()=>W.innerType._zod.values),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);if(Q.value===void 0)return Q.value=W.defaultValue,Q;let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>eX(J,W));return eX(G,W)}});function eX($,W){if($.value===void 0)$.value=W.defaultValue;return $}var iG=V("$ZodPrefault",($,W)=>{$0.init($,W),$._zod.optin="optional",s($._zod,"values",()=>W.innerType._zod.values),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);if(Q.value===void 0)Q.value=W.defaultValue;return W.innerType._zod.run(Q,X)}}),nG=V("$ZodNonOptional",($,W)=>{$0.init($,W),s($._zod,"values",()=>{let Q=W.innerType._zod.values;return Q?new Set([...Q].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(Q,X)=>{let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>$G(J,$));return $G(G,$)}});function $G($,W){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:W});return $}var dG=V("$ZodCatch",($,W)=>{$0.init($,W),s($._zod,"optin",()=>W.innerType._zod.optin),s($._zod,"optout",()=>W.innerType._zod.optout),s($._zod,"values",()=>W.innerType._zod.values),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>{if(Q.value=J.value,J.issues.length)Q.value=W.catchValue({...Q,error:{issues:J.issues.map((w)=>n0(w,X,f0()))},input:Q.value}),Q.issues=[];return Q});if(Q.value=G.value,G.issues.length)Q.value=W.catchValue({...Q,error:{issues:G.issues.map((J)=>n0(J,X,f0()))},input:Q.value}),Q.issues=[];return Q}});var oG=V("$ZodPipe",($,W)=>{$0.init($,W),s($._zod,"values",()=>W.in._zod.values),s($._zod,"optin",()=>W.in._zod.optin),s($._zod,"optout",()=>W.out._zod.optout),s($._zod,"propValues",()=>W.in._zod.propValues),$._zod.parse=(Q,X)=>{if(X.direction==="backward"){let J=W.out._zod.run(Q,X);if(J instanceof Promise)return J.then((w)=>p4(w,W.in,X));return p4(J,W.in,X)}let G=W.in._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>p4(J,W.out,X));return p4(G,W.out,X)}});function p4($,W,Q){if($.issues.length)return $.aborted=!0,$;return W._zod.run({value:$.value,issues:$.issues},Q)}var tG=V("$ZodReadonly",($,W)=>{$0.init($,W),s($._zod,"propValues",()=>W.innerType._zod.propValues),s($._zod,"values",()=>W.innerType._zod.values),s($._zod,"optin",()=>W.innerType._zod.optin),s($._zod,"optout",()=>W.innerType._zod.optout),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then(WG);return WG(G)}});function WG($){return $.value=Object.freeze($.value),$}var rG=V("$ZodCustom",($,W)=>{L0.init($,W),$0.init($,W),$._zod.parse=(Q,X)=>{return Q},$._zod.check=(Q)=>{let X=Q.value,G=W.fn(X);if(G instanceof Promise)return G.then((J)=>QG(J,Q,X,$));QG(G,Q,X,$);return}});function QG($,W,Q,X){if(!$){let G={code:"custom",input:Q,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)G.params=X._zod.def.params;W.issues.push(W6(G))}}var DD=($)=>{let W=typeof $;switch(W){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return W},FD=()=>{let $={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 W(X){return $[X]??null}let Q={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(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${DD(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${f4(X.values[0])}`;return`Invalid option: expected one of ${x4(X.values,"|")}`;case"too_big":{let G=X.inclusive?"<=":"<",J=W(X.origin);if(J)return`Too big: expected ${X.origin??"value"} to have ${G}${X.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${G}${X.maximum.toString()}`}case"too_small":{let G=X.inclusive?">=":">",J=W(X.origin);if(J)return`Too small: expected ${X.origin} to have ${G}${X.minimum.toString()} ${J.unit}`;return`Too small: expected ${X.origin} to be ${G}${X.minimum.toString()}`}case"invalid_format":{let G=X;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 ${Q[G.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${x4(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};function u$(){return{localeError:FD()}}var gM=Symbol("ZodOutput"),pM=Symbol("ZodInput");class sG{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...W){let Q=W[0];if(this._map.set($,Q),Q&&typeof Q==="object"&&"id"in Q){if(this._idmap.has(Q.id))throw Error(`ID ${Q.id} already exists in the registry`);this._idmap.set(Q.id,$)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let W=this._map.get($);if(W&&typeof W==="object"&&"id"in W)this._idmap.delete(W.id);return this._map.delete($),this}get($){let W=$._zod.parent;if(W){let Q={...this.get(W)??{}};delete Q.id;let X={...Q,...this._map.get($)};return Object.keys(X).length?X:void 0}return this._map.get($)}has($){return this._map.has($)}}function UD(){return new sG}var c6=UD();function aG($,W){return new $({type:"string",...x(W)})}function eG($,W){return new $({type:"string",format:"email",check:"string_format",abort:!1,...x(W)})}function c$($,W){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...x(W)})}function $J($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...x(W)})}function WJ($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...x(W)})}function QJ($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...x(W)})}function XJ($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...x(W)})}function GJ($,W){return new $({type:"string",format:"url",check:"string_format",abort:!1,...x(W)})}function JJ($,W){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...x(W)})}function wJ($,W){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...x(W)})}function YJ($,W){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...x(W)})}function bJ($,W){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...x(W)})}function HJ($,W){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...x(W)})}function zJ($,W){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...x(W)})}function DJ($,W){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...x(W)})}function FJ($,W){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...x(W)})}function UJ($,W){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...x(W)})}function BJ($,W){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...x(W)})}function LJ($,W){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...x(W)})}function AJ($,W){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...x(W)})}function OJ($,W){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...x(W)})}function KJ($,W){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...x(W)})}function ZJ($,W){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...x(W)})}function PJ($,W){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...x(W)})}function VJ($,W){return new $({type:"string",format:"date",check:"string_format",...x(W)})}function jJ($,W){return new $({type:"string",format:"time",check:"string_format",precision:null,...x(W)})}function MJ($,W){return new $({type:"string",format:"duration",check:"string_format",...x(W)})}function qJ($,W){return new $({type:"number",checks:[],...x(W)})}function IJ($,W){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...x(W)})}function NJ($,W){return new $({type:"boolean",...x(W)})}function EJ($,W){return new $({type:"null",...x(W)})}function TJ($){return new $({type:"unknown"})}function RJ($,W){return new $({type:"never",...x(W)})}function d4($,W){return new v$({check:"less_than",...x(W),value:$,inclusive:!1})}function m6($,W){return new v$({check:"less_than",...x(W),value:$,inclusive:!0})}function o4($,W){return new _$({check:"greater_than",...x(W),value:$,inclusive:!1})}function l6($,W){return new _$({check:"greater_than",...x(W),value:$,inclusive:!0})}function t4($,W){return new xX({check:"multiple_of",...x(W),value:$})}function r4($,W){return new yX({check:"max_length",...x(W),maximum:$})}function Q6($,W){return new fX({check:"min_length",...x(W),minimum:$})}function s4($,W){return new uX({check:"length_equals",...x(W),length:$})}function m$($,W){return new cX({check:"string_format",format:"regex",...x(W),pattern:$})}function l$($){return new mX({check:"string_format",format:"lowercase",...x($)})}function g$($){return new lX({check:"string_format",format:"uppercase",...x($)})}function p$($,W){return new gX({check:"string_format",format:"includes",...x(W),includes:$})}function i$($,W){return new pX({check:"string_format",format:"starts_with",...x(W),prefix:$})}function n$($,W){return new iX({check:"string_format",format:"ends_with",...x(W),suffix:$})}function c1($){return new nX({check:"overwrite",tx:$})}function d$($){return c1((W)=>W.normalize($))}function o$(){return c1(($)=>$.trim())}function t$(){return c1(($)=>$.toLowerCase())}function r$(){return c1(($)=>$.toUpperCase())}function SJ($,W,Q){return new $({type:"array",element:W,...x(Q)})}function CJ($,W,Q){let X=x(Q);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:W,...X})}function kJ($,W,Q){return new $({type:"custom",check:"custom",fn:W,...x(Q)})}function vJ($){let W=BD((Q)=>{return Q.addIssue=(X)=>{if(typeof X==="string")Q.issues.push(W6(X,Q.value,W._zod.def));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=Q.value),G.inst??(G.inst=W),G.continue??(G.continue=!W._zod.def.abort),Q.issues.push(W6(G))}},$(Q.value,Q)});return W}function BD($,W){let Q=new L0({check:"custom",...x(W)});return Q._zod.check=$,Q}function X6($){return!!$._zod}function E1($,W){if(X6($))return y6($,W);return $.safeParse(W)}function a4($){if(!$)return;let W;if(X6($))W=$._zod?.def?.shape;else W=$.shape;if(!W)return;if(typeof W==="function")try{return W()}catch{return}return W}function _J($){if(X6($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let Q=$._def;if(Q){if(Q.value!==void 0)return Q.value;if(Array.isArray(Q.values)&&Q.values.length>0)return Q.values[0]}let X=$.value;if(X!==void 0)return X;return}var p6={};SQ(p6,{time:()=>e$,duration:()=>$8,datetime:()=>s$,date:()=>a$,ZodISOTime:()=>yJ,ZodISODuration:()=>fJ,ZodISODateTime:()=>xJ,ZodISODate:()=>hJ});var xJ=V("ZodISODateTime",($,W)=>{BG.init($,W),G0.init($,W)});function s$($){return PJ(xJ,$)}var hJ=V("ZodISODate",($,W)=>{LG.init($,W),G0.init($,W)});function a$($){return VJ(hJ,$)}var yJ=V("ZodISOTime",($,W)=>{AG.init($,W),G0.init($,W)});function e$($){return jJ(yJ,$)}var fJ=V("ZodISODuration",($,W)=>{OG.init($,W),G0.init($,W)});function $8($){return MJ(fJ,$)}var uJ=($,W)=>{u4.init($,W),$.name="ZodError",Object.defineProperties($,{format:{value:(Q)=>rQ($,Q)},flatten:{value:(Q)=>tQ($,Q)},addIssue:{value:(Q)=>{$.issues.push(Q),$.message=JSON.stringify($.issues,e1,2)}},addIssues:{value:(Q)=>{$.issues.push(...Q),$.message=JSON.stringify($.issues,e1,2)}},isEmpty:{get(){return $.issues.length===0}}})},Rq=V("ZodError",uJ),v0=V("ZodError",uJ,{Parent:Error});var cJ=c4(v0),mJ=m4(v0),lJ=h6(v0),gJ=f6(v0),pJ=sQ(v0),iJ=aQ(v0),nJ=eQ(v0),dJ=$X(v0),oJ=WX(v0),tJ=QX(v0),rJ=XX(v0),sJ=GX(v0);var b0=V("ZodType",($,W)=>{return $0.init($,W),$.def=W,$.type=W.type,Object.defineProperty($,"_def",{value:W}),$.check=(...Q)=>{return $.clone(o.mergeDefs(W,{checks:[...W.checks??[],...Q.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]}))},$.clone=(Q,X)=>i0($,Q,X),$.brand=()=>$,$.register=(Q,X)=>{return Q.add($,X),$},$.parse=(Q,X)=>cJ($,Q,X,{callee:$.parse}),$.safeParse=(Q,X)=>lJ($,Q,X),$.parseAsync=async(Q,X)=>mJ($,Q,X,{callee:$.parseAsync}),$.safeParseAsync=async(Q,X)=>gJ($,Q,X),$.spa=$.safeParseAsync,$.encode=(Q,X)=>pJ($,Q,X),$.decode=(Q,X)=>iJ($,Q,X),$.encodeAsync=async(Q,X)=>nJ($,Q,X),$.decodeAsync=async(Q,X)=>dJ($,Q,X),$.safeEncode=(Q,X)=>oJ($,Q,X),$.safeDecode=(Q,X)=>tJ($,Q,X),$.safeEncodeAsync=async(Q,X)=>rJ($,Q,X),$.safeDecodeAsync=async(Q,X)=>sJ($,Q,X),$.refine=(Q,X)=>$.check(zF(Q,X)),$.superRefine=(Q)=>$.check(DF(Q)),$.overwrite=(Q)=>$.check(c1(Q)),$.optional=()=>Y0($),$.nullable=()=>$w($),$.nullish=()=>Y0($w($)),$.nonoptional=(Q)=>GF($,Q),$.array=()=>p($),$.or=(Q)=>e([$,Q]),$.and=(Q)=>$9($,Q),$.transform=(Q)=>Q8($,Jw(Q)),$.default=(Q)=>WF($,Q),$.prefault=(Q)=>XF($,Q),$.catch=(Q)=>wF($,Q),$.pipe=(Q)=>Q8($,Q),$.readonly=()=>HF($),$.describe=(Q)=>{let X=$.clone();return c6.add(X,{description:Q}),X},Object.defineProperty($,"description",{get(){return c6.get($)?.description},configurable:!0}),$.meta=(...Q)=>{if(Q.length===0)return c6.get($);let X=$.clone();return c6.add(X,Q[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),Ww=V("_ZodString",($,W)=>{n4.init($,W),b0.init($,W);let Q=$._zod.bag;$.format=Q.format??null,$.minLength=Q.minimum??null,$.maxLength=Q.maximum??null,$.regex=(...X)=>$.check(m$(...X)),$.includes=(...X)=>$.check(p$(...X)),$.startsWith=(...X)=>$.check(i$(...X)),$.endsWith=(...X)=>$.check(n$(...X)),$.min=(...X)=>$.check(Q6(...X)),$.max=(...X)=>$.check(r4(...X)),$.length=(...X)=>$.check(s4(...X)),$.nonempty=(...X)=>$.check(Q6(1,...X)),$.lowercase=(X)=>$.check(l$(X)),$.uppercase=(X)=>$.check(g$(X)),$.trim=()=>$.check(o$()),$.normalize=(...X)=>$.check(d$(...X)),$.toLowerCase=()=>$.check(t$()),$.toUpperCase=()=>$.check(r$())}),MD=V("ZodString",($,W)=>{n4.init($,W),Ww.init($,W),$.email=(Q)=>$.check(eG(qD,Q)),$.url=(Q)=>$.check(GJ(ID,Q)),$.jwt=(Q)=>$.check(ZJ(cD,Q)),$.emoji=(Q)=>$.check(JJ(ND,Q)),$.guid=(Q)=>$.check(c$(aJ,Q)),$.uuid=(Q)=>$.check($J(e4,Q)),$.uuidv4=(Q)=>$.check(WJ(e4,Q)),$.uuidv6=(Q)=>$.check(QJ(e4,Q)),$.uuidv7=(Q)=>$.check(XJ(e4,Q)),$.nanoid=(Q)=>$.check(wJ(ED,Q)),$.guid=(Q)=>$.check(c$(aJ,Q)),$.cuid=(Q)=>$.check(YJ(TD,Q)),$.cuid2=(Q)=>$.check(bJ(RD,Q)),$.ulid=(Q)=>$.check(HJ(SD,Q)),$.base64=(Q)=>$.check(AJ(yD,Q)),$.base64url=(Q)=>$.check(OJ(fD,Q)),$.xid=(Q)=>$.check(zJ(CD,Q)),$.ksuid=(Q)=>$.check(DJ(kD,Q)),$.ipv4=(Q)=>$.check(FJ(vD,Q)),$.ipv6=(Q)=>$.check(UJ(_D,Q)),$.cidrv4=(Q)=>$.check(BJ(xD,Q)),$.cidrv6=(Q)=>$.check(LJ(hD,Q)),$.e164=(Q)=>$.check(KJ(uD,Q)),$.datetime=(Q)=>$.check(s$(Q)),$.date=(Q)=>$.check(a$(Q)),$.time=(Q)=>$.check(e$(Q)),$.duration=(Q)=>$.check($8(Q))});function Z($){return aG(MD,$)}var G0=V("ZodStringFormat",($,W)=>{W0.init($,W),Ww.init($,W)}),qD=V("ZodEmail",($,W)=>{JG.init($,W),G0.init($,W)});var aJ=V("ZodGUID",($,W)=>{XG.init($,W),G0.init($,W)});var e4=V("ZodUUID",($,W)=>{GG.init($,W),G0.init($,W)});var ID=V("ZodURL",($,W)=>{wG.init($,W),G0.init($,W)});var ND=V("ZodEmoji",($,W)=>{YG.init($,W),G0.init($,W)});var ED=V("ZodNanoID",($,W)=>{bG.init($,W),G0.init($,W)});var TD=V("ZodCUID",($,W)=>{HG.init($,W),G0.init($,W)});var RD=V("ZodCUID2",($,W)=>{zG.init($,W),G0.init($,W)});var SD=V("ZodULID",($,W)=>{DG.init($,W),G0.init($,W)});var CD=V("ZodXID",($,W)=>{FG.init($,W),G0.init($,W)});var kD=V("ZodKSUID",($,W)=>{UG.init($,W),G0.init($,W)});var vD=V("ZodIPv4",($,W)=>{KG.init($,W),G0.init($,W)});var _D=V("ZodIPv6",($,W)=>{ZG.init($,W),G0.init($,W)});var xD=V("ZodCIDRv4",($,W)=>{PG.init($,W),G0.init($,W)});var hD=V("ZodCIDRv6",($,W)=>{VG.init($,W),G0.init($,W)});var yD=V("ZodBase64",($,W)=>{MG.init($,W),G0.init($,W)});var fD=V("ZodBase64URL",($,W)=>{qG.init($,W),G0.init($,W)});var uD=V("ZodE164",($,W)=>{IG.init($,W),G0.init($,W)});var cD=V("ZodJWT",($,W)=>{NG.init($,W),G0.init($,W)});var Qw=V("ZodNumber",($,W)=>{y$.init($,W),b0.init($,W),$.gt=(X,G)=>$.check(o4(X,G)),$.gte=(X,G)=>$.check(l6(X,G)),$.min=(X,G)=>$.check(l6(X,G)),$.lt=(X,G)=>$.check(d4(X,G)),$.lte=(X,G)=>$.check(m6(X,G)),$.max=(X,G)=>$.check(m6(X,G)),$.int=(X)=>$.check(eJ(X)),$.safe=(X)=>$.check(eJ(X)),$.positive=(X)=>$.check(o4(0,X)),$.nonnegative=(X)=>$.check(l6(0,X)),$.negative=(X)=>$.check(d4(0,X)),$.nonpositive=(X)=>$.check(m6(0,X)),$.multipleOf=(X,G)=>$.check(t4(X,G)),$.step=(X,G)=>$.check(t4(X,G)),$.finite=()=>$;let Q=$._zod.bag;$.minValue=Math.max(Q.minimum??Number.NEGATIVE_INFINITY,Q.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(Q.maximum??Number.POSITIVE_INFINITY,Q.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(Q.format??"").includes("int")||Number.isSafeInteger(Q.multipleOf??0.5),$.isFinite=!0,$.format=Q.format??null});function r($){return qJ(Qw,$)}var mD=V("ZodNumberFormat",($,W)=>{EG.init($,W),Qw.init($,W)});function eJ($){return IJ(mD,$)}var lD=V("ZodBoolean",($,W)=>{TG.init($,W),b0.init($,W)});function B0($){return NJ(lD,$)}var gD=V("ZodNull",($,W)=>{RG.init($,W),b0.init($,W)});function X8($){return EJ(gD,$)}var pD=V("ZodUnknown",($,W)=>{SG.init($,W),b0.init($,W)});function J0(){return TJ(pD)}var iD=V("ZodNever",($,W)=>{CG.init($,W),b0.init($,W)});function nD($){return RJ(iD,$)}var dD=V("ZodArray",($,W)=>{kG.init($,W),b0.init($,W),$.element=W.element,$.min=(Q,X)=>$.check(Q6(Q,X)),$.nonempty=(Q)=>$.check(Q6(1,Q)),$.max=(Q,X)=>$.check(r4(Q,X)),$.length=(Q,X)=>$.check(s4(Q,X)),$.unwrap=()=>$.element});function p($,W){return SJ(dD,$,W)}var Xw=V("ZodObject",($,W)=>{xG.init($,W),b0.init($,W),o.defineLazy($,"shape",()=>{return W.shape}),$.keyof=()=>I0(Object.keys($._zod.def.shape)),$.catchall=(Q)=>$.clone({...$._zod.def,catchall:Q}),$.passthrough=()=>$.clone({...$._zod.def,catchall:J0()}),$.loose=()=>$.clone({...$._zod.def,catchall:J0()}),$.strict=()=>$.clone({...$._zod.def,catchall:nD()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(Q)=>{return o.extend($,Q)},$.safeExtend=(Q)=>{return o.safeExtend($,Q)},$.merge=(Q)=>o.merge($,Q),$.pick=(Q)=>o.pick($,Q),$.omit=(Q)=>o.omit($,Q),$.partial=(...Q)=>o.partial(ww,$,Q[0]),$.required=(...Q)=>o.required(Yw,$,Q[0])});function E($,W){let Q={type:"object",shape:$??{},...o.normalizeParams(W)};return new Xw(Q)}function j0($,W){return new Xw({type:"object",shape:$,catchall:J0(),...o.normalizeParams(W)})}var Gw=V("ZodUnion",($,W)=>{f$.init($,W),b0.init($,W),$.options=W.options});function e($,W){return new Gw({type:"union",options:$,...o.normalizeParams(W)})}var oD=V("ZodDiscriminatedUnion",($,W)=>{Gw.init($,W),hG.init($,W)});function G8($,W,Q){return new oD({type:"union",options:W,discriminator:$,...o.normalizeParams(Q)})}var tD=V("ZodIntersection",($,W)=>{yG.init($,W),b0.init($,W)});function $9($,W){return new tD({type:"intersection",left:$,right:W})}var rD=V("ZodRecord",($,W)=>{fG.init($,W),b0.init($,W),$.keyType=W.keyType,$.valueType=W.valueType});function w0($,W,Q){return new rD({type:"record",keyType:$,valueType:W,...o.normalizeParams(Q)})}var W8=V("ZodEnum",($,W)=>{uG.init($,W),b0.init($,W),$.enum=W.entries,$.options=Object.values(W.entries);let Q=new Set(Object.keys(W.entries));$.extract=(X,G)=>{let J={};for(let w of X)if(Q.has(w))J[w]=W.entries[w];else throw Error(`Key ${w} not found in enum`);return new W8({...W,checks:[],...o.normalizeParams(G),entries:J})},$.exclude=(X,G)=>{let J={...W.entries};for(let w of X)if(Q.has(w))delete J[w];else throw Error(`Key ${w} not found in enum`);return new W8({...W,checks:[],...o.normalizeParams(G),entries:J})}});function I0($,W){let Q=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new W8({type:"enum",entries:Q,...o.normalizeParams(W)})}var sD=V("ZodLiteral",($,W)=>{cG.init($,W),b0.init($,W),$.values=new Set(W.values),Object.defineProperty($,"value",{get(){if(W.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return W.values[0]}})});function T($,W){return new sD({type:"literal",values:Array.isArray($)?$:[$],...o.normalizeParams(W)})}var aD=V("ZodTransform",($,W)=>{mG.init($,W),b0.init($,W),$._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new C6($.constructor.name);Q.addIssue=(J)=>{if(typeof J==="string")Q.issues.push(o.issue(J,Q.value,W));else{let w=J;if(w.fatal)w.continue=!1;w.code??(w.code="custom"),w.input??(w.input=Q.value),w.inst??(w.inst=$),Q.issues.push(o.issue(w))}};let G=W.transform(Q.value,Q);if(G instanceof Promise)return G.then((J)=>{return Q.value=J,Q});return Q.value=G,Q}});function Jw($){return new aD({type:"transform",transform:$})}var ww=V("ZodOptional",($,W)=>{lG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function Y0($){return new ww({type:"optional",innerType:$})}var eD=V("ZodNullable",($,W)=>{gG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function $w($){return new eD({type:"nullable",innerType:$})}var $F=V("ZodDefault",($,W)=>{pG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function WF($,W){return new $F({type:"default",innerType:$,get defaultValue(){return typeof W==="function"?W():o.shallowClone(W)}})}var QF=V("ZodPrefault",($,W)=>{iG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function XF($,W){return new QF({type:"prefault",innerType:$,get defaultValue(){return typeof W==="function"?W():o.shallowClone(W)}})}var Yw=V("ZodNonOptional",($,W)=>{nG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function GF($,W){return new Yw({type:"nonoptional",innerType:$,...o.normalizeParams(W)})}var JF=V("ZodCatch",($,W)=>{dG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function wF($,W){return new JF({type:"catch",innerType:$,catchValue:typeof W==="function"?W:()=>W})}var YF=V("ZodPipe",($,W)=>{oG.init($,W),b0.init($,W),$.in=W.in,$.out=W.out});function Q8($,W){return new YF({type:"pipe",in:$,out:W})}var bF=V("ZodReadonly",($,W)=>{tG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function HF($){return new bF({type:"readonly",innerType:$})}var bw=V("ZodCustom",($,W)=>{rG.init($,W),b0.init($,W)});function Hw($,W){return CJ(bw,$??(()=>!0),W)}function zF($,W={}){return kJ(bw,$,W)}function DF($){return vJ($)}function J8($,W){return Q8(Jw($),W)}f0(u$());var w8="2025-11-25";var zw=[w8,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],T1="io.modelcontextprotocol/related-task",Q9="2.0",A0=Hw(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Dw=e([Z(),r().int()]),Fw=Z(),qI=j0({ttl:e([r(),X8()]).optional(),pollInterval:r().optional()}),FF=E({ttl:r().optional()}),UF=E({taskId:Z()}),Y8=j0({progressToken:Dw.optional(),[T1]:UF.optional()}),_0=E({_meta:Y8.optional()}),i6=_0.extend({task:FF.optional()}),Uw=($)=>i6.safeParse($).success,O0=E({method:Z(),params:_0.loose().optional()}),u0=E({_meta:Y8.optional()}),c0=E({method:Z(),params:u0.loose().optional()}),K0=j0({_meta:Y8.optional()}),X9=e([Z(),r().int()]),Bw=E({jsonrpc:T(Q9),id:X9,...O0.shape}).strict(),b8=($)=>Bw.safeParse($).success,Lw=E({jsonrpc:T(Q9),...c0.shape}).strict(),Aw=($)=>Lw.safeParse($).success,H8=E({jsonrpc:T(Q9),id:X9,result:K0}).strict(),n6=($)=>H8.safeParse($).success;var i;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(i||(i={}));var z8=E({jsonrpc:T(Q9),id:X9.optional(),error:E({code:r().int(),message:Z(),data:J0().optional()})}).strict();var Ow=($)=>z8.safeParse($).success;var Kw=e([Bw,Lw,H8,z8]),II=e([H8,z8]),G9=K0.strict(),BF=u0.extend({requestId:X9.optional(),reason:Z().optional()}),J9=c0.extend({method:T("notifications/cancelled"),params:BF}),LF=E({src:Z(),mimeType:Z().optional(),sizes:p(Z()).optional(),theme:I0(["light","dark"]).optional()}),d6=E({icons:p(LF).optional()}),G6=E({name:Z(),title:Z().optional()}),Zw=G6.extend({...G6.shape,...d6.shape,version:Z(),websiteUrl:Z().optional(),description:Z().optional()}),AF=$9(E({applyDefaults:B0().optional()}),w0(Z(),J0())),OF=J8(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},$9(E({form:AF.optional(),url:A0.optional()}),w0(Z(),J0()).optional())),KF=j0({list:A0.optional(),cancel:A0.optional(),requests:j0({sampling:j0({createMessage:A0.optional()}).optional(),elicitation:j0({create:A0.optional()}).optional()}).optional()}),ZF=j0({list:A0.optional(),cancel:A0.optional(),requests:j0({tools:j0({call:A0.optional()}).optional()}).optional()}),PF=E({experimental:w0(Z(),A0).optional(),sampling:E({context:A0.optional(),tools:A0.optional()}).optional(),elicitation:OF.optional(),roots:E({listChanged:B0().optional()}).optional(),tasks:KF.optional()}),VF=_0.extend({protocolVersion:Z(),capabilities:PF,clientInfo:Zw}),D8=O0.extend({method:T("initialize"),params:VF});var jF=E({experimental:w0(Z(),A0).optional(),logging:A0.optional(),completions:A0.optional(),prompts:E({listChanged:B0().optional()}).optional(),resources:E({subscribe:B0().optional(),listChanged:B0().optional()}).optional(),tools:E({listChanged:B0().optional()}).optional(),tasks:ZF.optional()}),MF=K0.extend({protocolVersion:Z(),capabilities:jF,serverInfo:Zw,instructions:Z().optional()}),F8=c0.extend({method:T("notifications/initialized"),params:u0.optional()});var w9=O0.extend({method:T("ping"),params:_0.optional()}),qF=E({progress:r(),total:Y0(r()),message:Y0(Z())}),IF=E({...u0.shape,...qF.shape,progressToken:Dw}),Y9=c0.extend({method:T("notifications/progress"),params:IF}),NF=_0.extend({cursor:Fw.optional()}),o6=O0.extend({params:NF.optional()}),t6=K0.extend({nextCursor:Fw.optional()}),EF=I0(["working","input_required","completed","failed","cancelled"]),r6=E({taskId:Z(),status:EF,ttl:e([r(),X8()]),createdAt:Z(),lastUpdatedAt:Z(),pollInterval:Y0(r()),statusMessage:Y0(Z())}),J6=K0.extend({task:r6}),TF=u0.merge(r6),s6=c0.extend({method:T("notifications/tasks/status"),params:TF}),b9=O0.extend({method:T("tasks/get"),params:_0.extend({taskId:Z()})}),H9=K0.merge(r6),z9=O0.extend({method:T("tasks/result"),params:_0.extend({taskId:Z()})}),NI=K0.loose(),D9=o6.extend({method:T("tasks/list")}),F9=t6.extend({tasks:p(r6)}),U9=O0.extend({method:T("tasks/cancel"),params:_0.extend({taskId:Z()})}),Pw=K0.merge(r6),Vw=E({uri:Z(),mimeType:Y0(Z()),_meta:w0(Z(),J0()).optional()}),jw=Vw.extend({text:Z()}),U8=Z().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mw=Vw.extend({blob:U8}),a6=I0(["user","assistant"]),w6=E({audience:p(a6).optional(),priority:r().min(0).max(1).optional(),lastModified:p6.datetime({offset:!0}).optional()}),qw=E({...G6.shape,...d6.shape,uri:Z(),description:Y0(Z()),mimeType:Y0(Z()),annotations:w6.optional(),_meta:Y0(j0({}))}),RF=E({...G6.shape,...d6.shape,uriTemplate:Z(),description:Y0(Z()),mimeType:Y0(Z()),annotations:w6.optional(),_meta:Y0(j0({}))}),B8=o6.extend({method:T("resources/list")}),SF=t6.extend({resources:p(qw)}),CF=o6.extend({method:T("resources/templates/list")}),kF=t6.extend({resourceTemplates:p(RF)}),L8=_0.extend({uri:Z()}),vF=L8,A8=O0.extend({method:T("resources/read"),params:vF}),_F=K0.extend({contents:p(e([jw,Mw]))}),xF=c0.extend({method:T("notifications/resources/list_changed"),params:u0.optional()}),hF=L8,yF=O0.extend({method:T("resources/subscribe"),params:hF}),fF=L8,uF=O0.extend({method:T("resources/unsubscribe"),params:fF}),cF=u0.extend({uri:Z()}),mF=c0.extend({method:T("notifications/resources/updated"),params:cF}),lF=E({name:Z(),description:Y0(Z()),required:Y0(B0())}),gF=E({...G6.shape,...d6.shape,description:Y0(Z()),arguments:Y0(p(lF)),_meta:Y0(j0({}))}),pF=o6.extend({method:T("prompts/list")}),iF=t6.extend({prompts:p(gF)}),nF=_0.extend({name:Z(),arguments:w0(Z(),Z()).optional()}),dF=O0.extend({method:T("prompts/get"),params:nF}),O8=E({type:T("text"),text:Z(),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),K8=E({type:T("image"),data:U8,mimeType:Z(),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),Z8=E({type:T("audio"),data:U8,mimeType:Z(),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),oF=E({type:T("tool_use"),name:Z(),id:Z(),input:w0(Z(),J0()),_meta:w0(Z(),J0()).optional()}),tF=E({type:T("resource"),resource:e([jw,Mw]),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),rF=qw.extend({type:T("resource_link")}),P8=e([O8,K8,Z8,rF,tF]),sF=E({role:a6,content:P8}),aF=K0.extend({description:Z().optional(),messages:p(sF)}),eF=c0.extend({method:T("notifications/prompts/list_changed"),params:u0.optional()}),$U=E({title:Z().optional(),readOnlyHint:B0().optional(),destructiveHint:B0().optional(),idempotentHint:B0().optional(),openWorldHint:B0().optional()}),WU=E({taskSupport:I0(["required","optional","forbidden"]).optional()}),Iw=E({...G6.shape,...d6.shape,description:Z().optional(),inputSchema:E({type:T("object"),properties:w0(Z(),A0).optional(),required:p(Z()).optional()}).catchall(J0()),outputSchema:E({type:T("object"),properties:w0(Z(),A0).optional(),required:p(Z()).optional()}).catchall(J0()).optional(),annotations:$U.optional(),execution:WU.optional(),_meta:w0(Z(),J0()).optional()}),V8=o6.extend({method:T("tools/list")}),QU=t6.extend({tools:p(Iw)}),B9=K0.extend({content:p(P8).default([]),structuredContent:w0(Z(),J0()).optional(),isError:B0().optional()}),EI=B9.or(K0.extend({toolResult:J0()})),XU=i6.extend({name:Z(),arguments:w0(Z(),J0()).optional()}),e6=O0.extend({method:T("tools/call"),params:XU}),GU=c0.extend({method:T("notifications/tools/list_changed"),params:u0.optional()}),TI=E({autoRefresh:B0().default(!0),debounceMs:r().int().nonnegative().default(300)}),$4=I0(["debug","info","notice","warning","error","critical","alert","emergency"]),JU=_0.extend({level:$4}),j8=O0.extend({method:T("logging/setLevel"),params:JU}),wU=u0.extend({level:$4,logger:Z().optional(),data:J0()}),YU=c0.extend({method:T("notifications/message"),params:wU}),bU=E({name:Z().optional()}),HU=E({hints:p(bU).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),zU=E({mode:I0(["auto","required","none"]).optional()}),DU=E({type:T("tool_result"),toolUseId:Z().describe("The unique identifier for the corresponding tool call."),content:p(P8).default([]),structuredContent:E({}).loose().optional(),isError:B0().optional(),_meta:w0(Z(),J0()).optional()}),FU=G8("type",[O8,K8,Z8]),W9=G8("type",[O8,K8,Z8,oF,DU]),UU=E({role:a6,content:e([W9,p(W9)]),_meta:w0(Z(),J0()).optional()}),BU=i6.extend({messages:p(UU),modelPreferences:HU.optional(),systemPrompt:Z().optional(),includeContext:I0(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:p(Z()).optional(),metadata:A0.optional(),tools:p(Iw).optional(),toolChoice:zU.optional()}),LU=O0.extend({method:T("sampling/createMessage"),params:BU}),M8=K0.extend({model:Z(),stopReason:Y0(I0(["endTurn","stopSequence","maxTokens"]).or(Z())),role:a6,content:FU}),q8=K0.extend({model:Z(),stopReason:Y0(I0(["endTurn","stopSequence","maxTokens","toolUse"]).or(Z())),role:a6,content:e([W9,p(W9)])}),AU=E({type:T("boolean"),title:Z().optional(),description:Z().optional(),default:B0().optional()}),OU=E({type:T("string"),title:Z().optional(),description:Z().optional(),minLength:r().optional(),maxLength:r().optional(),format:I0(["email","uri","date","date-time"]).optional(),default:Z().optional()}),KU=E({type:I0(["number","integer"]),title:Z().optional(),description:Z().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),ZU=E({type:T("string"),title:Z().optional(),description:Z().optional(),enum:p(Z()),default:Z().optional()}),PU=E({type:T("string"),title:Z().optional(),description:Z().optional(),oneOf:p(E({const:Z(),title:Z()})),default:Z().optional()}),VU=E({type:T("string"),title:Z().optional(),description:Z().optional(),enum:p(Z()),enumNames:p(Z()).optional(),default:Z().optional()}),jU=e([ZU,PU]),MU=E({type:T("array"),title:Z().optional(),description:Z().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({type:T("string"),enum:p(Z())}),default:p(Z()).optional()}),qU=E({type:T("array"),title:Z().optional(),description:Z().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({anyOf:p(E({const:Z(),title:Z()}))}),default:p(Z()).optional()}),IU=e([MU,qU]),NU=e([VU,jU,IU]),EU=e([NU,AU,OU,KU]),TU=i6.extend({mode:T("form").optional(),message:Z(),requestedSchema:E({type:T("object"),properties:w0(Z(),EU),required:p(Z()).optional()})}),RU=i6.extend({mode:T("url"),message:Z(),elicitationId:Z(),url:Z().url()}),SU=e([TU,RU]),CU=O0.extend({method:T("elicitation/create"),params:SU}),kU=u0.extend({elicitationId:Z()}),vU=c0.extend({method:T("notifications/elicitation/complete"),params:kU}),L9=K0.extend({action:I0(["accept","decline","cancel"]),content:J8(($)=>$===null?void 0:$,w0(Z(),e([Z(),r(),B0(),p(Z())])).optional())}),_U=E({type:T("ref/resource"),uri:Z()});var xU=E({type:T("ref/prompt"),name:Z()}),hU=_0.extend({ref:e([xU,_U]),argument:E({name:Z(),value:Z()}),context:E({arguments:w0(Z(),Z()).optional()}).optional()}),yU=O0.extend({method:T("completion/complete"),params:hU});var fU=K0.extend({completion:j0({values:p(Z()).max(100),total:Y0(r().int()),hasMore:Y0(B0())})}),uU=E({uri:Z().startsWith("file://"),name:Z().optional(),_meta:w0(Z(),J0()).optional()}),cU=O0.extend({method:T("roots/list"),params:_0.optional()}),I8=K0.extend({roots:p(uU)}),mU=c0.extend({method:T("notifications/roots/list_changed"),params:u0.optional()}),RI=e([w9,D8,yU,j8,dF,pF,B8,CF,A8,yF,uF,e6,V8,b9,z9,D9,U9]),SI=e([J9,Y9,F8,mU,s6]),CI=e([G9,M8,q8,L9,I8,H9,F9,J6]),kI=e([w9,LU,CU,cU,b9,z9,D9,U9]),vI=e([J9,Y9,YU,mF,xF,GU,eF,s6,vU]),_I=e([G9,MF,fU,aF,iF,SF,kF,_F,B9,QU,H9,F9,J6]);class l extends Error{constructor($,W,Q){super(`MCP error ${$}: ${W}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,W,Q){if($===i.UrlElicitationRequired&&Q){let X=Q;if(X.elicitations)return new Nw(X.elicitations,W)}return new l($,W,Q)}}class Nw extends l{constructor($,W=`URL elicitation${$.length>1?"s":""} required`){super(i.UrlElicitationRequired,W,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}function R1($){return $==="completed"||$==="failed"||$==="cancelled"}var lU=Symbol("Let zodToJsonSchema decide on which parser to use");var UN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function N8($){let Q=a4($)?.method;if(!Q)throw Error("Schema is missing a method literal");let X=_J(Q);if(typeof X!=="string")throw Error("Schema method literal must be a string");return X}function E8($,W){let Q=E1($,W);if(!Q.success)throw Q.error;return Q.data}var oU=60000;class T8{constructor($){if(this._options=$,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(J9,(W)=>{this._oncancel(W)}),this.setNotificationHandler(Y9,(W)=>{this._onprogress(W)}),this.setRequestHandler(w9,(W)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(b9,async(W,Q)=>{let X=await this._taskStore.getTask(W.params.taskId,Q.sessionId);if(!X)throw new l(i.InvalidParams,"Failed to retrieve task: Task not found");return{...X}}),this.setRequestHandler(z9,async(W,Q)=>{let X=async()=>{let G=W.params.taskId;if(this._taskMessageQueue){let w;while(w=await this._taskMessageQueue.dequeue(G,Q.sessionId)){if(w.type==="response"||w.type==="error"){let Y=w.message,b=Y.id,H=this._requestResolvers.get(b);if(H)if(this._requestResolvers.delete(b),w.type==="response")H(Y);else{let z=Y,F=new l(z.error.code,z.error.message,z.error.data);H(F)}else{let z=w.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${b}`))}continue}await this._transport?.send(w.message,{relatedRequestId:Q.requestId})}}let J=await this._taskStore.getTask(G,Q.sessionId);if(!J)throw new l(i.InvalidParams,`Task not found: ${G}`);if(!R1(J.status))return await this._waitForTaskUpdate(G,Q.signal),await X();if(R1(J.status)){let w=await this._taskStore.getTaskResult(G,Q.sessionId);return this._clearTaskQueue(G),{...w,_meta:{...w._meta,[T1]:{taskId:G}}}}return await X()};return await X()}),this.setRequestHandler(D9,async(W,Q)=>{try{let{tasks:X,nextCursor:G}=await this._taskStore.listTasks(W.params?.cursor,Q.sessionId);return{tasks:X,nextCursor:G,_meta:{}}}catch(X){throw new l(i.InvalidParams,`Failed to list tasks: ${X instanceof Error?X.message:String(X)}`)}}),this.setRequestHandler(U9,async(W,Q)=>{try{let X=await this._taskStore.getTask(W.params.taskId,Q.sessionId);if(!X)throw new l(i.InvalidParams,`Task not found: ${W.params.taskId}`);if(R1(X.status))throw new l(i.InvalidParams,`Cannot cancel task in terminal status: ${X.status}`);await this._taskStore.updateTaskStatus(W.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(W.params.taskId);let G=await this._taskStore.getTask(W.params.taskId,Q.sessionId);if(!G)throw new l(i.InvalidParams,`Task not found after cancellation: ${W.params.taskId}`);return{_meta:{},...G}}catch(X){if(X instanceof l)throw X;throw new l(i.InvalidRequest,`Failed to cancel task: ${X instanceof Error?X.message:String(X)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,W,Q,X,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(X,W),startTime:Date.now(),timeout:W,maxTotalTimeout:Q,resetTimeoutOnProgress:G,onTimeout:X})}_resetTimeout($){let W=this._timeoutInfo.get($);if(!W)return!1;let Q=Date.now()-W.startTime;if(W.maxTotalTimeout&&Q>=W.maxTotalTimeout)throw this._timeoutInfo.delete($),l.fromError(i.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:W.maxTotalTimeout,totalElapsed:Q});return clearTimeout(W.timeoutId),W.timeoutId=setTimeout(W.onTimeout,W.timeout),!0}_cleanupTimeout($){let W=this._timeoutInfo.get($);if(W)clearTimeout(W.timeoutId),this._timeoutInfo.delete($)}async connect($){this._transport=$;let W=this.transport?.onclose;this._transport.onclose=()=>{W?.(),this._onclose()};let Q=this.transport?.onerror;this._transport.onerror=(G)=>{Q?.(G),this._onerror(G)};let X=this._transport?.onmessage;this._transport.onmessage=(G,J)=>{if(X?.(G,J),n6(G)||Ow(G))this._onresponse(G);else if(b8(G))this._onrequest(G,J);else if(Aw(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let W=l.fromError(i.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Q of $.values())Q(W)}_onerror($){this.onerror?.($)}_onnotification($){let W=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(W===void 0)return;Promise.resolve().then(()=>W($)).catch((Q)=>this._onerror(Error(`Uncaught error in notification handler: ${Q}`)))}_onrequest($,W){let Q=this._requestHandlers.get($.method)??this.fallbackRequestHandler,X=this._transport,G=$.params?._meta?.[T1]?.taskId;if(Q===void 0){let H={jsonrpc:"2.0",id:$.id,error:{code:i.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:H,timestamp:Date.now()},X?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else X?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J);let w=Uw($.params)?$.params.task:void 0,Y=this._taskStore?this.requestTaskStore($,X?.sessionId):void 0,b={signal:J.signal,sessionId:X?.sessionId,_meta:$.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:$.id};if(G)z.relatedTask={taskId:G};await this.notification(H,z)},sendRequest:async(H,z,F)=>{let U={...F,relatedRequestId:$.id};if(G&&!U.relatedTask)U.relatedTask={taskId:G};let B=U.relatedTask?.taskId??G;if(B&&Y)await Y.updateTaskStatus(B,"input_required");return await this.request(H,z,U)},authInfo:W?.authInfo,requestId:$.id,requestInfo:W?.requestInfo,taskId:G,taskStore:Y,taskRequestedTtl:w?.ttl,closeSSEStream:W?.closeSSEStream,closeStandaloneSSEStream:W?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(w)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,b)).then(async(H)=>{if(J.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:$.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:z,timestamp:Date.now()},X?.sessionId);else await X?.send(z)},async(H)=>{if(J.signal.aborted)return;let z={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(H.code)?H.code:i.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:z,timestamp:Date.now()},X?.sessionId);else await X?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:W,...Q}=$.params,X=Number(W),G=this._progressHandlers.get(X);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let J=this._responseHandlers.get(X),w=this._timeoutInfo.get(X);if(w&&J&&w.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(Y){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),J(Y);return}G(Q)}_onresponse($){let W=Number($.id),Q=this._requestResolvers.get(W);if(Q){if(this._requestResolvers.delete(W),n6($))Q($);else{let J=new l($.error.code,$.error.message,$.error.data);Q(J)}return}let X=this._responseHandlers.get(W);if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(W),this._cleanupTimeout(W);let G=!1;if(n6($)&&$.result&&typeof $.result==="object"){let J=$.result;if(J.task&&typeof J.task==="object"){let w=J.task;if(typeof w.taskId==="string")G=!0,this._taskProgressTokens.set(w.taskId,W)}}if(!G)this._progressHandlers.delete(W);if(n6($))X($);else{let J=l.fromError($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,W,Q){let{task:X}=Q??{};if(!X){try{yield{type:"result",result:await this.request($,W,Q)}}catch(J){yield{type:"error",error:J instanceof l?J:new l(i.InternalError,String(J))}}return}let G;try{let J=await this.request($,J6,Q);if(J.task)G=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new l(i.InternalError,"Task creation did not return a task");while(!0){let w=await this.getTask({taskId:G},Q);if(yield{type:"taskStatus",task:w},R1(w.status)){if(w.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},W,Q)};else if(w.status==="failed")yield{type:"error",error:new l(i.InternalError,`Task ${G} failed`)};else if(w.status==="cancelled")yield{type:"error",error:new l(i.InternalError,`Task ${G} was cancelled`)};return}if(w.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},W,Q)};return}let Y=w.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((b)=>setTimeout(b,Y)),Q?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof l?J:new l(i.InternalError,String(J))}}}request($,W,Q){let{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J,task:w,relatedTask:Y}=Q??{};return new Promise((b,H)=>{let z=(M)=>{H(M)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),w)this.assertTaskCapability($.method)}catch(M){z(M);return}Q?.signal?.throwIfAborted();let F=this._requestMessageId++,U={...$,jsonrpc:"2.0",id:F};if(Q?.onprogress)this._progressHandlers.set(F,Q.onprogress),U.params={...$.params,_meta:{...$.params?._meta||{},progressToken:F}};if(w)U.params={...U.params,task:w};if(Y)U.params={...U.params,_meta:{...U.params?._meta||{},[T1]:Y}};let B=(M)=>{this._responseHandlers.delete(F),this._progressHandlers.delete(F),this._cleanupTimeout(F),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:F,reason:String(M)}},{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((C)=>this._onerror(Error(`Failed to send cancellation: ${C}`)));let S=M instanceof l?M:new l(i.RequestTimeout,String(M));H(S)};this._responseHandlers.set(F,(M)=>{if(Q?.signal?.aborted)return;if(M instanceof Error)return H(M);try{let S=E1(W,M.result);if(!S.success)H(S.error);else b(S.data)}catch(S){H(S)}}),Q?.signal?.addEventListener("abort",()=>{B(Q?.signal?.reason)});let K=Q?.timeout??oU,P=()=>B(l.fromError(i.RequestTimeout,"Request timed out",{timeout:K}));this._setupTimeout(F,K,Q?.maxTotalTimeout,P,Q?.resetTimeoutOnProgress??!1);let q=Y?.taskId;if(q){let M=(S)=>{let C=this._responseHandlers.get(F);if(C)C(S);else this._onerror(Error(`Response handler missing for side-channeled request ${F}`))};this._requestResolvers.set(F,M),this._enqueueTaskMessage(q,{type:"request",message:U,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(F),H(S)})}else this._transport.send(U,{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((M)=>{this._cleanupTimeout(F),H(M)})})}async getTask($,W){return this.request({method:"tasks/get",params:$},H9,W)}async getTaskResult($,W,Q){return this.request({method:"tasks/result",params:$},W,Q)}async listTasks($,W){return this.request({method:"tasks/list",params:$},F9,W)}async cancelTask($,W){return this.request({method:"tasks/cancel",params:$},Pw,W)}async notification($,W){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let Q=W?.relatedTask?.taskId;if(Q){let w={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[T1]:W.relatedTask}}};await this._enqueueTaskMessage(Q,{type:"notification",message:w,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!W?.relatedRequestId&&!W?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let w={...$,jsonrpc:"2.0"};if(W?.relatedTask)w={...w,params:{...w.params,_meta:{...w.params?._meta||{},[T1]:W.relatedTask}}};this._transport?.send(w,W).catch((Y)=>this._onerror(Y))});return}let J={...$,jsonrpc:"2.0"};if(W?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[T1]:W.relatedTask}}};await this._transport.send(J,W)}setRequestHandler($,W){let Q=N8($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(X,G)=>{let J=E8($,X);return Promise.resolve(W(J,G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,W){let Q=N8($);this._notificationHandlers.set(Q,(X)=>{let G=E8($,X);return Promise.resolve(W(G))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let W=this._taskProgressTokens.get($);if(W!==void 0)this._progressHandlers.delete(W),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,W,Q){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let X=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,W,Q,X)}async _clearTaskQueue($,W){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,W);for(let X of Q)if(X.type==="request"&&b8(X.message)){let G=X.message.id,J=this._requestResolvers.get(G);if(J)J(new l(i.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,W){let Q=this._options?.defaultTaskPollInterval??1000;try{let X=await this._taskStore?.getTask($);if(X?.pollInterval)Q=X.pollInterval}catch{}return new Promise((X,G)=>{if(W.aborted){G(new l(i.InvalidRequest,"Request cancelled"));return}let J=setTimeout(X,Q);W.addEventListener("abort",()=>{clearTimeout(J),G(new l(i.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,W){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(X)=>{if(!$)throw Error("No request provided");return await Q.createTask(X,$.id,{method:$.method,params:$.params},W)},getTask:async(X)=>{let G=await Q.getTask(X,W);if(!G)throw new l(i.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(X,G,J)=>{await Q.storeTaskResult(X,G,J,W);let w=await Q.getTask(X,W);if(w){let Y=s6.parse({method:"notifications/tasks/status",params:w});if(await this.notification(Y),R1(w.status))this._cleanupTaskProgressHandler(X)}},getTaskResult:(X)=>{return Q.getTaskResult(X,W)},updateTaskStatus:async(X,G,J)=>{let w=await Q.getTask(X,W);if(!w)throw new l(i.InvalidParams,`Task "${X}" not found - it may have been cleaned up`);if(R1(w.status))throw new l(i.InvalidParams,`Cannot update task "${X}" from terminal status "${w.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(X,G,J,W);let Y=await Q.getTask(X,W);if(Y){let b=s6.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(b),R1(Y.status))this._cleanupTaskProgressHandler(X)}},listTasks:(X)=>{return Q.listTasks(X,W)}}}}function Ew($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Tw($,W){let Q={...$};for(let X in W){let G=X,J=W[G];if(J===void 0)continue;let w=Q[G];if(Ew(w)&&Ew(J))Q[G]={...w,...J};else Q[G]=J}return Q}var JH=RQ(jW(),1),wH=RQ(GH(),1);function Xj(){let $=new JH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return wH.default($),$}class kW{constructor($){this._ajv=$??Xj()}getValidator($){let W="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(Q)=>{if(W(Q))return{valid:!0,data:Q,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(W.errors)}}}}class vW{constructor($){this._server=$}requestStream($,W,Q){return this._server.requestStream($,W,Q)}async getTask($,W){return this._server.getTask({taskId:$},W)}async getTaskResult($,W,Q){return this._server.getTaskResult({taskId:$},W,Q)}async listTasks($,W){return this._server.listTasks($?{cursor:$}:void 0,W)}async cancelTask($,W){return this._server.cancelTask({taskId:$},W)}}function YH($,W,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${W})`);switch(W){case"tools/call":if(!$.tools?.call)throw Error(`${Q} does not support task creation for tools/call (required for ${W})`);break;default:break}}function bH($,W,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${W})`);switch(W){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${Q} does not support task creation for sampling/createMessage (required for ${W})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${Q} does not support task creation for elicitation/create (required for ${W})`);break;default:break}}class _W extends T8{constructor($,W){super(W);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($4.options.map((Q,X)=>[Q,X])),this.isMessageIgnored=(Q,X)=>{let G=this._loggingLevels.get(X);return G?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=W?.capabilities??{},this._instructions=W?.instructions,this._jsonSchemaValidator=W?.jsonSchemaValidator??new kW,this.setRequestHandler(D8,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(F8,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(j8,async(Q,X)=>{let G=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Q.params,w=$4.safeParse(J);if(w.success)this._loggingLevels.set(G,w.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new vW(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Tw(this._capabilities,$)}setRequestHandler($,W){let X=a4($)?.method;if(!X)throw Error("Schema is missing a method literal");let G;if(X6(X)){let w=X;G=w._zod?.def?.value??w.value}else{let w=X;G=w._def?.value??w.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let w=async(Y,b)=>{let H=E1(e6,Y);if(!H.success){let B=H.error instanceof Error?H.error.message:String(H.error);throw new l(i.InvalidParams,`Invalid tools/call request: ${B}`)}let{params:z}=H.data,F=await Promise.resolve(W(Y,b));if(z.task){let B=E1(J6,F);if(!B.success){let K=B.error instanceof Error?B.error.message:String(B.error);throw new l(i.InvalidParams,`Invalid task creation result: ${K}`)}return B.data}let U=E1(B9,F);if(!U.success){let B=U.error instanceof Error?U.error.message:String(U.error);throw new l(i.InvalidParams,`Invalid tools/call result: ${B}`)}return U.data};return super.setRequestHandler($,w)}return super.setRequestHandler($,W)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);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 ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);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 ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){bH(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;YH(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let W=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:zw.includes(W)?W:w8,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"},G9)}async createMessage($,W){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let Q=$.messages[$.messages.length-1],X=Array.isArray(Q.content)?Q.content:[Q.content],G=X.some((b)=>b.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,w=J?Array.isArray(J.content)?J.content:[J.content]:[],Y=w.some((b)=>b.type==="tool_use");if(G){if(X.some((b)=>b.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let b=new Set(w.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(X.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(b.size!==H.size||![...b].every((z)=>H.has(z)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},q8,W);return this.request({method:"sampling/createMessage",params:$},M8,W)}async elicitInput($,W){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},L9,W)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},G=await this.request({method:"elicitation/create",params:X},L9,W);if(G.action==="accept"&&G.content&&X.requestedSchema)try{let w=this._jsonSchemaValidator.getValidator(X.requestedSchema)(G.content);if(!w.valid)throw new l(i.InvalidParams,`Elicitation response content does not match requested schema: ${w.errorMessage}`)}catch(J){if(J instanceof l)throw J;throw new l(i.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return G}}}createElicitationCompletionNotifier($,W){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:$}},W)}async listRoots($,W){return this.request({method:"roots/list",params:$},I8,W)}async sendLoggingMessage($,W){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,W))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}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 HH={name:"@sequenzy/mcp",version:"0.0.149",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",lint:"eslint src","type-check":"bunx --bun 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:"^7.0.2"},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 xW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],zH={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}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",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 Jj($){let Q=($??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return Q.length>0?Q:"https://sequenzy.com"}function e0($){let W=$?.trim();return W?W:void 0}function J1($){return encodeURIComponent($)}function D0($,W){return`${$}${W}`}function F0($,W=""){return`/dashboard/company/${J1($)}${W}`}function DH($,W,Q){return D0($,`${F0(W,"/settings")}?tab=${encodeURIComponent(Q)}`)}function wj($,W){let Q=xW.map((X)=>[X,W?DH($,W,X):""]);return Object.fromEntries(Q)}function A1($={},W){let Q=Jj(W),X=e0($.companyId),G={},J=wj(Q,X);if(!X)return{appUrl:Q,routeTemplates:zH,settingsTabValues:xW,urls:G,settingsUrls:J};G.dashboard=D0(Q,F0(X)),G.campaigns=D0(Q,F0(X,"/campaign")),G.landingPages=D0(Q,F0(X,"/landing-pages")),G.sequences=D0(Q,F0(X,"/sequences")),G.settings=D0(Q,F0(X,"/settings")),G.emails=D0(Q,F0(X,"/emails")),G.subscribers=D0(Q,F0(X,"/subscribers")),G.sentEmails=D0(Q,F0(X,"/sent-emails")),G.segments=D0(Q,F0(X,"/segments")),G.metrics=D0(Q,F0(X,"/metrics")),G.transactional=D0(Q,F0(X,"/transactional"));let w=e0($.campaignId);if(w)G.campaign=D0(Q,F0(X,`/campaign/${J1(w)}`)),G.campaignPreview=`${G.campaign}?step=review`;let Y=e0($.landingPageId);if(Y)G.landingPage=D0(Q,F0(X,`/landing-pages/${J1(Y)}`));let b=e0($.sequenceId);if(b)G.sequence=D0(Q,F0(X,`/sequences/${J1(b)}`));let H=e0($.emailId)??e0($.templateId);if(H)G.email=D0(Q,F0(X,`/emails/${J1(H)}`)),G.template=G.email;let z=e0($.transactionalId);if(z)G.transactionalEmail=D0(Q,F0(X,`/transactional/${J1(z)}`));let F=e0($.emailSendId);if(F)G.emailSend=D0(Q,F0(X,`/sent-emails/${J1(F)}`));let U=e0($.domainId);if(U)G.domain=D0(Q,F0(X,`/settings/domain/${J1(U)}`)),G.domainVerify=`${G.domain}/verify`;let B=e0($.status);if(B)G.campaignList=D0(Q,F0(X,`/campaign/list/${J1(B)}`)),G.sequenceList=D0(Q,F0(X,`/sequences/list/${J1(B)}`));let K=e0($.settingsTab);if(K)G.settingsTab=DH(Q,X,K);return{appUrl:Q,routeTemplates:zH,settingsTabValues:xW,urls:G,settingsUrls:J}}var FH=[{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 UH($){try{let W;switch($){case"sequenzy://dashboard":W=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let Q=await D("GET","/api/v1/account"),X=j1()??Q.currentCompanyId;if(!X)throw Error("No company available. Create or select a company first.");W=await D("GET",`/api/v1/companies/${X}`);break}case"sequenzy://campaigns/recent":W=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":W=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":W=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":W=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":W=await D("GET","/api/v1/templates");break;case"sequenzy://segments":W=await D("GET","/api/v1/segments");break;case"sequenzy://tags":W=await D("GET","/api/v1/tags");break;case"sequenzy://health":W=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":W=A1();break;default:throw Error(`Unknown resource: ${$}`)}return{contents:[{uri:$,mimeType:"application/json",text:JSON.stringify(W,null,2)}]}}catch(W){return{contents:[{uri:$,mimeType:"text/plain",text:V1(W)}]}}}function h($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function L($,W){let Q=$[W];if(typeof Q!=="string")return;let X=Q.trim();return X.length>0?X:void 0}function hW($,W,Q){let X=W[Q];if(X===void 0||X===null)return[];if(typeof X==="string"){let J=X.trim();return J.length>0?[J]:[]}if(!Array.isArray(X))throw Error(`\`${Q}\` must be an array of strings when calling \`${$}\`.`);let G=[];return X.forEach((J,w)=>{if(typeof J!=="string")throw Error(`\`${Q}\` item ${w+1} must be a string when calling \`${$}\`.`);let Y=J.trim();if(Y.length>0&&!G.includes(Y))G.push(Y)}),G}function A($,W,Q){let X=L(W,Q);if(X===void 0)throw Error(`\`${Q}\` is required when calling \`${$}\`.`);return X}var $$=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"button","text":"Click Me","url":"https://example.com","variant":"primary"}; {"type":"image","src":"https://...","alt":"Description","width":100,"widthType":"percent","height":240,"objectFit":"cover","href":"https://example.com","align":"center"}. Heading and text use `content`; button uses `text` but also accepts `content` as an alias and defaults `variant` to `primary`. Image `widthType` accepts `percent` or `px`.';var yW=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "commerceCollection", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',fW=' Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Set `allowMultiple: true` on a text-only options poll to let recipients pick several answers: answer links then open a hosted selection page where the recipient checks any number of options and saves them in one submit, and `attributeKey` stores the list of selected values (filter with attribute `contains`). Multi-select polls cannot use option images or configurations whose encoded signed links exceed the delivery-safe size limit. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). `accentColor` recolors every appearance, including "brutal". `optionRadius` sets answer-button corners in px (0 is square) independently of `styles.borderRadius`, while `questionColor` recolors only the question. `fontFamily` applies to the poll; `optionFontSize`, `optionFontWeight`, `optionLetterSpacing`, and `optionTextTransform` style answers, and the matching `questionFontSize`, `questionFontWeight`, `questionLetterSpacing`, and `questionTextTransform` fields style the question. Sizes and spacing are px, weights are 100-900, and transforms are "none" or "uppercase". Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',uW=' For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',cW="Raw HTML is stored as one opaque block. Sequenzy preserves that markup but does not add a company logo, branded native sections, or theme-driven block design. Use blocks for editor-native design, or a drafting prompt when you want Sequenzy to compose a new branded email.",W$=" Merge tags resolve in this content but are always HTML-escaped; prefix a tag with 'html.' - e.g. {{html.subscriber.body_html}} - to insert a trusted subscriber attribute or variable holding prebuilt HTML unescaped. Injected HTML is sanitized (scripts, event handlers, and dangerous URLs stripped), must be final HTML, and renders raw only in HTML text position, never inside attributes.",U0=`${cW}${W$}`,Q$=' The code is minted per subscriber at run time and reaches every later email in the same sequence as {{discount.code}}. Also available: {{discount.value}} (pre-formatted, e.g. "20% off" or "$10 off"), {{discount.percentOff}}, {{discount.amountOff}}, {{discount.currency}}, and {{date.discount.expiresAt}} (locale-formatted expiry). Present the code with a { "type": "discount-code", "code": "{{discount.code}}", "label": "Your discount code" } block, or inline {{discount.code}} in any text block. These tags resolve only in emails downstream of the discount step; render_email substitutes a clearly fake sample code so the email can be previewed before anyone is enrolled, and lists anything it could not resolve under unresolvedMergeTags.',y1='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',mW=" `styles` applies to the block's own container, not to an inner rendered element. On a button block, `styles.backgroundColor` colors the band behind the button and `styles.textColor` does not reach the label - set the top-level `buttonColor` and `buttonTextColor` fields instead, or leave them unset to inherit the email theme's primary color.",d1=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",x0=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. 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\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${W$}${yW}${mW}${d1}${fW}${uW}${$$}`,X$=" Replacing a step's blocks keeps that step's existing Style > Format rather than the company default: a step that already had a logo or footer gets them back even if you omit them, and every block added that way is listed in the response `warnings`. Pass `emailPreset` to change the format. A step whose stored content is a single raw HTML block has no format, so replacing it with another single raw HTML block is stored exactly as sent; replacing it with native blocks converts the step and does add a footer.",Yj=` For action_email:${X$}`,O1=`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\`.${W$}${yW}${mW}${d1}${fW}${uW}${$$}`,K6=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native 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\`. Blocks can include repeat blocks over array variables such as items.${W$}${yW}${mW}${d1}${fW}${uW}${$$}`,o1="Display name recipients see, e.g. 'Brennon at TradeTally'. Selects the sender identity of that name on fromEmail, creating it when the address has no identity by that name; the mailbox's other display names, and everything pinned to them, are untouched. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name.",t1="Display name for the Reply-To address. Requires replyTo; omit it when using replyProfileId, which already carries its own display name. An address carries one Reply-To name company-wide: if replyTo already has a saved profile under a different name, that saved name is kept and the response `warnings` array says so. Rename it with update_sender_profile (type 'reply') to change it everywhere.",I4="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",BH="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",lW=500,gW=500,G$=["is","contains","gt","gte","lt","lte","is_not_empty"],h0={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},N4=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],E4=N4.join(", "),J$={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day. Changing the window does not move contacts already waiting on a delay step - they keep their existing wait time, and narrowing the window can defer them to the next allowed day. Call realign_sequence_enrollments after the change to pull those waits back to the new opening.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00, or 24:00 for the end-of-day boundary. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},bj={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Z6={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:bj,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},P6={type:"object",description:"Wait until the next occurrence of a weekday inside a local-time window before this step, e.g. { day: 'sunday', startTime: '09:00', endTime: '12:00', timezone: 'America/Los_Angeles' }. Continues immediately when the step is reached inside the window, so a Sunday-morning enrollment is not pushed a full week. Place it immediately before the email when the send day matters - it controls when the flow resumes, so any step between it and the email shifts the send off the window (a sequence-level sendingWindow only holds emails at send time; it does not reschedule the graph).",properties:{day:{type:"string",description:"Single weekday convenience alias for days, e.g. sunday or sun."},days:{type:"array",items:{type:"string"},description:"Weekdays the wait may release on. Full or short names such as sunday, sun. The nearest upcoming day wins."},startTime:{type:"string",description:"Window start in 24-hour HH:mm local time, e.g. 09:00. Required."},endTime:{type:"string",description:"Window end in 24-hour HH:mm local time. Defaults to the end-of-day boundary 24:00. If the wake-up is missed past endTime (rare operational failure), the wait rolls to the next configured day instead of releasing late."},timezone:{type:"string",description:"IANA timezone the window is evaluated in, e.g. America/Los_Angeles. Required."},untilStartTime:{type:"string",description:"Alias for startTime."},untilEndTime:{type:"string",description:"Alias for endTime."},untilTimezone:{type:"string",description:"Alias for timezone."}},additionalProperties:!1},V6={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil. For a wait-until-weekday-window delay, either set mode:'until_weekday' plus untilDays/untilStartTime/untilTimezone here, or use waitUntilWeekday.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date","until_weekday"],description:"Use duration for a fixed wait, until_date to resolve a date from the trigger event, or until_weekday to wait for the next weekday/time window."},untilDays:{type:"array",items:{type:"string"},description:"For mode:'until_weekday', weekday names the wait may release on."},untilStartTime:{type:"string",description:"For mode:'until_weekday', window start in 24-hour HH:mm local time."},untilEndTime:{type:"string",description:"For mode:'until_weekday', window end in 24-hour HH:mm local time. Defaults to the end-of-day boundary 24:00."},untilTimezone:{type:"string",description:"For mode:'until_weekday', IANA timezone the window is evaluated in."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},pW={type:"object",description:`Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, waitUntil, or waitUntilWeekday ({ day, startTime, endTime, timezone } - hold until the next weekday window); optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, emailPreset, isTransactional, attachments ([{ filename, path }] URL-backed files fetched at send time; path may use {{event.*}} from the enrollment event; [] removes them), and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. For an existing random logic_branch, randomPercentages may be updated with one non-negative value per branch summing to 100. splitMode cannot be converted in place because condition and random splits have different graph topology; build a new random split with insert_sequence_step. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.${Yj}`,properties:{emailPreset:{type:"string",enum:["branded","minimal"],description:"For an action_email node with native Sequenzy blocks, set the linked email's per-email Style > Format. Native block emails may include supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded to restore branded chrome. This does not change the company-wide default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},w$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:pW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},j6=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],M6=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var Hj=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","request_api_key_handoff","list_websites","list_integrations","get_integration","get_integration_pixel","list_integration_capabilities","list_integration_activity","get_event_schema","list_sender_profiles","get_notification_preferences","get_tracking_settings","get_sending_status","check_website","get_integration_guide","get_subscriber","get_subscriber_import","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_email_components","get_email_component","get_default_email_component","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_campaign_audience","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","list_popups","get_popup","get_popup_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_enrollments","get_sequence_enrollment_realignment","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_transactional_stats","get_campaign_stats","list_poll_responses","get_sequence_stats","list_campaign_events","list_sequence_events","list_email_metrics","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),zj=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","update_sms_number_label","resume_sending","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","sync_integration","activate_integration_pixel","create_api_key","update_api_key","revoke_api_key","delete_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","create_subscriber_import","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","trigger_subscriber_event","trigger_subscriber_events","bulk_add_subscriber_tags","bulk_remove_subscriber_tags","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","create_email_component","update_email_component","set_default_email_component","delete_email_component","restart_ab_test","update_ab_test_variant","update_ab_test","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","share_campaign","unshare_campaign","share_template","unshare_template","unschedule_campaign","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","update_form","create_popup","update_popup","duplicate_popup","delete_popup","create_landing_page","update_landing_page","duplicate_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","send_sequence_test_email","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","duplicate_sequence","archive_sequence","unarchive_sequence","create_sequence_goal","update_sequence_goal","delete_sequence_goal","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","move_sequence_enrollments","realign_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","delete_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),Dj=new Set(["send_test_email","send_test_sms","send_sequence_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","enable_sequence","unarchive_sequence","resume_sequence_enrollments","move_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),Fj=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","bulk_remove_subscriber_tags","delete_segment","delete_audience_sync","delete_template","delete_email_component","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","delete_popup","set_integration_sync_enabled","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","move_sequence_enrollments","realign_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","delete_transactional_email","remove_recipient_suppression","unshare_campaign","unshare_template"]);function Uj($){let W=Hj.has($),Q=zj.has($);if(W===Q)throw Error(`MCP tool "${$}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:W,destructiveHint:W?!1:Fj.has($),openWorldHint:Dj.has($)}}function LH($){return{...$,annotations:{...$.annotations,...Uj($.name)}}}var iW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains","is","is_not"],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"],pollResponse:["is"],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"],commerceProduct:["is","is_not","at_least","less_than_count"],commerceCollection:["is","is_not","at_least","less_than_count"]},Bj=Object.entries(iW).map(([$,W])=>`${$}: ${W.join(", ")}`).join("; "),nW={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","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct","commerceCollection"],description:`Filter field. Use \`email\` with is/is_not for exact, case-insensitive address matching (allowlists and exclusions) and with contains/not_contains for domain or substring matching. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Use \`commerceCollection\` to segment on anyone who bought ANY product in a store collection - the value is the collection id or handle (e.g. \`skincare\`), optionally provider-prefixed and/or with an order-count threshold (\`shopify:skincare:2\`); collection membership is resolved from the synced catalog as it stands now, and only Shopify collections and WooCommerce categories are synced. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${y1}`},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: ${Bj}.`},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, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${y1}`}},required:["field","operator","value"],additionalProperties:!1},dW={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 Y$($){if(!Array.isArray($))return $;return $.map((W)=>{if(typeof W!=="object"||W===null)return W;let Q=W;if(typeof Q.id==="string"&&Q.id.trim()!=="")return Q;return{...Q,id:crypto.randomUUID()}})}function b$($){if(typeof $!=="object"||$===null)return $;let W=$;if(W.kind==="filter"||"field"in W||"operator"in W||"value"in W){let Q=Y$([W]);return Array.isArray(Q)?Q[0]:W}if(W.kind!=="group")return $;return{...W,id:typeof W.id==="string"&&W.id.trim()!==""?W.id:crypto.randomUUID(),children:Array.isArray(W.children)?W.children.map(b$):[]}}function Lj($){let W=$.indexOf(":");return W!==-1&&$.substring(0,W).trim().length>0}function Aj($){let W=$.indexOf(":");return W!==-1&&$.substring(W+1).trim().length>0}function AH($){if($==="all")return!0;let W=$.match(/^(\d+)d$/);if(!W?.[1])return!1;let Q=Number.parseInt(W[1],10);return Number.isInteger(Q)&&Q>0}function Oj($,W){let Q=W.split(":");if($==="at_least"||$==="less_than_count"){if(Q.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let J=Q.slice(0,-2).join(":").trim(),w=Q.at(-2),Y=Q.at(-1),b=w===void 0?Number.NaN:Number.parseInt(w,10);return J&&Number.isInteger(b)&&b>0&&Y!==void 0&&AH(Y)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(Q.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let X=Q.slice(0,-1).join(":").trim(),G=Q.at(-1);return X&&G!==void 0&&AH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function Kj($){let W=$.indexOf(":");if(W===-1)return{productId:$,subfilter:null,rawValue:null};let Q=$.substring(0,W),X=$.substring(W+1),G=X.indexOf(":");if(G===-1)return{productId:Q,subfilter:X,rawValue:null};return{productId:Q,subfilter:X.substring(0,G),rawValue:X.substring(G+1)}}function Zj($){return $.trim().toLowerCase().replace(/[-\s]+/g,"_")}function Pj($){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($)}function Vj($,W){if(W==="cancels_at"||W==="cancel_at"||W==="cancellation_at")return!0;if($==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(W);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(W)}function jj($){return["is","is_not","gte","lte","gt","lt"].includes($)}function Mj($,W,Q){if($==="stripeProduct"){if(W!=="at_least"&&W!=="less_than_count")return null;let Y=Q.indexOf(":");if(Y===-1)return null;let b=Q.substring(0,Y).trim(),H=Number.parseInt(Q.substring(Y+1).trim(),10);return b&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if($!=="stripeCurrentProduct"&&$!=="stripeTrialProduct")return null;let{productId:X,subfilter:G,rawValue:J}=Kj(Q);if(!X.trim())return"Stripe product filters must include a product ID.";if(!G)return W==="is"||W==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let w=Zj(G);if(Pj(w))return W==="is"||W==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!Vj($,w))return`Unsupported Stripe product subfilter "${G}".`;if(!jj(W))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return J?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var OH=new Set(["shopify","woocommerce","api"]);function qj($,W){let Q=W.trim(),X=Q.indexOf(":");if(X!==-1&&OH.has(Q.substring(0,X).trim()))Q=Q.substring(X+1).trim();if(!Q)return'Purchased Product filters must include a product ID, like "shopify:42".';if($!=="at_least"&&$!=="less_than_count")return null;let G=Q.lastIndexOf(":");if(G===-1)return null;let J=Q.substring(0,G).trim(),w=Number.parseInt(Q.substring(G+1).trim(),10);return J&&Number.isInteger(w)&&w>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function Ij($,W){let Q=W.trim(),X=Q.indexOf(":");if(X!==-1&&OH.has(Q.substring(0,X).trim()))Q=Q.substring(X+1).trim();if(!Q)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if($!=="at_least"&&$!=="less_than_count")return null;let G=Q.lastIndexOf(":");if(G===-1)return null;let J=Q.substring(0,G).trim(),w=Number.parseInt(Q.substring(G+1).trim(),10);return J&&Number.isInteger(w)&&w>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function Nj($){let W;try{W=JSON.parse($)}catch{return`Poll response filters must use valid JSON. ${y1}`}if(!h(W)||W.v!==1||typeof W.campaignId!=="string"||!W.campaignId.trim()||typeof W.blockId!=="string"||!W.blockId.trim()||!h(W.match))return`Poll response filter context is invalid. ${y1}`;let Q=W.match;if(Q.kind==="answer"&&typeof Q.value==="string"&&Q.value.length>0)return null;if(Q.kind==="npsBucket"&&(Q.bucket==="promoters"||Q.bucket==="passives"||Q.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${y1}`}function H$($){if(typeof $!=="object"||$===null)return"Segment filters must be objects.";let W=$,Q=W.field,X=W.operator,G=W.value;if(typeof Q!=="string"||!(Q in iW))return`Unsupported segment filter field "${String(Q)}".`;if(typeof X!=="string")return`Segment filter "${Q}" must include an operator.`;let J=iW[Q];if(!J.includes(X))return`Operator "${X}" is not supported for ${Q} filters. Use one of: ${J.join(", ")}.`;if(X!=="is_empty"&&X!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${Q}" must include a value.`;if(Q==="attribute"){if(typeof G!=="string")return'Attribute filters must include a value: "attributeName:value", or "attributeName:" for empty checks.';if(!Lj(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(X!=="is_empty"&&X!=="is_not_empty"&&!Aj(G))return'Attribute filters must include a value after "attributeName:".'}if(Q==="event"&&typeof G==="string"){let w=Oj(X,G);if(w)return w}if(Q==="pollResponse"&&typeof G==="string"){let w=Nj(G);if(w)return w}if((Q==="stripeProduct"||Q==="stripeCurrentProduct"||Q==="stripeTrialProduct")&&typeof G==="string"){let w=Mj(Q,X,G);if(w)return w}if(Q==="commerceProduct"&&typeof G==="string"){let w=qj(X,G);if(w)return w}if(Q==="commerceCollection"&&typeof G==="string"){let w=Ij(X,G);if(w)return w}if(Q==="tag"&&(X==="contains"||X==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function z$($){if(typeof $!=="object"||$===null)return[];let W=$;if(W.kind==="filter"||"field"in W||"operator"in W||"value"in W){let Q=H$(W);return Q?[Q]:[]}if(Array.isArray(W.children))return W.children.flatMap(z$);return[]}function y0($,W,Q){if(W.html!==void 0&&W.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${$}\`, not both.`);if(W.blocks!==void 0&&!Array.isArray(W.blocks))throw Error(`\`blocks\` must be an array when calling \`${$}\`.`);if(Q?.requireContent&&W.html===void 0&&W.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${$}\`.`)}function K1($,W){if(W.labels===void 0)return;if(!Array.isArray(W.labels))throw Error(`\`labels\` must be an array when calling \`${$}\`.`);if(W.labels.some((Q)=>typeof Q!=="string"||Q.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${$}\`.`)}function PH($){let W=$.filters!==void 0,Q=$.root!==void 0;if(W&&Q)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!W&&!Q)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(W){if(!Array.isArray($.filters))throw Error("`filters` must be an array when calling `create_segment`.");if($.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(Q&&(typeof $.root!=="object"||$.root===null))throw Error("`root` must be an object when calling `create_segment`.");let X=W?$.filters.flatMap((G)=>{let J=H$(G);return J?[J]:[]}):z$($.root);if(X.length>0)throw Error(X[0]??"Invalid segment filter in `create_segment`.")}function VH($){let W=$.filters!==void 0,Q=$.root!==void 0;if(W&&Q)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if($.name===void 0&&$.filterJoinOperator===void 0&&!W&&!Q)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(W){if(!Array.isArray($.filters))throw Error("`filters` must be an array when calling `update_segment`.");if($.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(Q&&(typeof $.root!=="object"||$.root===null))throw Error("`root` must be an object when calling `update_segment`.");let X=W?$.filters.flatMap((G)=>{let J=H$(G);return J?[J]:[]}):Q?z$($.root):[];if(X.length>0)throw Error(X[0]??"Invalid segment filter in `update_segment`.")}var oW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function tW($,W,Q){if(W[Q]!==void 0&&!h(W[Q]))throw Error(`\`${Q}\` must be an object when calling \`${$}\`.`)}function KH($,W,Q){if(W[Q]!==void 0&&!Array.isArray(W[Q]))throw Error(`\`${Q}\` must be an array when calling \`${$}\`.`)}function jH($){let W=new Set(["companyId",...oW]),Q=Object.keys($).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);let X={};for(let G of oW)if($[G]!==void 0)X[G]=$[G];if(Object.keys(X).length===0)throw Error(`Provide at least one of ${oW.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if($[G]!==void 0&&typeof $[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(tW("update_company",$,"brandColors"),tW("update_company",$,"socialLinks"),tW("update_company",$,"pricing"),$.emailTheme!==void 0&&$.emailTheme!==null&&!h($.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");KH("update_company",$,"valueProps"),KH("update_company",$,"testimonials");for(let G of["replyTrackingEnabled","forwardReplies"])if($[G]!==void 0&&typeof $[G]!=="boolean")throw Error(`\`${G}\` must be a boolean when calling \`update_company\`.`);if($.replyTrackingDomainMode!==void 0&&$.replyTrackingDomainMode!=="sequenzy"&&$.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof $.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test($.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let G of["fromEmail","replyTo"]){let J=$[G];if(typeof J==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(J.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}return X}var rW=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],sW=["source","medium","campaign","content","term"];function MH($){let W=new Set(["companyId",...rW]),Q=Object.keys($).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let X={};for(let G of rW)if($[G]!==void 0)X[G]=$[G];if(Object.keys(X).length===0)throw Error(`Provide at least one of ${rW.map((G)=>`\`${G}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let G of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if($[G]!==void 0&&typeof $[G]!=="boolean")throw Error(`\`${G}\` must be a boolean when calling \`update_tracking_settings\`.`);if($.defaultAttributionWindowHours!==void 0&&(typeof $.defaultAttributionWindowHours!=="number"||!Number.isInteger($.defaultAttributionWindowHours)||$.defaultAttributionWindowHours<1||$.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if($.autoUtmSettings!==void 0&&$.autoUtmSettings!==null&&!h($.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(h($.autoUtmSettings)){let G=$.autoUtmSettings,J=Object.keys(G).filter((w)=>!sW.includes(w));if(J.length>0)throw Error(`\`autoUtmSettings\` accepts only ${sW.map((w)=>`\`${w}\``).join(", ")}. Unsupported: ${J.map((w)=>`\`${w}\``).join(", ")}.`);for(let w of sW){let Y=G[w];if(Y!==void 0&&Y!==null&&typeof Y!=="string")throw Error(`\`autoUtmSettings.${w}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return X}var eW={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},$Q={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function WQ($){let{profileKey:W,emailKey:Q,nameKey:X,addressLabel:G}=$.pair,J=$.args[W]!==void 0,w=$.args[Q]!==void 0,Y=$.args[X]!==void 0,b=$.location?`for ${$.location} when calling \`${$.toolName}\``:`when calling \`${$.toolName}\``,H=`\`${W}\` already sets both the ${G} address and the display name, so send it without \`${Q}\`${$.nameIsOverride?"":` and \`${X}\``}.`;if(J&&w){let[z,F]=$.profileFirst?[W,Q]:[Q,W];throw Error(`Provide either \`${z}\` or \`${F}\` ${b}, not both. ${H}`)}if(J&&Y&&!$.nameIsOverride)throw Error(`\`${X}\` cannot be combined with \`${W}\` ${b}. ${H}`);if(Y&&!w&&!$.nameIsOverride)throw Error(`\`${X}\` requires \`${Q}\` ${b}. Send \`${X}\` with the \`${Q}\` it names, or send \`${W}\` on its own to use an existing profile's address and name.`)}function q6($,W,Q){let X=Q?.replyFirst?[$Q,eW]:[eW,$Q];for(let G of X)WQ({toolName:$,args:W,pair:G})}var qH=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function Ej($){return qH.some((W)=>$[W]!==void 0)}function Tj($){if(typeof $.nodeType==="string")return $.nodeType==="action_email";return $.type===void 0||$.type==="email"}function D$($,W,Q){for(let X of qH){let G=Q[X];if(G!==void 0&&typeof G!=="string")throw Error(`\`${X}\` must be a string for ${W} when calling \`${$}\`.`)}WQ({toolName:$,args:Q,pair:eW,location:W,profileFirst:!0,nameIsOverride:!0}),WQ({toolName:$,args:Q,pair:$Q,location:W,profileFirst:!0})}function QQ($,W,Q){if(Ej(Q)&&!Tj(Q))throw Error(`Sender identity fields are only supported for email steps at ${W} when calling \`${$}\`.`);D$($,W,Q)}function ZH($,W,Q){if(!Array.isArray(Q))return;Q.forEach((X,G)=>{if(h(X))D$($,`${W}[${G}]`,X)})}function aW($,W,Q){if(!Array.isArray(Q))return;Q.forEach((X,G)=>{if(h(X))QQ($,`${W}[${G}]`,X)})}function Rj($){if(ZH("update_sequence","emails",$.emails),ZH("update_sequence","steps",$.steps),h($.insertSteps))aW("update_sequence","insertSteps.steps",$.insertSteps.steps);if(!h($.branch))return;if(Array.isArray($.branch.branches))$.branch.branches.forEach((Q,X)=>{if(h(Q))aW("update_sequence",`branch.branches[${X}].steps`,Q.steps)});aW("update_sequence","branch.elseSteps",$.branch.elseSteps)}function IH($){K1("update_sequence",$);let W=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if($.trigger===void 0&&W.some((X)=>$[X]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(q6("update_sequence",$),$.clearEnrollmentFieldPath===!0&&$.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if($.clearSendingWindow===!0&&$.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if($.clearBccEmails===!0&&$.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if($.branch!==void 0&&$.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");Rj($);let Q={...$};if(delete Q.clearEnrollmentFieldPath,delete Q.clearSendingWindow,delete Q.clearBccEmails,$.clearEnrollmentFieldPath===!0)Q.enrollmentFieldPath=null;if($.clearSendingWindow===!0)Q.sendingWindow=null;if($.clearBccEmails===!0)Q.bccEmails=null;return Q}function Sj($,W){if((W.triggerType??"event")==="event"){if(typeof W.triggerEventName!=="string"||W.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${$}\` with an event goal (the default \`triggerType\`).`);return}if(typeof W.attributePath!=="string"||W.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${$}\` with \`triggerType: "attribute_change"\`.`);let X=W.attributeCondition??"changed",G=typeof W.attributeValue==="string"&&W.attributeValue.trim().length>0,J=typeof W.attributePreviousValue==="string"&&W.attributePreviousValue.trim().length>0;if((X==="changed_to"||X==="changed_from_to")&&!G)throw Error(`\`attributeValue\` is required when calling \`${$}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(X==="changed_from_to"&&!J)throw Error(`\`attributePreviousValue\` is required when calling \`${$}\` with \`attributeCondition: "changed_from_to"\`.`)}function NH($){Sj("create_sequence_goal",$)}function EH($){if(typeof $.triggerEventName==="string"&&$.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof $.attributePath==="string"&&$.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function vH($,W,Q){let X=A($,W,"nodeId");if(!h(W.changes)||Object.keys(W.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${Q} when calling \`${$}\`.`);let G=A($,W,"expectedUpdatedAt");return{nodeId:X,changes:W.changes,expectedUpdatedAt:G}}function _H($){let W=vH("update_sequence_node",$,"the node update");return{...$.confirmLiveChange!==void 0&&{confirmLiveChange:$.confirmLiveChange},nodeUpdates:[W]}}function xH($){if(!Array.isArray($.updates)||$.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let W=new Set,Q=$.updates.map((X,G)=>{if(!h(X))throw Error(`\`updates[${G}]\` must be an object when calling \`update_sequence_nodes\`.`);let J=vH("update_sequence_nodes",X,`updates[${G}]`),w=String(J.nodeId);if(W.has(w))throw Error(`\`updates[${G}]\` targets duplicate nodeId '${w}' when calling \`update_sequence_nodes\`.`);return W.add(w),J});return{...$.confirmLiveChange!==void 0&&{confirmLiveChange:$.confirmLiveChange},nodeUpdates:Q}}function hH($){let W=A("edit_sequence_graph",$,"action"),Q=A("edit_sequence_graph",$,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(W))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let G=L($,"nodeId"),J=L($,"afterNodeId"),w=L($,"beforeNodeId"),Y=$.edges;if(W!=="replace_edges"&&!G)throw Error(`\`nodeId\` is required for ${W} when calling \`edit_sequence_graph\`.`);if(W==="replace_edges"&&G)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let b=W==="move_node"||W==="duplicate_node";if(b&&(J?1:0)+(w?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${W} when calling \`edit_sequence_graph\`.`);if(!b&&(J||w))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${W} when calling \`edit_sequence_graph\`.`);if((W==="replace_edges"||W==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${W} when calling \`edit_sequence_graph\`.`);if((W==="move_node"||W==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${W} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(Y)?Y.map((z,F)=>{if(!h(z))throw Error(`\`edges\` item ${F+1} must be an object when calling \`edit_sequence_graph\`.`);let U=A("edit_sequence_graph",z,"sourceNodeId"),B=A("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!h(z.condition))throw Error(`\`edges\` item ${F+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:U,targetNodeId:B,...h(z.condition)?{condition:z.condition}:{}}}):void 0;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},graphEdit:{action:W,expectedRevision:Q,...G?{nodeId:G}:{},...J?{afterNodeId:J}:{},...w?{beforeNodeId:w}:{},...H?{edges:H}:{}}}}function Cj($,W,Q){if(($==="has_tag"||$==="does_not_have_tag")&&!L(W,"tagId")&&!L(W,"tagName"))throw Error(`\`${Q}\` must provide \`tagId\` or \`tagName\` for ${$} when calling \`insert_sequence_step\`.`);if($==="in_list"&&!L(W,"listId"))throw Error(`\`${Q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if($==="in_segment"&&!L(W,"segmentId"))throw Error(`\`${Q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if($==="event_received"&&!L(W,"eventName"))throw Error(`\`${Q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if($.startsWith("field_")&&(!L(W,"fieldName")||!L(W,"fieldValue")))throw Error(`\`${Q}\` must provide \`fieldName\` and \`fieldValue\` for ${$} when calling \`insert_sequence_step\`.`)}var kj=["conditionType","tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"];function yH($){let W=L($,"type")??"email";if(!new Set(["email","sms","delay","create_discount","update_subscriber","condition","add_tag","remove_tag","add_to_list","remove_from_list","webhook","ai","logic_wait_for_event","logic_branch"]).has(W))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(W==="logic_wait_for_event"){let w=A("insert_sequence_step",$,"eventName"),Y=$.timeoutDays,b=Y===void 0?7:Y;if(typeof b!=="number"||!Number.isInteger(b)||b<1||b>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let H=L($,"timeoutAction")??"continue";if(H!=="continue"&&H!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let z={steps:[{nodeType:"logic_wait_for_event",config:{label:L($,"label")??`Wait for ${w}`,eventName:w,timeoutDays:b,timeoutAction:H}}]},F=L($,"afterNodeId");if(F)z.afterNodeId=F;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},insertSteps:z}}if(W==="logic_branch"){let w=A("insert_sequence_step",$,"afterNodeId");if(!Array.isArray($.branches)||$.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let Y=new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]),b=L($,"splitMode")??"condition";if(b!=="condition"&&b!=="random")throw Error("`splitMode` must be `condition` or `random` when inserting `logic_branch` with `insert_sequence_step`.");let H=b==="random";if(H){if(!Array.isArray($.randomPercentages)||$.randomPercentages.length!==$.branches.length)throw Error("`randomPercentages` must contain one percentage per entry in `branches` when `splitMode` is `random`.");if($.randomPercentages.some((q)=>typeof q!=="number"||!Number.isFinite(q)||q<0))throw Error("`randomPercentages` must contain non-negative numbers when `splitMode` is `random`.");let P=$.randomPercentages.reduce((q,M)=>q+M,0);if(Math.abs(P-100)>0.001)throw Error(`\`randomPercentages\` must sum to 100 when \`splitMode\` is \`random\`, received ${P}.`);if(Array.isArray($.elseSteps)&&$.elseSteps.length>0||L($,"elseTargetNodeId"))throw Error("`elseSteps` and `elseTargetNodeId` are not valid when `splitMode` is `random`. Every path is weighted by `randomPercentages`, so add another entry to `branches` instead.")}else if($.randomPercentages!==void 0)throw Error("`randomPercentages` is only valid when `splitMode` is `random`.");let z=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],F=$.allowEmptyPaths===!0,U=$.branches.map((P,q)=>{if(!h(P))throw Error(`\`branches[${q}]\` must be an object when calling \`insert_sequence_step\`.`);let M=`branches[${q}]`;if(H){let v=kj.find((k)=>P[k]!==void 0);if(v)throw Error(`\`${M}.${v}\` must be omitted when \`splitMode\` is \`random\`, because the path is chosen by percentage rather than by evaluating the subscriber.`)}else{let v=A("insert_sequence_step",P,"conditionType");if(!Y.has(v))throw Error(`\`branches[${q}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);Cj(v,P,M)}if(P.steps!==void 0&&!Array.isArray(P.steps))throw Error(`\`branches[${q}].steps\` must be an array when calling \`insert_sequence_step\`.`);let S=L(P,"targetNodeId"),C=Array.isArray(P.steps)&&P.steps.length>0;if(!S&&!C&&!F)throw Error(`\`branches[${q}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(z.flatMap((v)=>P[v]===void 0?[]:[[v,P[v]]]))});if($.elseSteps!==void 0&&!Array.isArray($.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let B=L($,"elseTargetNodeId"),K=Array.isArray($.elseSteps)&&$.elseSteps.length>0;if(!H&&!B&&!K&&!F)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},branch:{afterNodeId:w,...L($,"label")?{label:L($,"label")}:{},...H?{splitMode:b,randomPercentages:$.randomPercentages}:{},branches:U,...Array.isArray($.elseSteps)?{elseSteps:$.elseSteps}:{},...B?{elseTargetNodeId:B}:{},...F?{allowEmptyPaths:!0}:{}}}}if(W==="delay"||W==="create_discount"||W==="update_subscriber"||W==="condition"||W==="add_tag"||W==="remove_tag"||W==="add_to_list"||W==="remove_from_list"||W==="webhook"||W==="ai"){let w;if(W==="delay"){w={type:"delay"};for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if($[H]!==void 0)w[H]=$[H];if(w.delay===void 0&&w.delayMs===void 0&&w.waitUntil===void 0&&w.waitUntilWeekday===void 0)throw Error("Provide `delay`, `delayMs`, `waitUntil`, or `waitUntilWeekday` when inserting a delay step.")}else if(W==="create_discount"){w={type:"create_discount"};for(let H of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if($[H]!==void 0)w[H]=$[H]}else if(W==="update_subscriber"){if(!h($.config))throw Error("`config` is required when inserting an update_subscriber step.");w={type:"update_subscriber",nodeType:"action_update_attributes",config:$.config}}else if(W==="webhook"){let H=L($,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(H))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if($.headers!==void 0&&(!h($.headers)||Object.values($.headers).some((B)=>typeof B!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=L($,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if($.body!==void 0&&typeof $.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if($.resultKey!==void 0&&typeof $.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let F=L($,"body"),U=L($,"resultKey");w={type:"webhook",nodeType:"action_webhook",config:{label:L($,"label")??"Webhook",url:A("insert_sequence_step",$,"url"),method:H,...$.headers!==void 0?{headers:$.headers}:{},...F?{body:F}:{},...U?{resultKey:U}:{},...z?{onError:z}:{}}}}else if(W==="ai"){let H=L($,"onError");if(H&&!["continue","exit","fail"].includes(H))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting an ai step.");if(!Array.isArray($.outputFields)||$.outputFields.length===0)throw Error("`outputFields` is required when inserting an ai step, e.g. [{ key: 'subject_line', fallback: 'We miss you' }].");if($.includeAttributes!==void 0){if(!Array.isArray($.includeAttributes)||$.includeAttributes.some((z)=>typeof z!=="string"))throw Error("`includeAttributes` must be an array of attribute names when inserting an ai step.")}if($.recentEventLimit!==void 0&&typeof $.recentEventLimit!=="number")throw Error("`recentEventLimit` must be a number between 1 and 50 when inserting an ai step.");w={type:"ai",nodeType:"action_ai",config:{label:L($,"label")??"Ask AI",prompt:A("insert_sequence_step",$,"prompt"),resultKey:A("insert_sequence_step",$,"resultKey"),outputFields:$.outputFields,...$.includeTags!==void 0?{includeTags:$.includeTags===!0}:{},...$.includeEventProperties!==void 0?{includeEventProperties:$.includeEventProperties===!0}:{},...$.includeRecentEvents!==void 0?{includeRecentEvents:$.includeRecentEvents===!0}:{},...$.recentEventLimit!==void 0?{recentEventLimit:$.recentEventLimit}:{},...$.includeAttributes!==void 0?{includeAttributes:$.includeAttributes}:{},...H?{onError:H}:{}}}}else if(W==="condition"){let H=A("insert_sequence_step",$,"conditionType");if(!new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]).has(H))throw Error("`conditionType` is not supported for condition steps.");if((H==="has_tag"||H==="does_not_have_tag")&&!L($,"tagId")&&!L($,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!L($,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!L($,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!L($,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!L($,"fieldName")||!L($,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let F={label:L($,"label")??"Condition",conditionType:H};for(let U of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if($[U]!==void 0)F[U]=$[U];w={type:"condition",nodeType:"logic_condition",config:F}}else{let H=W==="add_tag"||W==="remove_tag",z=W==="add_tag"?"action_add_tag":W==="remove_tag"?"action_remove_tag":W==="add_to_list"?"action_add_to_list":"action_remove_from_list",F={label:L($,"label")??(W==="add_tag"?"Add Tag":W==="remove_tag"?"Remove Tag":W==="add_to_list"?"Add to List":"Remove from List")};if(H){let U=L($,"tagId"),B=L($,"tagName");if(!U&&!B)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(U)F.tagId=U;if(B)F.tagName=B}else{F.listId=A("insert_sequence_step",$,"listId");let U=L($,"listName");if(U)F.listName=U}w={nodeType:z,config:F}}for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if(W!=="delay"&&$[H]!==void 0)w[H]=$[H];let Y={steps:[w]},b=L($,"afterNodeId");if(b)Y.afterNodeId=b;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},insertSteps:Y}}let X=W==="sms",G;if(X){QQ("insert_sequence_step","SMS step",$);let w=L($,"text"),Y=Array.isArray($.blocks)&&$.blocks.length>0;if(w===void 0&&!Y)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");G={type:"sms"};for(let b of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil","waitUntilWeekday"])if($[b]!==void 0)G[b]=$[b]}else{y0("insert_sequence_step",$,{requireContent:!0}),D$("insert_sequence_step","email step",$),G={subject:A("insert_sequence_step",$,"subject")};for(let w of["name","previewText","html","blocks","delay","delayMs","waitUntil","waitUntilWeekday","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if($[w]!==void 0)G[w]=$[w]}let J={steps:[G]};if($.afterNodeId!==void 0)J.afterNodeId=$.afterNodeId;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},insertSteps:J}}function TH($,W){let Q=$[W];if(Q===void 0)return[];if(!Array.isArray(Q))throw Error(`\`${W}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let X=Q.map((G)=>typeof G==="string"?G.trim():"").filter((G)=>G.length>0);if(Q.some((G)=>typeof G!=="string")||X.length===0)throw Error(`\`${W}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return X}function RH($,W){let Q=$[W];if(Q===void 0)return[];if(!Array.isArray(Q))throw Error(`\`${W}\` must be an array when calling \`realign_sequence_enrollments\`.`);let X=Q.map((G)=>typeof G==="string"?G.trim():"").filter((G)=>G.length>0);if(Q.some((G)=>typeof G!=="string")||X.length===0)throw Error(`\`${W}\` must contain at least one non-empty string when calling \`realign_sequence_enrollments\`.`);return X}function fH($){let W=RH($,"nodeIds"),Q=RH($,"subscriberIds"),X=L($,"cursor");if($.dryRun!==void 0&&typeof $.dryRun!=="boolean")throw Error("`dryRun` must be a boolean when calling `realign_sequence_enrollments`.");return{...W.length>0&&{nodeIds:W},...Q.length>0&&{subscriberIds:Q},...X!==void 0&&{cursor:X},...typeof $.dryRun==="boolean"&&{dryRun:$.dryRun}}}function uH($){let W=L($,"subscriberId"),Q=TH($,"subscriberIds"),X=TH($,"fieldValues");if($.cancelAll!==void 0&&typeof $.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let G=$.cancelAll===!0;if((W!==void 0?1:0)+(Q.length>0?1:0)+(X.length>0?1:0)+(G?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let w=L($,"fieldPath"),Y=L($,"reason");return{...G&&{cancelAll:!0},...W!==void 0&&{subscriberId:W},...Q.length>0&&{subscriberIds:Q},...w!==void 0&&{fieldPath:w},...X.length>0&&{fieldValues:X},...typeof $.dryRun==="boolean"&&{dryRun:$.dryRun},...Y!==void 0&&{reason:Y}}}var SH=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function CH($,W){let Q=$[W];if(Q===void 0||Q===null)return;let X=typeof Q==="string"?Number(Q):Q,G=W==="dailyLimit"?0:1;if(typeof X!=="number"||!Number.isSafeInteger(X)||X<G)throw Error(`\`${W}\` must be an integer of at least ${G} when calling \`move_sequence_enrollments\`.`);return X}function kH($,W){let Q=$[W];if(Q===void 0)return[];if(!Array.isArray(Q)||Q.some((G)=>typeof G!=="string"))throw Error(`\`${W}\` must be an array of strings when calling \`move_sequence_enrollments\`.`);let X=Q.map((G)=>G.trim()).filter((G)=>G.length>0);if(X.length===0)throw Error(`\`${W}\` must contain at least one non-empty string when calling \`move_sequence_enrollments\`.`);return X}function cH($){let W=A("move_sequence_enrollments",$,"fromNodeId"),Q=L($,"targetNodeId"),X=L($,"reason"),G=L($,"sort");if(G!==void 0&&!SH.includes(G))throw Error(`\`sort\` must be one of ${SH.join(", ")} when calling \`move_sequence_enrollments\`.`);let J=kH($,"subscriberIds"),w=kH($,"tags"),Y=CH($,"limit"),b=CH($,"dailyLimit");return{fromNodeId:W,...Q!==void 0&&{targetNodeId:Q},...Y!==void 0&&{limit:Y},...b!==void 0&&{dailyLimit:b},...G!==void 0&&{sort:G},...J.length>0&&{subscriberIds:J},...w.length>0&&{tags:w},...X!==void 0&&{reason:X},...typeof $.dryRun==="boolean"&&{dryRun:$.dryRun}}}function mH($){y0("create_campaign",$),K1("create_campaign",$);let W=L($,"prompt")!==void 0,Q=$.html!==void 0,X=$.blocks!==void 0,G=$.templateId!==void 0;if($.prompt!==void 0&&!W)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(W&&(Q||X||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!W&&($.style!==void 0||$.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!W&&L($,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function lH($){y0("create_template",$),K1("create_template",$);let W=L($,"prompt")!==void 0,Q=[W,$.html!==void 0,$.blocks!==void 0].filter(Boolean).length;if($.prompt!==void 0&&!W)throw Error("`prompt` cannot be empty when calling `create_template`.");if(Q!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!W&&($.style!==void 0||$.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!W&&L($,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function gH($){if(L($,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if($.targetLists!==void 0&&!h($.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if($.listIds!==void 0&&$.targetLists!==void 0)throw Error("Provide either `listIds` or `targetLists` when calling `schedule_campaign`, not both.");if($.listIds!==void 0&&(!Array.isArray($.listIds)||$.listIds.length===0||$.listIds.some((W)=>typeof W!=="string")))throw Error("`listIds` must be a non-empty array of list ID strings when calling `schedule_campaign`.");if($.sendTimeOptimization!==void 0){if(typeof $.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if($.spreadOverHours!==void 0){if(typeof $.spreadOverHours!=="number"||!Number.isInteger($.spreadOverHours)||$.spreadOverHours<1||$.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if($.recurringInterval!==void 0&&$.recurringInterval!=="weekly"&&$.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function F$($,W,Q){let X=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(W).filter((J)=>!X.has(J));if(G.length>0)throw Error(`\`${$}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((J)=>`\`${J}\``).join(", ")}.`);if(Q.requireUpdate&&W.name===void 0&&W.slug===void 0&&W.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${$}\`.`);return{...W.name!==void 0&&{name:W.name},...W.slug!==void 0&&{slug:W.slug},...W.content!==void 0&&{content:W.content}}}function pH($){let W=new Set(["companyId","domain","verify"]),Q=Object.keys($).filter((X)=>!W.has(X));if(Q.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}.`);if($.domain===void 0&&$.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...$.domain!==void 0&&{domain:$.domain},...typeof $.verify==="boolean"&&{verify:$.verify}}}function iH($){y0("create_transactional_email",$);let W=L($,"prompt")!==void 0,Q=$.html!==void 0,X=$.blocks!==void 0;if($.prompt!==void 0&&!W)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(W&&(Q||X))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!W&&($.style!==void 0||$.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!W&&!Q&&!X)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!W&&L($,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var I6={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},vj={type:"object",description:"Config for advanced nodeType steps. Required fields depend on nodeType: action_add_tag and action_remove_tag need tagId or tagName; action_add_to_list and action_remove_from_list need listId; action_update_attributes uses the Update Subscriber fields (firstName, lastName, status, customAttributeUpdates) and may use trigger-event merge tags; logic_wait_for_event needs eventName plus optional timeoutDays and timeoutAction; logic_condition needs conditionType plus that condition's resource field; action_webhook needs an HTTPS url plus optional method, headers, body, resultKey, and onError; action_ai generates short per-contact fragments (a sentence or two each) that later email steps insert with {{ai.KEY.field}} merge tags, not whole emails, and needs prompt, resultKey, and outputFields plus optional includeTags, includeEventProperties, includeRecentEvents, recentEventLimit, includeAttributes, and onError; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...I6.properties,tagId:{type:"string",description:"action_add_tag / action_remove_tag: tag ID. Pass a name in tagName instead, because tag actions resolve tagId by ID only. has_tag / does_not_have_tag also accept a tag name here. Missing tag definitions are created automatically."},tagName:{type:"string",description:"action_add_tag / action_remove_tag / has_tag / does_not_have_tag: tag name. Use instead of tagId when you only know the name."},listId:{type:"string",description:"action_add_to_list / action_remove_from_list / in_list: list ID. It must match an existing list in this company; listName is filled in for you."},listName:{type:"string",description:"Optional cached list display name for list actions."},eventName:{type:"string",description:"logic_wait_for_event and event_received conditions: event to wait for or check, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"logic_condition: condition evaluated before continuing. has_phone and sms_subscribed need no resource fields."},segmentId:{type:"string",description:"logic_condition: segment ID for in_segment."},segmentName:{type:"string",description:"Optional cached segment display name."},linkUrl:{type:"string",description:"logic_condition: optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"logic_condition: scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"logic_condition: subscriber attribute name/path for field comparisons."},fieldValue:{type:"string",description:"logic_condition: comparison value for field comparisons."},url:{type:"string",description:"action_webhook: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}} resolved at execution time."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'action_webhook: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"action_webhook / action_ai: where the result is saved. Later steps reference it via {{webhooks.KEY.data.field}} (webhook) or {{ai.KEY.field}} (AI) merge tags. Required for action_ai. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"action_webhook / action_ai: behavior when the step fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed. Defaults to fail for webhooks and continue for AI steps (fallbacks fill the output fields)."},prompt:{type:"string",description:"action_ai: prompt template sent to the model, resolved per contact at execution time. Supports merge tags like {{first_name}}, {{event.plan}}, and {{webhooks.KEY.data.field}}. Max 8000 chars."},outputFields:{type:"array",description:"action_ai: named values the model must return (1-10). Each key becomes a {{ai.KEY.<key>}} merge tag for later steps. fallback is used when generation fails, so emails still send with sensible copy. Combined field maxLength values must fit the step's conservative 2000-token multilingual response budget plus JSON overhead.",items:{type:"object",properties:{key:{type:"string",description:"Field key, e.g. subject_line. Must start with a letter; letters, numbers, underscores; max 64 chars; unique within the step."},description:{type:"string",description:"What the model should produce for this field, e.g. 'A subject line under 50 characters'. Max 300 chars."},maxLength:{type:"integer",minimum:1,maximum:4000,description:"Hard cap on stored characters (1-4000). Defaults to 500. Output beyond it is cut."},fallback:{type:"string",description:"Text used verbatim when generation fails or the model omits the field."}},required:["key"],additionalProperties:!1}},includeTags:{type:"boolean",description:"action_ai: include the contact's tags in the prompt context."},includeEventProperties:{type:"boolean",description:"action_ai: include the enrollment's trigger event name and properties in the prompt context."},includeRecentEvents:{type:"boolean",description:"action_ai: include the contact's most recent custom events (newest first) in the prompt context."},recentEventLimit:{type:"number",description:"action_ai: how many recent events to include when includeRecentEvents is true (1-50, default 10)."},includeAttributes:{type:"array",items:{type:"string"},description:"action_ai: custom attribute keys to include in the prompt context (max 30). Only the listed keys are sent."},delayDays:{type:"number",description:"logic_delay: whole days to wait."},delayHours:{type:"number",description:"logic_delay: hours to wait."},delayMinutes:{type:"number",description:"logic_delay: minutes to wait."}},additionalProperties:!0},T4={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Reply-To display name override for this step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."}},R4={type:"object",description:"A typed step to create inside a sequence path, including email, SMS, delay, discount, subscriber actions, conditions, waits, webhooks, and AI steps.",properties:{type:{type:"string",enum:["email","sms","delay","create_discount","discount","update_subscriber","condition","webhook","ai"],description:"Sequence path step type. Omit for email steps; use delay for fixed/date waits or update_subscriber for action_update_attributes. For an event gate, use nodeType:'logic_wait_for_event' with an explicit config object. A path is one linear chain, so it cannot contain a nested 'logic_branch' step: end the path with the step the nested branch should follow, then insert that branch with its own insert_sequence_step call using an afterNodeId from addedBranchPathNodeIds."},nodeType:{type:"string",enum:["logic_delay","action_email","action_sms","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook","action_ai"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action. Tag, list, subscriber-update, wait, condition, webhook, and AI node types carry their fields in config, for example nodeType:'action_add_tag' with config:{ tagName:'newsletter-confirmed' }. SMS steps still use the step-level text/imageUrls/ineligibleAction, discount steps the step-level discount fields, and delays the step-level delay/delayMs/waitUntil."},config:vj,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:K6,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd on this step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},text:{type:"string",description:"SMS only: plain-text message body."},imageUrls:{type:"array",items:{type:"string"},description:"SMS only: up to two public MMS image URLs."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS only: behavior when the contact cannot receive SMS."},delay:V6,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Z6,waitUntilWeekday:P6,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Reply-To display name override for this email step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},discount:{type:"object",description:`Discount configuration for create_discount steps. Same shape as create_sequence steps.${Q$}`,additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},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},XQ={type:"object",properties:{id:{type:"string",description:"Optional stable path ID. Defaults to branch-0, branch-1, and so on. The value 'else' is reserved."},label:{type:"string",description:"Display label, for example 'Replied in this sequence'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition for this path. has_phone and sms_subscribed need no resource fields. Required unless the branch sets splitMode 'random', where paths are chosen by percentage and this field must be omitted."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag."},listId:{type:"string",description:"List ID for in_list."},segmentId:{type:"string",description:"Segment ID for in_segment."},segmentName:{type:"string",description:"Optional display name for in_segment."},eventName:{type:"string",description:"Event name for event_received, for example email.replied."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"Subscriber attribute name/path for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},targetNodeId:{type:"string",description:"Optional existing node to route this branch path to. Use a node ID from get_sequence, including the sequence completion node when this path should stop. If steps are also provided, they run before this target."},steps:{type:"array",description:"Optional new steps for this path. When targetNodeId is also set, the last new step connects to that existing node.",items:R4}},additionalProperties:!1},GQ="Branch paths. On the default condition split they are evaluated in order and an else fallback is created automatically. On a random split (splitMode 'random') each entry is a weighted variant, conditionType and condition-specific fields are omitted, and there is no else path. Each path can create steps, route directly to an existing targetNodeId, or do both.",JQ={type:"string",enum:["condition","random"],description:"How subscribers are routed. 'condition' (default) evaluates each branch's conditionType in order. 'random' assigns each subscriber a path by percentage when they reach the node, which is how you build a concurrent A/B split inside a sequence - for example testing two abandoned-cart offers against each other at the same time instead of running them one after another. Random splits require randomPercentages, omit conditionType and condition-specific fields on every branch, and must not define an else path. To A/B test the content of a single existing email step instead of branching the flow, use create_ab_test with automationNodeId, which tracks variants and picks a winner for you."},wQ={type:"array",items:{type:"number"},description:"Required when splitMode is 'random': one non-negative percentage per entry in branches, in the same order, summing to 100. For an even two-way test use [50, 50]."};function nH($){if(!$||typeof $!=="object")return null;let W=$;if(W.success!==!1)return null;if(typeof W.error==="string")return Error(W.error);if(W.error&&typeof W.error==="object"&&typeof W.error.message==="string")return Error(W.error.message);if(typeof W.message==="string")return Error(W.message);return Error("The tool returned an unsuccessful response.")}var YQ=1000,bQ=1000,HQ=YQ*bQ-1;function zQ($){return $.trim().toLowerCase().replace(/\s+/g,"-")}function _j($,W){let Q=L(W,"attribute"),X=L(W,"attributeValue"),G=u($,W,"attributeOperator",G$);if(!Q){if(X!==void 0||G!==void 0)throw Error(`\`attributeValue\` and \`attributeOperator\` require \`attribute\` when calling \`${$}\`.`);return{}}let J=G??"is",w;if(X!==void 0)w=`${Q}:${X}`;else if(Q.includes(":"))w=Q;else if(J==="is_not_empty")w=`${Q}:`;else throw Error(`Provide \`attributeValue\` (or use \`attribute: "name:value"\`) when \`attributeOperator\` is \`${J}\` in \`${$}\`. Only \`is_not_empty\` may omit a value.`);return{attribute:w,attributeOperator:J}}function xj($){let W=new URLSearchParams;if(typeof $.query==="string"&&$.query.trim()!=="")W.set("query",$.query.trim());if(Array.isArray($.tags)&&$.tags.length>0)W.set("tags",$.tags.filter((Q)=>typeof Q==="string"&&Q.trim()!=="").join(","));if(typeof $.list==="string"&&$.list.trim()!=="")W.set("list",$.list.trim());if(typeof $.listId==="string"&&$.listId.trim()!=="")W.set("listId",$.listId.trim());if(typeof $.listName==="string"&&$.listName.trim()!=="")W.set("listName",$.listName.trim());if(typeof $.segmentId==="string"&&$.segmentId.trim()!=="")W.set("segmentId",$.segmentId);if(typeof $.status==="string"&&$.status.trim()!=="")W.set("status",$.status.trim());if(typeof $.unsubscribedAfter==="string"&&$.unsubscribedAfter.trim()!=="")W.set("unsubscribedAfter",$.unsubscribedAfter.trim());if(typeof $.unsubscribedBefore==="string"&&$.unsubscribedBefore.trim()!=="")W.set("unsubscribedBefore",$.unsubscribedBefore.trim());if($.attribute){if(W.set("attribute",$.attribute),$.attributeOperator)W.set("attributeOperator",$.attributeOperator)}if($.cursor)W.set("cursor",$.cursor);else W.set("page",String($.page));if(W.set("limit",String($.pageSize)),$.includeTotal===!1)W.set("includeTotal","false");return W}async function tH($,W){let X=sH("search_subscribers",$,"limit"),G=L($,"cursor"),J=G?hj("search_subscribers",$):yj("search_subscribers",$,X),w=X===void 0?void 0:J+X,Y=Math.min(YQ,Math.max(1,w??YQ)),b=_j("search_subscribers",$),H=[],z=1,F=G,U,B=null,K=0,P=!1,q=!1;while(!0){let k=w===void 0?void 0:w-H.length,S0=F?Math.min(Y,Math.max(1,k??Y)):Y,g0=xj({query:$.query,tags:$.tags,list:$.list,listId:$.listId,listName:$.listName,segmentId:$.segmentId,status:$.status,unsubscribedAfter:$.unsubscribedAfter,unsubscribedBefore:$.unsubscribedBefore,attribute:b.attribute,attributeOperator:b.attributeOperator,page:z,pageSize:S0,cursor:F}),C0=await D("GET",`/api/v1/subscribers?${g0.toString()}`,void 0,W);if(K===0)B=C0.pagination?.total??null;K+=1,H.push(...C0.subscribers??[]);let a1=(C0.subscribers??[]).length,p0=C0.pagination?.nextCursor??void 0;U=p0;let R6=w!==void 0&&H.length>=w,P1;if(p0)P1=!1;else if(C0.pagination?.hasMore!==void 0)P1=!C0.pagination.hasMore;else if(C0.pagination?.totalPages!==void 0&&C0.pagination.totalPages!==null)P1=z>=C0.pagination.totalPages;else P1=a1<S0;if(P1||a1===0&&!p0){P=!0;break}if(R6)break;if(K>=bQ){q=!0;break}if(p0)F=p0;else if(F)break;else z+=1}if(q&&(H.length<J||H.length===J&&U===void 0))throw Error(`Could not reach offset ${J} within ${bQ} requests because too few matches were returned per page. Start without \`offset\` and follow \`pagination.nextCursor\` instead.`);if(B===null&&P&&!G)B=H.length;let M=H.slice(J,w),S=P?!1:B!==null?J+M.length<B:!P||H.length>J+M.length,C=U!==void 0&&H.length===J+M.length,v=J+M.length;return{success:!0,subscribers:M,pagination:{page:X===void 0?1:Math.floor(J/X)+1,limit:X??Y,offset:J,total:B,totalPages:B===null?null:Math.ceil(B/(X??Y)),fetchedPages:K,hasMore:S,nextOffset:S&&!G&&v<=HQ?v:null,nextCursor:S&&C?U??null:null},returned:M.length,truncated:S}}function hj($,W){if(W.offset!==void 0||W.page!==void 0)throw Error(`\`cursor\` cannot be combined with \`offset\` or \`page\` when calling \`${$}\`. Keep following \`pagination.nextCursor\` instead.`);return 0}function yj($,W,Q){let X=rH($,W,"offset"),G=sH($,W,"page");if(X!==void 0&&G!==void 0)throw Error(`Provide either \`offset\` or \`page\` when calling \`${$}\`, not both.`);if(G!==void 0){if(Q===void 0)throw Error(`\`page\` requires \`limit\` when calling \`${$}\` so the page size is defined. Omit both to fetch every match in one call.`);return dH($,(G-1)*Q)}return dH($,X??0)}function dH($,W){if(W>HQ)throw Error(`\`offset\` must be ${HQ} or less when calling \`${$}\`. Use \`cursor\` to continue beyond that point.`);return W}function rH($,W,Q){let X=W[Q];if(X===void 0||X===null)return;if(typeof X!=="number"||!Number.isInteger(X)||X<0)throw Error(`\`${Q}\` must be a non-negative integer when calling \`${$}\`.`);return X}function sH($,W,Q){let X=rH($,W,Q);if(X!==void 0&&X<1)throw Error(`\`${Q}\` must be 1 or greater when calling \`${$}\`.`);return X}function DQ($){let W=typeof $.email==="string"&&$.email.trim()!==""?$.email.trim():void 0,Q=typeof $.externalId==="string"&&$.externalId.trim()!==""?$.externalId.trim():void 0;return{...W?{email:W}:{},...Q?{externalId:Q}:{}}}function $1($,W){let Q=DQ(W);if(!Q.email&&!Q.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${$}\`.`);return Q}function U$($,W){let Q=new URLSearchParams;if(W?.includeMachineEngagement)Q.set("includeMachineEngagement","true");let X=Q.toString(),G=X?`?${X}`:"";if($.email)return`/api/v1/subscribers/${encodeURIComponent($.email)}${G}`;return Q.set("externalId",String($.externalId)),`/api/v1/subscribers/external?${Q.toString()}`}function FQ($){if($.email)return`/api/v1/subscribers/${encodeURIComponent($.email)}/notes`;let W=new URLSearchParams;return W.set("externalId",String($.externalId)),`/api/v1/subscribers/external/notes?${W.toString()}`}async function S4($,W,Q){return D("GET",U$($,Q),void 0,W)}function u($,W,Q,X){let G=L(W,Q);if(G===void 0)return;if(!X.includes(G))throw Error(`\`${Q}\` must be one of ${X.join(", ")} when calling \`${$}\`.`);return G}function C4($,W,Q,X){let G=A($,W,Q);if(!X.includes(G))throw Error(`\`${Q}\` must be one of ${X.join(", ")} when calling \`${$}\`.`);return G}function X0($,W,Q,X,G){let J=W[Q];if(J===void 0)return;if(typeof J!=="number"||!Number.isInteger(J)||J<X||J>G)throw Error(`\`${Q}\` must be an integer between ${X} and ${G} when calling \`${$}\`.`);return J}function fj($,W){let Q=[],X=u($,W,"eventType",N4);if(X)Q.push(X);if(W.eventTypes!==void 0){if(!Array.isArray(W.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${$}\`.`);W.eventTypes.forEach((G,J)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${J+1} must be a string when calling \`${$}\`.`);let w=G.trim();if(!N4.includes(w))throw Error(`\`eventTypes\` item ${J+1} must be one of ${N4.join(", ")} when calling \`${$}\`.`);Q.push(w)})}return[...new Set(Q)]}function UQ($,W){let Q=new URLSearchParams,X=fj($,W);if(X.length>0)Q.set("eventTypes",X.join(","));let G=u($,W,"period",["1h","24h","7d","30d","90d"]);if(G)Q.set("period",G);let J=L(W,"start");if(J)Q.set("start",J);let w=L(W,"end");if(w)Q.set("end",w);let Y=X0($,W,"page",1,1e6);if(Y!==void 0)Q.set("page",String(Y));let b=X0($,W,"limit",1,500);if(b!==void 0)Q.set("limit",String(b));if(W.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");return Q}function BQ($,W){if(W.events===void 0)return;if(!Array.isArray(W.events))throw Error(`\`events\` must be an array when calling \`${$}\`.`);let Q=W.events.map((X,G)=>{if(typeof X!=="string"||!M6.includes(X))throw Error(`\`events\` item ${G+1} must be one of ${M6.join(", ")} when calling \`${$}\`.`);return X});if(Q.length===0)throw Error(`\`events\` must include at least one event type when calling \`${$}\`.`);return Q}function LQ($,W){if(!Array.isArray(W.emails))throw Error(`\`emails\` must be an array when calling \`${$}\`.`);let Q=[];if(W.emails.forEach((X,G)=>{if(typeof X!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${$}\`.`);let J=X.trim();if(J.length>0)Q.push(J)}),Q.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${$}\`.`);if(Q.length>lW)throw Error(`\`emails\` must include no more than ${lW} email addresses when calling \`${$}\`. Split larger batches into multiple calls.`);return Q}function oH($,W,Q,X){let G=W[Q];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${Q}\` must be an array when calling \`${$}\`.`);let J=[];if(G.forEach((w,Y)=>{if(typeof w!=="string")throw Error(`\`${Q}\` item ${Y+1} must be a string when calling \`${$}\`.`);let b=w.trim();if(b.length>0)J.push(b)}),J.length===0)throw Error(`\`${Q}\` must include at least one ${X} when calling \`${$}\`.`);return J}function aH($){let Q=oH("enroll_subscribers_in_sequence",$,"emails","email address"),X=oH("enroll_subscribers_in_sequence",$,"subscriberIds","subscriber ID"),G=(Q?.length??0)+(X?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>gW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${gW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let J=L($,"targetNodeId");return{...Q!==void 0&&{emails:Q},...X!==void 0&&{subscriberIds:X},...J!==void 0&&{targetNodeId:J}}}import{readFileSync as uj,statSync as cj}from"node:fs";import{basename as mj}from"node:path";var lj={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 gj($){let W=$.split(".").pop()?.toLowerCase()??"";return lj[W]??null}var pj=104857600;async function eH($,W){if(!k4())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 Q=gj($);if(!Q)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let X=cj($).size;if(X>pj)throw Error(`File is too large (${Math.round(X/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=uj($),J=await D("POST","/api/v1/products/delivery/upload-url",{filename:mj($),contentType:Q,fileSizeBytes:X},W),w=await fetch(J.uploadUrl,{method:"PUT",headers:{"Content-Type":Q},body:G});if(!w.ok)throw Error(`File upload failed (${w.status})`);return{url:J.publicUrl,fileName:J.fileName,fileSizeBytes:X,mimeType:Q}}async function B$($){let W=L($,"companyId");if(W)return W;let Q=j1();if(Q)return Q;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function T6($,W){let Q=await B$(W);if(!Q)throw Error(`A company is required when calling \`${$}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return Q}function E6($,W){if(!h($)||!W)return $;return{...$,url:W}}function $3($,W){if(!h($))return $;return{...$,...W.campaign!==void 0&&{url:W.campaign},...W.campaignPreview!==void 0&&{previewUrl:W.campaignPreview}}}function N6($,W,Q){if(!Array.isArray($)||!W)return $;return $.map((X)=>{if(!h(X))return X;let G=L(X,"id");if(!G)return X;let J=A1({companyId:W,...Q==="campaign"&&{campaignId:G},...Q==="landingPage"&&{landingPageId:G},...Q==="sequence"&&{sequenceId:G},...Q==="template"&&{emailId:G},...Q==="transactional"&&{transactionalId:G},...Q==="emailSend"&&{emailSendId:G}});if(Q==="campaign")return $3(X,J.urls);let w=Q==="sequence"?J.urls.sequence:Q==="landingPage"?J.urls.landingPage:Q==="template"?J.urls.email:Q==="transactional"?J.urls.transactionalEmail:J.urls.emailSend;return E6(X,w)})}function ij($){if(!Array.isArray($))return $;return $.map((W)=>{if(!h(W))return W;let Q=L(W,"id");if(!Q)return W;let X=A1({companyId:Q});return{...W,url:X.urls.dashboard,settingsUrl:X.urls.settings}})}var AQ=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","list_email_sends","create_campaign","update_campaign","schedule_campaign","unschedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","move_sequence_enrollments","realign_sequence_enrollments","get_sequence_enrollment_realignment","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","update_ab_test","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function W3($,W,Q){if(!h(Q)||!AQ.has($))return Q;let X=h(Q.company)?Q.company:void 0,J=L(Q,"selectedCompanyId")??L(Q,"currentCompanyId")??L(Q,"companyId")??(X?L(X,"id"):void 0)??(X?L(X,"companyId"):void 0)??await B$(W);if(!J)return Q;let w=h(Q.campaign)?Q.campaign:void 0,Y=h(Q.sequence)?Q.sequence:void 0,b=h(Q.landingPage)?Q.landingPage:void 0,H=h(Q.template)?Q.template:void 0,z=h(Q.transactional)&&!Array.isArray(Q.transactional)?Q.transactional:void 0,F={companyId:J,campaignId:L(W,"campaignId")??L(Q,"campaignId")??(w?L(w,"id"):void 0),landingPageId:L(W,"landingPageId")??L(Q,"landingPageId")??(b?L(b,"id"):void 0),sequenceId:L(W,"sequenceId")??L(Q,"sequenceId")??(Y?L(Y,"id"):void 0),emailId:L(Q,"templateId")??(H?L(H,"id"):void 0)??(z?L(z,"emailId"):void 0)??L(W,"templateId"),transactionalId:L(W,"transactionalId")??(z?L(z,"id"):void 0)??L(W,"idOrSlug"),emailSendId:L(W,"emailSendId")??L(Q,"emailSendId")??(h(Q.emailSend)?L(Q.emailSend,"id"):void 0),status:L(W,"status")},U=A1(F),B=X?A1({companyId:J}):void 0;return{...Q,...Array.isArray(Q.companies)&&{companies:ij(Q.companies)},...Array.isArray(Q.campaigns)&&{campaigns:N6(Q.campaigns,J,"campaign")},...Array.isArray(Q.landingPages)&&{landingPages:N6(Q.landingPages,J,"landingPage")},...Array.isArray(Q.sequences)&&{sequences:N6(Q.sequences,J,"sequence")},...Array.isArray(Q.templates)&&{templates:N6(Q.templates,J,"template")},...Array.isArray(Q.transactional)&&{transactional:N6(Q.transactional,J,"transactional")},...Array.isArray(Q.emailSends)&&{emailSends:N6(Q.emailSends,J,"emailSend")},...X&&B!==void 0&&{company:{...X,url:B.urls.dashboard,settingsUrl:B.urls.settings}},...w&&U.urls.campaign!==void 0&&{campaign:$3(w,U.urls)},...Y&&U.urls.sequence!==void 0&&{sequence:E6(Y,U.urls.sequence)},...b&&U.urls.landingPage!==void 0&&{landingPage:E6(b,U.urls.landingPage)},...H&&U.urls.email!==void 0&&{template:E6(H,U.urls.email)},...z&&U.urls.transactionalEmail!==void 0&&{transactional:E6(z,U.urls.transactionalEmail)},...h(Q.emailSend)&&U.urls.emailSend!==void 0&&{emailSend:E6(Q.emailSend,U.urls.emailSend)},appUrls:U.urls}}import{readFileSync as nj,statSync as dj}from"node:fs";import{basename as oj,extname as X3}from"node:path";var KQ=5242880,tj=Math.ceil(KQ/3)*4,rj=Math.ceil(tj*1.05)+256,G3={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},sj=new Set(Object.values(G3));function OQ($){return $?.split(";")[0]?.trim().toLowerCase()||void 0}function aj($){return G3[X3($).toLowerCase()]}function ej($){let W=X3($);return(W?$.slice(0,-W.length):$).replace(/[-_]+/g," ").trim()||"Image"}function $M($){if($.length>rj)throw Error("Image assets must be 5MB or smaller.")}function WM($){let W=0,Q=0;for(let G=0;G<$.length;G+=1){let J=$.charCodeAt(G);if(J===9||J===10||J===11||J===12||J===13||J===32)continue;W+=1,Q=J===61?Q+1:0}if(Math.floor(W*3/4)-Math.min(Q,2)>KQ)throw Error("Image assets must be 5MB or smaller.")}function QM($){$M($);let W=$.trim(),Q=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(W),X=Q?.[2]??W;WM(X);let G=X.replace(/\s+/g,"");if(G.length===0||G.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(G))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(G,"base64"),...Q?.[1]?{dataUrlContentType:OQ(Q[1])}:{}}}function Q3($){if($<=0)throw Error("The image file is empty.");if($>KQ)throw Error("Image assets must be 5MB or smaller.")}function XM($){let W=aj($.filename)??OQ($.explicitContentType)??OQ($.dataUrlContentType);if(!W||!sj.has(W))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return W}function GM($){let W,Q,X;if($.filePath!==void 0){if(!k4())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let J=dj($.filePath).size;Q3(J),W=nj($.filePath),Q=$.filename??oj($.filePath)}else{if(!$.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!$.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let J=QM($.imageBase64);W=J.bytes,X=J.dataUrlContentType,Q=$.filename,Q3(W.byteLength)}let G=XM({filename:Q,explicitContentType:$.contentType,dataUrlContentType:X});return{bytes:W,filename:Q,contentType:G,altText:$.altText??ej(Q)}}async function J3($){let W=GM($),Q=W.bytes.byteLength,X=await D("POST","/api/v1/media/upload-url",{filename:W.filename,contentType:W.contentType,fileSizeBytes:Q},$.companyId);return await uQ(X.uploadUrl,W.bytes,W.contentType,$.companyId),(await D("POST","/api/v1/media/complete-upload",{key:X.key,filename:X.fileName,contentType:W.contentType,fileSizeBytes:Q,...$.sourceWidth!==void 0&&{width:$.sourceWidth},...$.sourceHeight!==void 0&&{height:$.sourceHeight},altText:W.altText},$.companyId)).asset}var JM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},r1={type:"string",description:"Human-readable status, confirmation, or next-step message."},ZQ={type:"string",description:"Additional context about the result."};function I($){return{type:"object",description:$,additionalProperties:!0}}function Z1($){return{type:"array",description:$,items:I("One item in the returned collection.")}}function O($){return{type:"string",description:$}}function w1($){return{type:["object","null"],description:$,additionalProperties:!0}}function H0($){return{type:["string","null"],description:$}}function _($){return{type:"number",description:$}}function w3($){return{type:["number","null"],description:$}}function c($){return{type:"boolean",description:$}}function j($){return I(`The ${$} record returned by Sequenzy.`)}function y($){return Z1(`List of ${$} records returned by Sequenzy.`)}var f1="`opened` and `clicked` are unique counts deduplicated by email send (one recipient opening five times counts once), not total open events. Every count is attributed to the sends made inside the requested window, including engagement that arrives after the window ends, so `opened <= delivered <= sent` always holds. Rates use `rateDenominator` (`delivered`, or `sent` when no delivery events were recorded, reported as `rateDenominatorBasis`); `deliveryRate` and `bounceRate` divide by `sent`.",b3="Run state: branch on effectiveStatus (draft, live, enrollment_paused, paused, or archived) rather than on status, which reads `active` even when new enrollments are paused. acceptsNewEnrollments and processesExistingEnrollments answer the two questions behind it, and effectiveStatusSummary is a plain-language sentence. The legacy triggerConfig.active flag is not read by the runtime; it is reported as a mirror of acceptsNewEnrollments.",s1=I(`The sequence record returned by Sequenzy. ${b3}`),wM=Z1(`List of sequence records returned by Sequenzy. ${b3}`),L$={effectiveStatus:{type:"string",enum:["draft","live","enrollment_paused","paused","archived"],description:"Resolved run state. The one field to branch on: `status` still reads `active` while new enrollments are paused."},acceptsNewEnrollments:c("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:c("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:O("One plain-language sentence describing the run state, safe to show a user verbatim.")},Y3={...s1,properties:{migratedRecipientCount:_("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:_("Recipients completed because a deleted step had no surviving successor.")}},YM={appUrls:I("Dashboard URLs for relevant Sequenzy resources."),url:O("Primary dashboard URL for this result."),settingsUrl:O("Company settings URL when available.")},bM={success:JM,message:r1,note:ZQ,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:O("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:I("One returned item.")},value:I("Fallback object wrapper used only when a tool returns a non-object value.")},HM={get_account:{account:j("account"),companies:y("company"),apiKeyPermissions:I("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:O("Company ID selected by the authenticated API key, when available."),selectedCompanyId:O("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:O("Selected company ID."),companyName:O("Selected company name.")},get_app_urls:{dashboard:O("Company dashboard URL."),settings:O("Company settings URL."),campaign:O("Campaign editor URL."),landingPage:O("Landing page editor URL."),sequence:O("Sequence editor URL."),email:O("Email editor URL."),transactionalEmail:O("Transactional email URL."),emailSend:O("Sent email detail URL."),domain:O("Sending domain settings URL."),urls:I("All generated URLs keyed by resource type.")},create_company:{company:j("company"),autoSelected:c("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:j("company")},get_company:{company:j("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:I("One sync rule.")},isDefault:c("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:I("One sync rule.")},isDefault:c("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:I("Effective cart-abandonment settings (defaults applied)."),priceDrop:I("Effective price-drop settings (defaults applied)."),shopDomain:O("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings after the update."),cartAbandonment:I("Effective cart-abandonment settings after the update."),priceDrop:I("Effective price-drop settings after the update."),shopDomain:O("Connected Shopify store domain.")},create_api_key:{apiKey:I("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:O("Newly created API key if the API response uses the short key field.")},request_api_key_handoff:{handoff:I("The prepared handoff: `url` opens the dashboard create-key form prefilled with the requested `name`, `preset` or `scopes`, and `replaces` when rotating. `canSelfServe` is true when the active key already holds api_keys:manage and could create the key directly. `deliversKeyToCaller` is always false - the new key is shown in the owner's browser and never returned here."),message:O("What to tell the operator about this handoff."),nextSteps:{type:"array",description:"Ordered steps to finish the rotation, including verifying the replacement and revoking the predecessor.",items:O("One step in the handoff.")}},list_api_keys:{apiKeys:y("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:j("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:j("revoked non-secret API key metadata")},delete_api_key:{apiKey:j("deleted non-secret API key metadata")},list_websites:{websites:y("sending domain, including DNS verification and readyToSend sending readiness")},list_integrations:{integrations:y("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, allowlisted non-secret details, and lastSyncSkipped (records the last sync could not import normally: suppressed profiles that cannot receive email, plus any that were not imported). Credentials are never included")},get_integration:{integration:I("The connected integration: provider, display name, category, provider account ID, active and sync status, last sync time and error, and allowlisted non-secret details. Credentials are never included."),capabilities:w1("What this provider does: category, connect method, what it syncs, every event it emits with when it fires, attributes it writes, supported actions, availability, and caveats. Null for a provider with no catalog entry."),events:Z1("Each event the provider emits, every matching tag rule and its conditions, listening sequences, and account-wide observation fields. Use activity for integration-specific delivery."),unusedEvents:{type:"array",description:"Events the provider emits that no sequence triggers on. These are the concrete automation gaps for this integration.",items:O("Event name with no listening sequence.")},accountNeverReceivedEvents:{type:"array",description:"Provider event names this account has never received from any source. This is not integration-specific delivery evidence.",items:O("Event name never seen account-wide.")},activity:I("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),pixel:w1("Shopify only: live storefront pixel state (installed, endpoint, endpointCurrent, configurationCurrent, healthy, error, dependentEvents). Null for providers without a pixel. When error is null and healthy is false, every dependentEvent is confirmed dark; an error means Shopify could not confirm the state."),recommendations:Z1("Prioritized problems and suggestions, each with a code, severity (error, warning, info), message, and a concrete action."),availableActions:{type:"array",description:"Action ids callable on this integration right now, given its current state.",items:O("Available action id.")}},list_integration_capabilities:{providers:y("integration provider, including category, connect method, what it syncs, every event it emits with the moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats")},get_event_schema:{eventName:{type:["string","null"],description:"Normalized name of the event described, or null when listing every documented event."},events:{type:"array",description:"One entry per event. Listing mode returns summaries only; asking for a single eventName adds `providers`, each with an `examplePayload` and a `properties` array of { path, type, description?, mergeTag? }. `documented: false` means no reference sample is published - the event name is still valid to trigger and to build a sequence on.",items:I("An event: eventName, documented, label, category, description, documentedProviders, and (single-event mode) providers, mergeTagPrefix, and notes.")},note:ZQ},list_integration_activity:{activity:y("integration activity row, including provider, action, status, event type, matched contact, message, and error. Payloads are sanitized, so no credentials appear"),windowHours:{type:"number",description:"Retention window in hours for integration activity."},note:ZQ},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:O("URL to configure in the provider's webhook settings with the same secret. Always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:c("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:c("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog only: outcome of the optional history import request ({ requested, queued, error }). The webhook connection succeeds even if queueing the import failed."}},set_integration_sync_enabled:{integrationId:O("The integration that was updated."),provider:O("Provider of the updated integration."),syncEnabled:c("Sync state after the update."),changed:c("False when the integration was already in the requested state."),message:r1},get_integration_pixel:{integrationId:O("The Shopify integration inspected."),provider:O("Always `shopify`."),shopDomain:O("Store the pixel was read from."),pixel:I("Live pixel state: installed, id, endpoint it posts to, endpointCurrent (including the supported compatibility route), configurationCurrent (endpoint plus signed connection settings), healthy, and error when Shopify could not confirm."),dependentEvents:{type:"array",description:"Event names that depend on this pixel. They are confirmed unable to arrive only when pixel.error is null and pixel.healthy is false.",items:O("Pixel-dependent event name.")},message:r1},activate_integration_pixel:{integrationId:O("The Shopify integration updated."),provider:O("Always `shopify`."),shopDomain:O("Store the pixel was installed on."),pixel:I("Pixel state after activation."),changed:c("False when the pixel was already installed and reporting to this account."),created:c("True when a new pixel was installed."),updated:c("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:O("Pixel-dependent event name.")},message:r1},sync_integration:{integrationId:O("The integration being synced."),provider:O("Provider of the synced integration."),jobId:H0("Background job id for the queued sync, when one was created."),syncStatus:O("Sync status after queueing. Poll get_integration to watch it progress."),syncTarget:w1("For Supabase, the project ref, schema, and table the backfill reads. Absent for providers whose sync has no configurable source."),message:r1},list_sender_profiles:{senderProfiles:y("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether the address is fully ready to send"),replyProfiles:y("reply-to profile"),defaultSenderProfileId:H0("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:H0("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:j("renamed sender (From) profile, present when type was sender"),replyProfile:j("renamed reply-to profile, present when type was reply"),renamed:c("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:Z1("One entry per notification event with its current mode: off, instant, or daily. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:Z1("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},get_sending_status:{status:O("Company-level sending state: active, paused, or suspended. Anything other than active blocks every send, including test sends."),pauseReason:H0("Exact enforcement message, including the measured rate, the threshold it crossed, and the send volume it was measured over. Null when sending is active."),pauseReasonKind:H0("Machine-readable pause cause: high_hard_bounce_rate, high_soft_bounce_rate, high_complaint_rate, phishing_guard, manual, or other. Only high_hard_bounce_rate can be cleared with resume_sending."),pausedAt:H0("ISO timestamp when sending was paused. Null when sending is active."),selfResume:I("Whether the account can clear this pause itself: canSelfResume, supported, allowedByAdmin, ownerIsTrusted, the automated aiReviewStatus (not_required, pending, approved, flagged, failed) with its reason and timestamps, and unavailableReason naming the blocking gate (unsupported_reason, waiting_for_review, blocked_by_ai, review_failed, blocked_by_admin)."),senderHealth:w1("Enforcement counts and the thresholds that apply at this volume for hard bounces, soft bounces, and complaints. bounceScopedSent is the denominator for bounce rates, complaintScopedSent is the denominator for complaint rates, and scopedSent remains as a backward-compatible alias for bounceScopedSent. Also includes enforcementMode. Null when the account has no metrics record yet or sender-health analytics are temporarily unavailable; pause state and remediation remain authoritative."),metricsWindow:I("Proof that enforcement is not time-windowed: kind is always all_time_since_reset and expiresAt is always null. bounceResetAt and complaintResetAt are the watermarks the totals are counted from. Do not tell the user to wait for a window to expire - there is none."),remediation:I("Ordered steps for the current state, plus supportEmail, docsUrl, and the dashboard URL. Relay these verbatim instead of improvising recovery advice.")},resume_sending:{resumed:c("True when this call restored sending. False when sending was already active."),message:r1,status:O("Sending state after the request. active on success."),selfResume:I("Self-resume state after the request, including the automated review status and how many gates remain."),metricsWindow:I("Enforcement watermarks after the resume. bounceResetAt moves to now, so the paused rate is recalculated from later sends."),remediation:I("Steps to keep sending healthy after the resume, plus supportEmail and docsUrl.")},get_tracking_settings:{tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:I("Signup consent settings: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled)."),autoUtm:I("Automatic UTM tagging state and its configured parameters."),trackingDomain:w1("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration.")},update_tracking_settings:{message:r1,tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:I("Signup consent settings after the update: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email, which is provisioned automatically the first time double opt-in is enabled."),autoUtm:I("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:w1("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:j("sending domain with separate DNS verification and readyToSend sending readiness; readiness.reason explains a domain that cannot send yet"),ready:c("Whether the sender website is ready."),status:O("Current processing or verification status.")},verify_sending_domain:{website:j("Sending domain with current DNS verification, readyToSend sending readiness, SPF, DKIM, and MAIL FROM details. When readyToSend is false, readiness.reason carries why: activation runs after the DNS records are correct, so it can still be pending while dkim.status reads verified."),verified:c("Whether the sending domain passed the fresh DNS verification check. Correct DNS alone does not mean the domain can send yet."),readyToSend:c("Whether DNS and the selected home transport are both ready for sending."),message:O("Verification result summary.")},get_integration_guide:{guide:j("integration guide"),code:O("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:I("One setup step.")}},add_subscriber:{subscriber:j("subscriber")},create_subscriber_import:{import:j("subscriber import")},get_subscriber_import:{import:j("subscriber import")},update_subscriber:{subscriber:j("subscriber")},remove_subscriber:{subscriber:j("subscriber"),hardDeleted:c("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:j("subscriber")},list_subscriber_notes:{notes:y("subscriber note")},add_subscriber_note:{note:j("subscriber note")},delete_subscriber_note:{id:O("Deleted subscriber note ID."),deleted:c("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:j("subscriber"),event:j("recorded event with its name and whether the event definition was created"),sideEffectFailures:{type:"array",description:"Sync-rule or automation side effects that failed. The event itself is still recorded.",items:O("One failed side effect.")}},trigger_subscriber_events:{subscriber:j("subscriber"),events:y("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:O("One tag name.")},requested:_("Identifiers supplied in the request."),matched:_("Existing subscribers resolved."),updated:_("Subscribers whose tags actually changed."),unchanged:_("Subscribers that already carried every tag."),failed:_("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:y("per-subscriber failure (up to 50)"),triggeredAutomations:c("Whether tag_added sequences were allowed to enroll these contacts.")},bulk_remove_subscriber_tags:{tags:{type:"array",description:"Normalized tag names removed from every matched subscriber.",items:O("One tag name.")},requested:_("Identifiers supplied in the request."),matched:_("Existing subscribers resolved."),updated:_("Subscribers whose tags actually changed."),unchanged:_("Subscribers that did not carry any of the tags."),failed:_("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:y("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:y("subscriber"),pagination:I("Pagination metadata: page, limit, offset, total (null when the server skipped the count, which it does for attribute filters), totalPages, fetchedPages, hasMore, nextOffset, and nextCursor. When hasMore is true, repeat the call with cursor set to nextCursor, or with offset set to nextOffset when nextCursor is null."),returned:_("Number of subscribers returned."),truncated:c("Whether matches remain beyond the returned window. Same as pagination.hasMore.")},list_products:{products:y("product"),pagination:I("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:y("product"),created:_("Number of products created."),updated:_("Number of products updated.")},delete_product:{productId:O("Deleted product ID.")},attach_product_file:{product:j("product"),delivery:j("digital delivery file")},remove_product_file:{product:j("product")},upload_image_asset:{asset:j("hosted image asset"),imageBlock:I("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:j("product sync job"),jobId:O("Queued product sync job ID.")},list_tags:{tags:y("tag")},create_tag:{tag:j("tag")},update_tag:{tag:j("tag")},delete_tag:{tagId:O("Deleted tag ID.")},list_lists:{lists:y("list")},create_list:{list:j("list")},update_list:{list:j("list")},delete_list:{listId:O("Deleted list ID.")},add_subscribers_to_list:{list:j("list"),added:_("Number of subscribers added to the list."),skipped:_("Number of subscribers skipped.")},remove_subscribers_from_list:{list:j("list"),removed:_("Number of subscribers removed from the list."),skipped:_("Number of subscribers skipped.")},list_segments:{segments:y("segment")},create_segment:{segment:j("segment")},update_segment:{segment:j("segment")},delete_segment:{segmentId:O("Deleted segment ID.")},get_segment_count:{count:_("Number of subscribers matching the segment."),segmentId:O("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:y("audience sync")},list_ad_accounts:{adAccounts:y("ad account")},create_audience_sync:{audienceSync:j("audience sync")},update_audience_sync:{audienceSync:j("audience sync")},delete_audience_sync:{audienceSyncId:O("Deleted audience sync ID.")},sync_audience_now:{audienceSync:j("audience sync"),job:j("audience sync job"),jobId:O("Queued audience sync job ID.")},list_templates:{templates:y("email template"),pagination:I("Pagination metadata: limit, offset, count (this page), total (every email body) and hasMore. Page with offset when hasMore is true.")},get_template:{template:j("email template")},create_template:{template:j("email template")},update_template:{template:j("email template")},set_template_localization:{templateId:O("Localized template ID."),localization:j("template localization")},sync_template_localizations:{templateId:O("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:O("One queued locale code.")},queuedVariantCount:_("Number of localized variants queued for translation.")},delete_template:{templateId:O("Deleted template ID.")},list_email_components:{components:y("email component")},get_email_component:{component:j("email component")},get_default_email_component:{component:j("default email component for the slot")},set_default_email_component:{component:j("saved default email component")},create_email_component:{component:j("email component")},update_email_component:{component:j("email component")},delete_email_component:{id:O("Deleted email component ID.")},list_ab_tests:{abTests:y("A/B test")},get_ab_test:{abTest:j("A/B test")},get_ab_test_stats:{abTest:j("A/B test"),stats:j("A/B test statistics")},restart_ab_test:{abTest:j("A/B test")},update_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},update_ab_test:{abTest:j("A/B test")},create_ab_test:{abTest:j("A/B test")},add_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},delete_ab_test_variant:{abTest:j("A/B test"),variantId:O("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:O("Deleted A/B test ID.")},list_campaigns:{campaigns:y("campaign"),pagination:I("Campaign page window: `limit`, `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`. Keep calling with an advanced `offset` while `hasMore` is true to enumerate every campaign.")},get_campaign:{campaign:j("campaign")},get_campaign_audience:{campaignId:O("Campaign the audience was resolved for."),campaignName:O("Campaign name."),status:O("Campaign status."),audience:I("Resolved targeting: `type`, a plain-language `summary`, `isUnset` (true when scheduling would fall back to every active subscriber), resolved `lists` and `segments` with names and a `missing` flag, `filters`, `include`/`exclude` rules, and individual subscriber adjustments."),recipientCount:_("Number of subscribers matching the effective targeting right now."),targetLists:w1("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:j("email send, including copied-recipient identity and primary email send ID when applicable"),events:y("email delivery event")},list_email_sends:{emailSends:y("email send"),pagination:j("email send pagination"),retentionDays:_("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:j("recipient suppression status")},remove_recipient_suppression:{removed:c("Whether stale bounce suppression was removed."),removedLocalBounce:c("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:O("One AWS SES region.")},remainingSuppression:j("recipient suppression status after cleanup")},create_campaign:{campaign:j("campaign")},update_campaign:{campaign:j("campaign")},schedule_campaign:{campaign:j("campaign"),scheduledAt:O("Scheduled send timestamp.")},unschedule_campaign:{campaign:j("draft campaign")},share_campaign:{shareUrl:O("Public anonymized view-in-browser URL for the campaign."),shareToken:O("Capability token embedded in the URL."),created:c("False when an already-active link was returned instead of minted.")},unshare_campaign:{revoked:c("False when the campaign had no active public link.")},share_template:{shareUrl:O("Public anonymized view-in-browser URL for the email."),shareToken:O("Capability token embedded in the URL."),created:c("False when an already-active link was returned instead of minted.")},unshare_template:{revoked:c("False when the email had no active public link.")},send_test_email:{emailSendId:O("Durable test email delivery ID."),recipientEmail:O("Test email recipient.")},send_test_sms:{smsSendId:O("Created test SMS send ID."),toPhone:O("Normalized E.164 destination phone.")},update_sms_number_label:{number:j("updated SMS number (label + brandPrefix override)")},cancel_campaign:{campaign:j("campaign")},pause_campaign:{campaign:j("campaign")},resume_campaign:{campaign:j("campaign")},delete_campaign:{campaignId:O("Deleted campaign ID.")},duplicate_campaign:{campaign:j("duplicated campaign")},resend_campaign_to_non_openers:{campaign:j("non-opener resend draft campaign"),estimatedNonOpenerCount:_("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:y("saved form")},create_form:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},list_popups:{popups:y("saved popup")},get_popup:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},create_popup:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},update_popup:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},get_popup_embed:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets.")},duplicate_popup:{popup:j("popup copy, created as a draft")},delete_popup:{popupId:O("Deleted popup ID.")},list_landing_pages:{landingPages:y("landing page")},get_landing_page:{landingPage:j("landing page")},create_landing_page:{landingPage:j("landing page")},update_landing_page:{landingPage:j("landing page")},duplicate_landing_page:{landingPage:j("landing page")},delete_landing_page:{landingPageId:O("Deleted landing page ID.")},publish_landing_page:{landingPage:j("landing page")},unpublish_landing_page:{landingPage:j("landing page")},connect_landing_page_domain:{landingPage:j("landing page"),domain:O("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:j("landing page"),domain:O("Landing page domain.")},list_sequences:{sequences:wM,pagination:I("Sequence page window: `limit` (null when limit and offset were both omitted and every sequence was returned), `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`.")},get_sequence:{sequence:s1},list_sequence_enrollments:{sequenceId:O("Sequence ID these enrollments belong to."),sequenceName:O("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},enrollments:{type:"array",description:"Contact-level enrollments matching the filters, one row per enrollment token.",items:{type:"object",description:"One subscriber's enrollment in this sequence.",properties:{enrollmentId:O("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:O("Sequence ID."),subscriberId:O("Subscriber ID."),email:H0("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists, and is null when neither is known."),firstName:H0("Subscriber first name, or null when unset."),lastName:H0("Subscriber last name, or null when unset."),subscriberStatus:H0("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:O("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:O("Sequence node this enrollment is currently sitting on."),currentNodeType:O("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:O("Current sequence node label or email subject when available."),currentNodeMissing:c("Whether the current node no longer exists in the sequence graph."),enrollmentKey:O("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:O("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:H0("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:O("ISO 8601 timestamp of the last change to this enrollment. For a waiting enrollment this is when it arrived at its current node; the platform does not separately track node entry time."),failedReason:H0("Why this enrollment stopped, for status `failed`. Null for every other status and for failures recorded before this field existed. A reason repeated across enrollments on the same currentNodeId points at that step's configuration or content rather than at the contacts."),movedFromNodeId:H0("Step this enrollment was released from by move_sequence_enrollments, or null when it reached its current step on its own."),movedAt:H0("ISO 8601 timestamp of that release, or null when the enrollment was never moved."),moveReason:H0("Note recorded with that release, or null when none was given.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:I("Pagination metadata.")},send_sequence_test_email:{sequenceId:O("Sequence ID."),nodeId:O("Tested sequence email-step node ID."),results:Z1("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:s1,eventTrackingCode:O("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:I("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:O("One required event name.")}},update_sequence:{sequence:Y3},update_sequence_node:{sequence:j("sequence")},update_sequence_nodes:{sequence:j("sequence")},edit_sequence_graph:{sequence:Y3},insert_sequence_step:{sequence:j("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:O("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:O("Inserted email template ID.")},insertedEmailCount:_("Number of email steps inserted."),addedBranchNodeId:O("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:I("Created path node IDs keyed by branch ID, plus else, in path order. Directly wired paths have empty arrays. Use a path's last node ID as afterNodeId to insert a nested branch on that path.")},enable_sequence:{sequenceId:O("Sequence ID."),status:O("Stored lifecycle status after the change."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},disable_sequence:{sequenceId:O("Sequence ID."),status:O("Stored lifecycle status after the change."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},duplicate_sequence:{sequence:s1,nodes:y("sequence node"),edges:y("sequence edge")},archive_sequence:{sequence:s1},unarchive_sequence:{sequence:s1},list_sequence_goals:{goals:y("sequence goal")},create_sequence_goal:{goal:j("sequence goal")},update_sequence_goal:{goal:j("sequence goal")},delete_sequence_goal:{goalId:O("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:j("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:O("Sequence ID."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},resume_sequence_enrollments:{sequenceId:O("Sequence ID."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},enroll_subscribers_in_sequence:{sequence:j("sequence"),enrollments:y("sequence enrollment"),enrolled:_("Number of subscribers enrolled."),skipped:_("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:O("Sequence ID."),dryRun:c("Whether this call only reported matches instead of cancelling them."),target:I("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:_("Active/waiting enrollments matching the target when the request started."),cancelledCount:_("Enrollments cancelled by this call."),remainingCount:_("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:y("sequence enrollment sample (up to 50)"),hasMore:c("Whether more enrollments matched than the returned sample.")},move_sequence_enrollments:{sequenceId:O("Sequence ID."),dryRun:c("Whether this call only reported the batch instead of moving it."),fromNodeId:O("Step the enrollments were taken from."),targetNodeId:O("Step the enrollments were moved onto, resolved from the source step's next step when not supplied."),sort:O("Order the batch was selected in."),requestedLimit:_("limit as requested."),effectiveLimit:_("How many this call was allowed to move after the daily guardrail was applied."),matchedCount:_("Movable enrollments parked on fromNodeId when the request started."),movedCount:_("Enrollments moved by this call."),remainingCount:_("Movable enrollments still on fromNodeId. Repeat the same request while this is above zero."),skippedCount:_("Enrollments excluded because they are active, a worker is mid-step on them, or they are parked awaiting double opt-in. Only safely parked waiting tokens can be moved."),dailyLimit:w3("Applied daily guardrail, or null when none was requested."),movedInWindow:_("Moves onto targetNodeId already recorded in the rolling 24-hour window."),dailyRemaining:w3("How many more can be moved onto targetNodeId today, or null when no dailyLimit was requested."),enqueuedCount:_("Moved enrollments handed to the worker queue. Zero while the sequence is not running."),enqueueErrors:{type:"array",description:"Moved enrollments whose queue handoff failed. They stay active on the target step and are recovered by the stuck-enrollment sweeper.",items:I("One tokenId with its enqueue error.")},tagResult:w1("Tagging outcome for the moved contacts: tags, updated, unchanged, failed, failures. Null when no tags were requested."),enrollments:y("moved (or, on a dry run, would-move) sequence enrollment sample (up to 50)"),hasMore:c("Whether more enrollments matched than the returned sample.")},realign_sequence_enrollments:{sequenceId:O("Sequence ID."),dryRun:c("Whether this call only previewed the new wait times instead of writing them."),sendingWindow:w1("The sequence sending window realignment anchored on (timezone, startTime, endTime, days), or null when only per-step weekday gates applied."),scannedCount:_("Waiting enrollments inspected by this call."),realignedCount:_("Waiting enrollments moved earlier (or that would move, on a dry run)."),unchangedCount:_("Waiting enrollments left exactly as they were."),unchangedReasons:I("Counts per reason an enrollment did not move: already_at_window_start, already_due, day_not_allowed, no_shared_opening, no_window, not_email_bound, send_retry, raced."),requeueFailedCount:_("Enrollments whose new wait time was stored but whose wake-up could not be re-queued. The stuck-enrollment sweeper recovers these within a few minutes."),changes:y("realigned enrollment sample (up to 50) with waitUntil, newWaitUntil, and movedEarlierMinutes"),hasMore:c("Whether a per-call cap stopped the scan early. Continue with nextCursor while this is true."),nextCursor:O("Opaque continuation cursor to pass as cursor on the next call when hasMore is true."),status:O("For an applied request, queued while the background job is pending."),jobId:O("Background job ID to pass to get_sequence_enrollment_realignment.")},get_sequence_enrollment_realignment:{sequenceId:O("Sequence ID."),dryRun:c("Always false for an applied job."),status:O("queued, running, completed, or failed."),jobId:O("Background realignment job ID."),result:w1("Completed realignment result, including counts, changes, hasMore, and nextCursor; null until completion."),error:H0("Safe recovery guidance when the job failed, otherwise null.")},delete_sequence:{sequenceId:O("Deleted sequence ID.")},list_transactional_emails:{transactional:y("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:j("transactional email")},create_transactional_email:{transactional:j("transactional email")},update_transactional_email:{transactional:j("transactional email")},delete_transactional_email:{deleted:I("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:O("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:j("transactional email")},get_stats:{stats:I(`Account-wide delivery funnel for the requested window. ${f1}`),emailType:O("Applied structural email type filter when one was requested."),commerceForecast:j("Optional background-computed commerce AOV, 12-month customer value, and 90-day revenue forecast. Omitted when no snapshot is available; insufficient_data is returned only after eligibility was evaluated successfully.")},get_campaign_stats:{campaign:j("campaign"),stats:I(`Delivery funnel for this campaign. ${f1}`),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:I("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. Multi-select polls set allowMultiple: true, count each subscriber once per selected option (answer percentages can sum past 100), and report totalResponses as the respondent count. To read the exact historical respondents with their answers and response times, call list_poll_responses with this campaignId (and the summary blockId to scope it). To build a reusable audience from one answer, use the summary blockId and this campaignId with create_segment. ${y1} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response (a value list for multi-select polls) and may be overwritten by a later poll that reuses the key.`,items:I("One poll or NPS results summary.")},recommendations:I("Product recommendation funnel: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts (per-product impressions/clicks). Orders count when a subscriber buys a recommended product within 7 days of clicking it. Present only when the campaign rendered product recommendation blocks.")},list_poll_responses:{campaignId:O("Campaign the responses belong to."),blockId:O("Poll block the results were scoped to. Present only when blockId was requested."),responses:{type:"array",description:"Individual responses, newest answer first. Each entry has subscriberId, email, externalId, firstName, lastName, blockId, variant (options or nps), question, attributeKey (the subscriber attribute the answer was stored under), allowMultiple, answers (selected option labels), values (their stored values), and respondedAt. Only each subscriber's latest answer per block appears. email is null when the subscriber has since been deleted.",items:I("One respondent's latest answer.")},pagination:I("Pagination metadata: page, limit, total (response rows across every page; one row per subscriber per poll block), and totalPages. Keep paging while page < totalPages.")},get_transactional_stats:{transactional:j("transactional email"),stats:I(`Delivery funnel for this transactional email. ${f1}`),complaints:j("complaint count and rate for the selected transactional email"),clickedLinks:y("clicked link with click count and percentage share"),bounceBreakdown:j("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:j("human and machine open and click counts")},get_sequence_stats:{sequence:s1,stats:I(`Delivery funnel across every email step in this sequence. ${f1}`),steps:{type:"array",description:`Per-step delivery funnel: one entry per email step of the sequence, in graph order, each with its own sent/delivered/opened/clicked counts. Read this to answer "how many of step N went out" - do not recount list_sequence_events. Counts come from the retained event stream, so they are not limited to the 14-day list_email_sends history. ${f1}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:_("1-based position of this email step in graph order. Step 4 is the fourth email a contact receives on the traversed path; on a branching graph, positions are assigned by traversal, so cross-check nodeId when a sequence forks."),nodeId:O("Automation node ID of this email step. Pass it to list_sequence_events or list_email_sends as automationNodeId to reach the individual recipients behind these counts, and it is the emailId that list_email_metrics reports for sequence emails."),subject:H0("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:I(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${f1}`),failedCount:_("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:Z1("Up to 20 of the failed contacts on this step, as { subscriberId, email, failedAt, failedReason }.")},required:["step","nodeId","stats"],additionalProperties:!0}},enrollmentCounts:{type:"object",description:"Live enrollment-token counts for this sequence. Includes only active and waiting enrollments and is always a current snapshot, independent of historical period/start/end filters.",properties:{active:_("Active enrollment count."),waiting:_("Waiting enrollment count."),total:_("Total active plus waiting enrollment count."),byCurrentNode:{type:"array",description:"Live active and waiting enrollment counts grouped by the token's current sequence node.",items:{type:"object",description:"Enrollment counts for one current sequence node.",properties:{currentNodeId:O("Current sequence node ID."),currentNodeType:O("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:O("Current sequence node label or email subject when available."),currentNodeMissing:c("Whether the current node no longer exists in the sequence graph."),active:_("Active enrollment count at this node."),waiting:_("Waiting enrollment count at this node."),total:_("Total active plus waiting enrollment count at this node.")},required:["currentNodeId","currentNodeMissing","active","waiting","total"],additionalProperties:!1}}},required:["active","waiting","total","byCurrentNode"],additionalProperties:!1},enrollmentSkipped:{type:"object",description:"Trigger matches where an unsubscribed or bounced contact could not be enrolled, including the total count and counts grouped by reason. Uses the requested period or start/end range; without an explicit range, this field defaults to the last 30 days.",properties:{count:_("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:_("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:I("Product recommendation funnel aggregated across the sequence's email nodes: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts. Present only when the sequence rendered product recommendation blocks.")},list_campaign_events:{events:y("campaign email event"),pagination:I("Pagination metadata.")},list_sequence_events:{events:y("sequence email event"),pagination:I("Pagination metadata.")},list_email_metrics:{emails:{type:"array",description:"One entry per email in scope: each campaign and each sequence email step, sorted by the requested sort/order.",items:{type:"object",description:"Metrics for one campaign or one sequence email step.",properties:{emailType:{type:"string",enum:["campaign","sequence"],description:"Whether this row is a campaign or a sequence email."},emailId:O("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:O("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:H0("Campaign ID, or null for sequence emails."),sequenceId:H0("Sequence ID, or null for campaigns."),sequenceName:H0("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:H0("Automation node ID of this step, or null for campaigns. Pass it as automationNodeId to list_sequence_events or list_email_sends to reach the recipients behind these counts."),step:{type:["number","null"],description:"1-based position of this email in its sequence, counted in graph order, or null for campaigns. Matches the step number in get_sequence_stats steps[]."},stats:I(`Delivery funnel for this email alone. ${f1}`),conversions:_("Attributed conversions credited to this email."),revenueCents:_("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:I(`Summed funnel across every email matching the filters, not just the returned page, plus \`emails\` (the number of matching emails), \`conversions\`, and \`revenueCents\`. Read totals.sent for "how many of this step went out in total". ${f1}`),pagination:I("Pagination metadata."),sort:O("Sort field the response was ordered by."),order:O("Sort order the response was ordered by."),step:_("Echo of the step filter, present only when one was requested."),sequenceIds:{type:"array",description:"Echo of the sequence IDs the breakdown was scoped to, present only when scoped.",items:O("Sequence ID.")}},get_subscriber_activity:{activity:y("subscriber activity event"),subscribers:y("subscriber"),pagination:I("Pagination metadata.")},list_team_members:{members:y("team member"),invitations:y("team invitation")},invite_team_member:{invitation:j("team invitation")},cancel_team_invitation:{invitationId:O("Cancelled invitation ID.")},list_conversations:{conversations:y("inbox conversation"),pagination:I("Pagination metadata.")},get_conversation:{conversation:j("inbox conversation"),messages:y("conversation message")},reply_to_conversation:{conversation:j("inbox conversation"),message:j("conversation message")},update_conversation_status:{conversation:j("inbox conversation")},mark_conversation_read:{conversation:j("inbox conversation")},list_webhooks:{webhooks:y("outbound webhook")},create_webhook:{webhook:j("outbound webhook")},update_webhook:{webhook:j("outbound webhook")},delete_webhook:{webhookId:O("Deleted outbound webhook ID.")},test_webhook:{webhook:j("outbound webhook"),delivery:j("test webhook delivery")},list_webhook_deliveries:{deliveries:y("webhook delivery")},replay_webhook_delivery:{delivery:j("webhook delivery"),job:j("webhook replay job")},generate_email:{email:j("generated email"),html:O("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:I("One generated email block.")},subject:O("Generated subject line."),previewText:O("Generated inbox preview text.")},generate_sequence:{sequence:j("persisted AI-generated sequence draft"),deprecated:c("Always true for this deprecated alias."),deprecationMessage:O("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:O("One generated subject line.")},variants:y("generated subject line variant")},generate_sms:{prompt:O("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:I("One generated SMS message.")}},get_sms_settings:{sms:I("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix (account-wide default), numbers (each with id, e164, label tag, brandPrefix override, status), readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:O("Email-safe HTML document, rendered exactly as it would be sent."),subject:O("Subject line with merge tags resolved."),previewText:H0("Inbox preview text with merge tags resolved, or null when unset."),locale:O("Localization locale the render resolved to."),personalized:c("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:c("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:Z1(`Merge tags that rendered as an empty string, as [{ tag, reason }]. reason "unknown" means nothing provides that name, so it stays empty for every recipient - usually a typo or a tag copied from another platform. reason "no_value" means the name is recognized, or could not be checked, but is blank for this contact. A name is only called unknown when the render had a source to check it against. Without the contact's attributes nothing is checkable, since a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass a stored subscriberId or an inline subscriber carrying customAttributes. Beyond that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event; {{recommendedProducts.*}} needs a stored subscriberId the catalog has something to recommend for; and {{discount.*}} is only checkable on a sequence step whose incoming paths all run the same discount step, never on a standalone template. Rendering a transactional email is checkable only when variables is passed, because its tags come from the variables of each send call and carry no prefix marking them. Otherwise those tags land in no_value rather than in unknown. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope; a key without it may report such a name as unknown. An empty array means every tag in the email resolved.`),entity:I("Which entity was rendered: type, id, and variantId.")}};function zM($){let W=HM[$];if(W===void 0)throw Error(`MCP tool "${$}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${$}\` MCP tool.`,properties:{...bM,...W,...AQ.has($)?YM:{}},additionalProperties:!0}}function H3($){return{...$,outputSchema:zM($.name)}}function z3($){if(h($))return $;if(Array.isArray($))return{items:$};return{value:$}}var D3=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:h0},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update an A/B test variant. Campaign variants are editable only in draft. Sequence variants can be edited after activity with confirmLiveChange, but earlier sends stay unchanged and combined results may no longer be accurate. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:`Replacement HTML body. Mutually exclusive with blocks. ${U0}`},blocks:{type:"array",description:`${O1}${d1} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the sequence is active, the test is no longer a draft, or it has recorded activity. The edit affects future sends and can make combined results inaccurate."}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test",description:"Update A/B test settings. Campaign tests use testPercentage, testDurationMinutes, and winnerCriteria. Sequence tests use testType, winnerThreshold, and winnerCriteria; changing live or already-used sequence settings requires confirmLiveChange. Provide at least one setting.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50."},testDurationMinutes:{type:"number",description:"Campaign-only test duration in minutes, from 15 to 1440."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Applies to both campaign and sequence tests."},testType:{type:"string",enum:["subject","content"],description:"Sequence-only variant strategy. When winnerCriteria is omitted, subject defaults to open_rate and content defaults to click_rate."},winnerThreshold:{type:"number",description:"Sequence-only number of recipients before selecting a winner, from 10 to 1000."},confirmLiveChange:{type:"boolean",description:"Required as true when sequence settings affect an active test or a test with recorded activity."}},required:["abTestId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test or convert a sequence email node into a typed A/B test node. Provide exactly one of campaignId or automationNodeId. Control variant A is created automatically from the current email. Campaign tests may add variants later; automationNodeId conversions require at least one variants[] entry to compete with control variant A.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID. Mutually exclusive with automationNodeId."},automationNodeId:{type:"string",description:"Sequence email-node ID to convert to action_ab_test. Mutually exclusive with campaignId."},confirmLiveChange:{type:"boolean",description:"Required as true when converting an email node in an active sequence."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50. Defaults to 20. Sequence tests use winnerThreshold instead."},testDurationMinutes:{type:"number",description:"Campaign-only test phase duration in minutes, from 15 to 1440. Defaults to 240. Sequence tests select after winnerThreshold recipients instead."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Campaign tests default to open_rate. For sequence tests, an explicit value overrides the testType default."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test variant strategy. Subject defaults to open_rate and content defaults to click_rate unless winnerCriteria is explicit. Defaults to content."},winnerThreshold:{type:"number",description:"Sequence test sample size from 10 to 1000. Defaults to 100."},variants:{type:"array",maxItems:4,description:"Extra variants to create in addition to control variant A. Optional for campaign tests; automationNodeId conversions require at least one entry.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${O1}${d1}`,items:{type:"object"}}},required:["subject"]}}}}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign or sequence A/B test. Sequence variants receive their own editable email template. Variants cannot be added after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${O1}${d1}`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because new variants immediately enter the live rotation."}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign or sequence A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because deletion immediately changes the live rotation."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var F3=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. IMPORTANT: If you have access to multiple companies, you MUST either:
|
|
29
|
+
`)}B.write("payload.value = newResult;"),B.write("return payload;");let S=B.compile();return(C,v)=>S(U,C,v)},J,w=u1,Y=!_4.jitless,H=Y&&N$.value,z=W.catchall,F;$._zod.parse=(U,B)=>{F??(F=X.value);let K=U.value;if(!w(K))return U.issues.push({expected:"object",code:"invalid_type",input:K,inst:$}),U;if(Y&&H&&B?.async===!1&&B.jitless!==!0){if(!J)J=G(W.shape);if(U=J(U,B),!z)return U;return _G([],K,U,B,F,$)}return Q(U,B)}});function rX($,W,Q,X){for(let J of $)if(J.issues.length===0)return W.value=J.value,W;let G=$.filter((J)=>!N1(J));if(G.length===1)return W.value=G[0].value,G[0];return W.issues.push({code:"invalid_union",input:W.value,inst:Q,errors:$.map((J)=>J.issues.map((w)=>n0(w,X,f0())))}),W}var f$=V("$ZodUnion",($,W)=>{$0.init($,W),s($._zod,"optin",()=>W.options.some((G)=>G._zod.optin==="optional")?"optional":void 0),s($._zod,"optout",()=>W.options.some((G)=>G._zod.optout==="optional")?"optional":void 0),s($._zod,"values",()=>{if(W.options.every((G)=>G._zod.values))return new Set(W.options.flatMap((G)=>Array.from(G._zod.values)));return}),s($._zod,"pattern",()=>{if(W.options.every((G)=>G._zod.pattern)){let G=W.options.map((J)=>J._zod.pattern);return new RegExp(`^(${G.map((J)=>_6(J.source)).join("|")})$`)}return});let Q=W.options.length===1,X=W.options[0]._zod.run;$._zod.parse=(G,J)=>{if(Q)return X(G,J);let w=!1,Y=[];for(let b of W.options){let H=b._zod.run({value:G.value,issues:[]},J);if(H instanceof Promise)Y.push(H),w=!0;else{if(H.issues.length===0)return H;Y.push(H)}}if(!w)return rX(Y,G,$,J);return Promise.all(Y).then((b)=>{return rX(b,G,$,J)})}}),hG=V("$ZodDiscriminatedUnion",($,W)=>{f$.init($,W);let Q=$._zod.parse;s($._zod,"propValues",()=>{let G={};for(let J of W.options){let w=J._zod.propValues;if(!w||Object.keys(w).length===0)throw Error(`Invalid discriminated union option at index "${W.options.indexOf(J)}"`);for(let[Y,b]of Object.entries(w)){if(!G[Y])G[Y]=new Set;for(let H of b)G[Y].add(H)}}return G});let X=$6(()=>{let G=W.options,J=new Map;for(let w of G){let Y=w._zod.propValues?.[W.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${W.options.indexOf(w)}"`);for(let b of Y){if(J.has(b))throw Error(`Duplicate discriminator value "${String(b)}"`);J.set(b,w)}}return J});$._zod.parse=(G,J)=>{let w=G.value;if(!u1(w))return G.issues.push({code:"invalid_type",expected:"object",input:w,inst:$}),G;let Y=X.value.get(w?.[W.discriminator]);if(Y)return Y._zod.run(G,J);if(W.unionFallback)return Q(G,J);return G.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:W.discriminator,input:w,path:[W.discriminator],inst:$}),G}}),yG=V("$ZodIntersection",($,W)=>{$0.init($,W),$._zod.parse=(Q,X)=>{let G=Q.value,J=W.left._zod.run({value:G,issues:[]},X),w=W.right._zod.run({value:G,issues:[]},X);if(J instanceof Promise||w instanceof Promise)return Promise.all([J,w]).then(([b,H])=>{return sX(Q,b,H)});return sX(Q,J,w)}});function h$($,W){if($===W)return{valid:!0,data:$};if($ instanceof Date&&W instanceof Date&&+$===+W)return{valid:!0,data:$};if(I1($)&&I1(W)){let Q=Object.keys(W),X=Object.keys($).filter((J)=>Q.indexOf(J)!==-1),G={...$,...W};for(let J of X){let w=h$($[J],W[J]);if(!w.valid)return{valid:!1,mergeErrorPath:[J,...w.mergeErrorPath]};G[J]=w.data}return{valid:!0,data:G}}if(Array.isArray($)&&Array.isArray(W)){if($.length!==W.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let X=0;X<$.length;X++){let G=$[X],J=W[X],w=h$(G,J);if(!w.valid)return{valid:!1,mergeErrorPath:[X,...w.mergeErrorPath]};Q.push(w.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function sX($,W,Q){if(W.issues.length)$.issues.push(...W.issues);if(Q.issues.length)$.issues.push(...Q.issues);if(N1($))return $;let X=h$(W.value,Q.value);if(!X.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(X.mergeErrorPath)}`);return $.value=X.data,$}var fG=V("$ZodRecord",($,W)=>{$0.init($,W),$._zod.parse=(Q,X)=>{let G=Q.value;if(!I1(G))return Q.issues.push({expected:"record",code:"invalid_type",input:G,inst:$}),Q;let J=[];if(W.keyType._zod.values){let w=W.keyType._zod.values;Q.value={};for(let b of w)if(typeof b==="string"||typeof b==="number"||typeof b==="symbol"){let H=W.valueType._zod.run({value:G[b],issues:[]},X);if(H instanceof Promise)J.push(H.then((z)=>{if(z.issues.length)Q.issues.push(...H1(b,z.issues));Q.value[b]=z.value}));else{if(H.issues.length)Q.issues.push(...H1(b,H.issues));Q.value[b]=H.value}}let Y;for(let b in G)if(!w.has(b))Y=Y??[],Y.push(b);if(Y&&Y.length>0)Q.issues.push({code:"unrecognized_keys",input:G,inst:$,keys:Y})}else{Q.value={};for(let w of Reflect.ownKeys(G)){if(w==="__proto__")continue;let Y=W.keyType._zod.run({value:w,issues:[]},X);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){Q.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((H)=>n0(H,X,f0())),input:w,path:[w],inst:$}),Q.value[Y.value]=Y.value;continue}let b=W.valueType._zod.run({value:G[w],issues:[]},X);if(b instanceof Promise)J.push(b.then((H)=>{if(H.issues.length)Q.issues.push(...H1(w,H.issues));Q.value[Y.value]=H.value}));else{if(b.issues.length)Q.issues.push(...H1(w,b.issues));Q.value[Y.value]=b.value}}}if(J.length)return Promise.all(J).then(()=>Q);return Q}});var uG=V("$ZodEnum",($,W)=>{$0.init($,W);let Q=q$(W.entries),X=new Set(Q);$._zod.values=X,$._zod.pattern=new RegExp(`^(${Q.filter((G)=>E$.has(typeof G)).map((G)=>typeof G==="string"?b1(G):G.toString()).join("|")})$`),$._zod.parse=(G,J)=>{let w=G.value;if(X.has(w))return G;return G.issues.push({code:"invalid_value",values:Q,input:w,inst:$}),G}}),cG=V("$ZodLiteral",($,W)=>{if($0.init($,W),W.values.length===0)throw Error("Cannot create literal schema with no valid values");$._zod.values=new Set(W.values),$._zod.pattern=new RegExp(`^(${W.values.map((Q)=>typeof Q==="string"?b1(Q):Q?b1(Q.toString()):String(Q)).join("|")})$`),$._zod.parse=(Q,X)=>{let G=Q.value;if($._zod.values.has(G))return Q;return Q.issues.push({code:"invalid_value",values:W.values,input:G,inst:$}),Q}});var mG=V("$ZodTransform",($,W)=>{$0.init($,W),$._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new C6($.constructor.name);let G=W.transform(Q.value,Q);if(X.async)return(G instanceof Promise?G:Promise.resolve(G)).then((w)=>{return Q.value=w,Q});if(G instanceof Promise)throw new Y1;return Q.value=G,Q}});function aX($,W){if($.issues.length&&W===void 0)return{issues:[],value:void 0};return $}var lG=V("$ZodOptional",($,W)=>{$0.init($,W),$._zod.optin="optional",$._zod.optout="optional",s($._zod,"values",()=>{return W.innerType._zod.values?new Set([...W.innerType._zod.values,void 0]):void 0}),s($._zod,"pattern",()=>{let Q=W.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)})?$`):void 0}),$._zod.parse=(Q,X)=>{if(W.innerType._zod.optin==="optional"){let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>aX(J,Q.value));return aX(G,Q.value)}if(Q.value===void 0)return Q;return W.innerType._zod.run(Q,X)}}),gG=V("$ZodNullable",($,W)=>{$0.init($,W),s($._zod,"optin",()=>W.innerType._zod.optin),s($._zod,"optout",()=>W.innerType._zod.optout),s($._zod,"pattern",()=>{let Q=W.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)}|null)$`):void 0}),s($._zod,"values",()=>{return W.innerType._zod.values?new Set([...W.innerType._zod.values,null]):void 0}),$._zod.parse=(Q,X)=>{if(Q.value===null)return Q;return W.innerType._zod.run(Q,X)}}),pG=V("$ZodDefault",($,W)=>{$0.init($,W),$._zod.optin="optional",s($._zod,"values",()=>W.innerType._zod.values),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);if(Q.value===void 0)return Q.value=W.defaultValue,Q;let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>eX(J,W));return eX(G,W)}});function eX($,W){if($.value===void 0)$.value=W.defaultValue;return $}var iG=V("$ZodPrefault",($,W)=>{$0.init($,W),$._zod.optin="optional",s($._zod,"values",()=>W.innerType._zod.values),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);if(Q.value===void 0)Q.value=W.defaultValue;return W.innerType._zod.run(Q,X)}}),nG=V("$ZodNonOptional",($,W)=>{$0.init($,W),s($._zod,"values",()=>{let Q=W.innerType._zod.values;return Q?new Set([...Q].filter((X)=>X!==void 0)):void 0}),$._zod.parse=(Q,X)=>{let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>$G(J,$));return $G(G,$)}});function $G($,W){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:W});return $}var dG=V("$ZodCatch",($,W)=>{$0.init($,W),s($._zod,"optin",()=>W.innerType._zod.optin),s($._zod,"optout",()=>W.innerType._zod.optout),s($._zod,"values",()=>W.innerType._zod.values),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>{if(Q.value=J.value,J.issues.length)Q.value=W.catchValue({...Q,error:{issues:J.issues.map((w)=>n0(w,X,f0()))},input:Q.value}),Q.issues=[];return Q});if(Q.value=G.value,G.issues.length)Q.value=W.catchValue({...Q,error:{issues:G.issues.map((J)=>n0(J,X,f0()))},input:Q.value}),Q.issues=[];return Q}});var oG=V("$ZodPipe",($,W)=>{$0.init($,W),s($._zod,"values",()=>W.in._zod.values),s($._zod,"optin",()=>W.in._zod.optin),s($._zod,"optout",()=>W.out._zod.optout),s($._zod,"propValues",()=>W.in._zod.propValues),$._zod.parse=(Q,X)=>{if(X.direction==="backward"){let J=W.out._zod.run(Q,X);if(J instanceof Promise)return J.then((w)=>p4(w,W.in,X));return p4(J,W.in,X)}let G=W.in._zod.run(Q,X);if(G instanceof Promise)return G.then((J)=>p4(J,W.out,X));return p4(G,W.out,X)}});function p4($,W,Q){if($.issues.length)return $.aborted=!0,$;return W._zod.run({value:$.value,issues:$.issues},Q)}var tG=V("$ZodReadonly",($,W)=>{$0.init($,W),s($._zod,"propValues",()=>W.innerType._zod.propValues),s($._zod,"values",()=>W.innerType._zod.values),s($._zod,"optin",()=>W.innerType._zod.optin),s($._zod,"optout",()=>W.innerType._zod.optout),$._zod.parse=(Q,X)=>{if(X.direction==="backward")return W.innerType._zod.run(Q,X);let G=W.innerType._zod.run(Q,X);if(G instanceof Promise)return G.then(WG);return WG(G)}});function WG($){return $.value=Object.freeze($.value),$}var rG=V("$ZodCustom",($,W)=>{L0.init($,W),$0.init($,W),$._zod.parse=(Q,X)=>{return Q},$._zod.check=(Q)=>{let X=Q.value,G=W.fn(X);if(G instanceof Promise)return G.then((J)=>QG(J,Q,X,$));QG(G,Q,X,$);return}});function QG($,W,Q,X){if(!$){let G={code:"custom",input:Q,inst:X,path:[...X._zod.def.path??[]],continue:!X._zod.def.abort};if(X._zod.def.params)G.params=X._zod.def.params;W.issues.push(W6(G))}}var DD=($)=>{let W=typeof $;switch(W){case"number":return Number.isNaN($)?"NaN":"number";case"object":{if(Array.isArray($))return"array";if($===null)return"null";if(Object.getPrototypeOf($)!==Object.prototype&&$.constructor)return $.constructor.name}}return W},FD=()=>{let $={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 W(X){return $[X]??null}let Q={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(X)=>{switch(X.code){case"invalid_type":return`Invalid input: expected ${X.expected}, received ${DD(X.input)}`;case"invalid_value":if(X.values.length===1)return`Invalid input: expected ${f4(X.values[0])}`;return`Invalid option: expected one of ${x4(X.values,"|")}`;case"too_big":{let G=X.inclusive?"<=":"<",J=W(X.origin);if(J)return`Too big: expected ${X.origin??"value"} to have ${G}${X.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${X.origin??"value"} to be ${G}${X.maximum.toString()}`}case"too_small":{let G=X.inclusive?">=":">",J=W(X.origin);if(J)return`Too small: expected ${X.origin} to have ${G}${X.minimum.toString()} ${J.unit}`;return`Too small: expected ${X.origin} to be ${G}${X.minimum.toString()}`}case"invalid_format":{let G=X;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 ${Q[G.format]??X.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${X.divisor}`;case"unrecognized_keys":return`Unrecognized key${X.keys.length>1?"s":""}: ${x4(X.keys,", ")}`;case"invalid_key":return`Invalid key in ${X.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${X.origin}`;default:return"Invalid input"}}};function u$(){return{localeError:FD()}}var gM=Symbol("ZodOutput"),pM=Symbol("ZodInput");class sG{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...W){let Q=W[0];if(this._map.set($,Q),Q&&typeof Q==="object"&&"id"in Q){if(this._idmap.has(Q.id))throw Error(`ID ${Q.id} already exists in the registry`);this._idmap.set(Q.id,$)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let W=this._map.get($);if(W&&typeof W==="object"&&"id"in W)this._idmap.delete(W.id);return this._map.delete($),this}get($){let W=$._zod.parent;if(W){let Q={...this.get(W)??{}};delete Q.id;let X={...Q,...this._map.get($)};return Object.keys(X).length?X:void 0}return this._map.get($)}has($){return this._map.has($)}}function UD(){return new sG}var c6=UD();function aG($,W){return new $({type:"string",...x(W)})}function eG($,W){return new $({type:"string",format:"email",check:"string_format",abort:!1,...x(W)})}function c$($,W){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...x(W)})}function $J($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...x(W)})}function WJ($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...x(W)})}function QJ($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...x(W)})}function XJ($,W){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...x(W)})}function GJ($,W){return new $({type:"string",format:"url",check:"string_format",abort:!1,...x(W)})}function JJ($,W){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...x(W)})}function wJ($,W){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...x(W)})}function YJ($,W){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...x(W)})}function bJ($,W){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...x(W)})}function HJ($,W){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...x(W)})}function zJ($,W){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...x(W)})}function DJ($,W){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...x(W)})}function FJ($,W){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...x(W)})}function UJ($,W){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...x(W)})}function BJ($,W){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...x(W)})}function LJ($,W){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...x(W)})}function AJ($,W){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...x(W)})}function OJ($,W){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...x(W)})}function KJ($,W){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...x(W)})}function ZJ($,W){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...x(W)})}function PJ($,W){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...x(W)})}function VJ($,W){return new $({type:"string",format:"date",check:"string_format",...x(W)})}function jJ($,W){return new $({type:"string",format:"time",check:"string_format",precision:null,...x(W)})}function MJ($,W){return new $({type:"string",format:"duration",check:"string_format",...x(W)})}function qJ($,W){return new $({type:"number",checks:[],...x(W)})}function IJ($,W){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...x(W)})}function NJ($,W){return new $({type:"boolean",...x(W)})}function EJ($,W){return new $({type:"null",...x(W)})}function TJ($){return new $({type:"unknown"})}function RJ($,W){return new $({type:"never",...x(W)})}function d4($,W){return new v$({check:"less_than",...x(W),value:$,inclusive:!1})}function m6($,W){return new v$({check:"less_than",...x(W),value:$,inclusive:!0})}function o4($,W){return new _$({check:"greater_than",...x(W),value:$,inclusive:!1})}function l6($,W){return new _$({check:"greater_than",...x(W),value:$,inclusive:!0})}function t4($,W){return new xX({check:"multiple_of",...x(W),value:$})}function r4($,W){return new yX({check:"max_length",...x(W),maximum:$})}function Q6($,W){return new fX({check:"min_length",...x(W),minimum:$})}function s4($,W){return new uX({check:"length_equals",...x(W),length:$})}function m$($,W){return new cX({check:"string_format",format:"regex",...x(W),pattern:$})}function l$($){return new mX({check:"string_format",format:"lowercase",...x($)})}function g$($){return new lX({check:"string_format",format:"uppercase",...x($)})}function p$($,W){return new gX({check:"string_format",format:"includes",...x(W),includes:$})}function i$($,W){return new pX({check:"string_format",format:"starts_with",...x(W),prefix:$})}function n$($,W){return new iX({check:"string_format",format:"ends_with",...x(W),suffix:$})}function c1($){return new nX({check:"overwrite",tx:$})}function d$($){return c1((W)=>W.normalize($))}function o$(){return c1(($)=>$.trim())}function t$(){return c1(($)=>$.toLowerCase())}function r$(){return c1(($)=>$.toUpperCase())}function SJ($,W,Q){return new $({type:"array",element:W,...x(Q)})}function CJ($,W,Q){let X=x(Q);return X.abort??(X.abort=!0),new $({type:"custom",check:"custom",fn:W,...X})}function kJ($,W,Q){return new $({type:"custom",check:"custom",fn:W,...x(Q)})}function vJ($){let W=BD((Q)=>{return Q.addIssue=(X)=>{if(typeof X==="string")Q.issues.push(W6(X,Q.value,W._zod.def));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=Q.value),G.inst??(G.inst=W),G.continue??(G.continue=!W._zod.def.abort),Q.issues.push(W6(G))}},$(Q.value,Q)});return W}function BD($,W){let Q=new L0({check:"custom",...x(W)});return Q._zod.check=$,Q}function X6($){return!!$._zod}function E1($,W){if(X6($))return y6($,W);return $.safeParse(W)}function a4($){if(!$)return;let W;if(X6($))W=$._zod?.def?.shape;else W=$.shape;if(!W)return;if(typeof W==="function")try{return W()}catch{return}return W}function _J($){if(X6($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let Q=$._def;if(Q){if(Q.value!==void 0)return Q.value;if(Array.isArray(Q.values)&&Q.values.length>0)return Q.values[0]}let X=$.value;if(X!==void 0)return X;return}var p6={};SQ(p6,{time:()=>e$,duration:()=>$8,datetime:()=>s$,date:()=>a$,ZodISOTime:()=>yJ,ZodISODuration:()=>fJ,ZodISODateTime:()=>xJ,ZodISODate:()=>hJ});var xJ=V("ZodISODateTime",($,W)=>{BG.init($,W),G0.init($,W)});function s$($){return PJ(xJ,$)}var hJ=V("ZodISODate",($,W)=>{LG.init($,W),G0.init($,W)});function a$($){return VJ(hJ,$)}var yJ=V("ZodISOTime",($,W)=>{AG.init($,W),G0.init($,W)});function e$($){return jJ(yJ,$)}var fJ=V("ZodISODuration",($,W)=>{OG.init($,W),G0.init($,W)});function $8($){return MJ(fJ,$)}var uJ=($,W)=>{u4.init($,W),$.name="ZodError",Object.defineProperties($,{format:{value:(Q)=>rQ($,Q)},flatten:{value:(Q)=>tQ($,Q)},addIssue:{value:(Q)=>{$.issues.push(Q),$.message=JSON.stringify($.issues,e1,2)}},addIssues:{value:(Q)=>{$.issues.push(...Q),$.message=JSON.stringify($.issues,e1,2)}},isEmpty:{get(){return $.issues.length===0}}})},Rq=V("ZodError",uJ),v0=V("ZodError",uJ,{Parent:Error});var cJ=c4(v0),mJ=m4(v0),lJ=h6(v0),gJ=f6(v0),pJ=sQ(v0),iJ=aQ(v0),nJ=eQ(v0),dJ=$X(v0),oJ=WX(v0),tJ=QX(v0),rJ=XX(v0),sJ=GX(v0);var b0=V("ZodType",($,W)=>{return $0.init($,W),$.def=W,$.type=W.type,Object.defineProperty($,"_def",{value:W}),$.check=(...Q)=>{return $.clone(o.mergeDefs(W,{checks:[...W.checks??[],...Q.map((X)=>typeof X==="function"?{_zod:{check:X,def:{check:"custom"},onattach:[]}}:X)]}))},$.clone=(Q,X)=>i0($,Q,X),$.brand=()=>$,$.register=(Q,X)=>{return Q.add($,X),$},$.parse=(Q,X)=>cJ($,Q,X,{callee:$.parse}),$.safeParse=(Q,X)=>lJ($,Q,X),$.parseAsync=async(Q,X)=>mJ($,Q,X,{callee:$.parseAsync}),$.safeParseAsync=async(Q,X)=>gJ($,Q,X),$.spa=$.safeParseAsync,$.encode=(Q,X)=>pJ($,Q,X),$.decode=(Q,X)=>iJ($,Q,X),$.encodeAsync=async(Q,X)=>nJ($,Q,X),$.decodeAsync=async(Q,X)=>dJ($,Q,X),$.safeEncode=(Q,X)=>oJ($,Q,X),$.safeDecode=(Q,X)=>tJ($,Q,X),$.safeEncodeAsync=async(Q,X)=>rJ($,Q,X),$.safeDecodeAsync=async(Q,X)=>sJ($,Q,X),$.refine=(Q,X)=>$.check(zF(Q,X)),$.superRefine=(Q)=>$.check(DF(Q)),$.overwrite=(Q)=>$.check(c1(Q)),$.optional=()=>Y0($),$.nullable=()=>$w($),$.nullish=()=>Y0($w($)),$.nonoptional=(Q)=>GF($,Q),$.array=()=>p($),$.or=(Q)=>e([$,Q]),$.and=(Q)=>$9($,Q),$.transform=(Q)=>Q8($,Jw(Q)),$.default=(Q)=>WF($,Q),$.prefault=(Q)=>XF($,Q),$.catch=(Q)=>wF($,Q),$.pipe=(Q)=>Q8($,Q),$.readonly=()=>HF($),$.describe=(Q)=>{let X=$.clone();return c6.add(X,{description:Q}),X},Object.defineProperty($,"description",{get(){return c6.get($)?.description},configurable:!0}),$.meta=(...Q)=>{if(Q.length===0)return c6.get($);let X=$.clone();return c6.add(X,Q[0]),X},$.isOptional=()=>$.safeParse(void 0).success,$.isNullable=()=>$.safeParse(null).success,$}),Ww=V("_ZodString",($,W)=>{n4.init($,W),b0.init($,W);let Q=$._zod.bag;$.format=Q.format??null,$.minLength=Q.minimum??null,$.maxLength=Q.maximum??null,$.regex=(...X)=>$.check(m$(...X)),$.includes=(...X)=>$.check(p$(...X)),$.startsWith=(...X)=>$.check(i$(...X)),$.endsWith=(...X)=>$.check(n$(...X)),$.min=(...X)=>$.check(Q6(...X)),$.max=(...X)=>$.check(r4(...X)),$.length=(...X)=>$.check(s4(...X)),$.nonempty=(...X)=>$.check(Q6(1,...X)),$.lowercase=(X)=>$.check(l$(X)),$.uppercase=(X)=>$.check(g$(X)),$.trim=()=>$.check(o$()),$.normalize=(...X)=>$.check(d$(...X)),$.toLowerCase=()=>$.check(t$()),$.toUpperCase=()=>$.check(r$())}),MD=V("ZodString",($,W)=>{n4.init($,W),Ww.init($,W),$.email=(Q)=>$.check(eG(qD,Q)),$.url=(Q)=>$.check(GJ(ID,Q)),$.jwt=(Q)=>$.check(ZJ(cD,Q)),$.emoji=(Q)=>$.check(JJ(ND,Q)),$.guid=(Q)=>$.check(c$(aJ,Q)),$.uuid=(Q)=>$.check($J(e4,Q)),$.uuidv4=(Q)=>$.check(WJ(e4,Q)),$.uuidv6=(Q)=>$.check(QJ(e4,Q)),$.uuidv7=(Q)=>$.check(XJ(e4,Q)),$.nanoid=(Q)=>$.check(wJ(ED,Q)),$.guid=(Q)=>$.check(c$(aJ,Q)),$.cuid=(Q)=>$.check(YJ(TD,Q)),$.cuid2=(Q)=>$.check(bJ(RD,Q)),$.ulid=(Q)=>$.check(HJ(SD,Q)),$.base64=(Q)=>$.check(AJ(yD,Q)),$.base64url=(Q)=>$.check(OJ(fD,Q)),$.xid=(Q)=>$.check(zJ(CD,Q)),$.ksuid=(Q)=>$.check(DJ(kD,Q)),$.ipv4=(Q)=>$.check(FJ(vD,Q)),$.ipv6=(Q)=>$.check(UJ(_D,Q)),$.cidrv4=(Q)=>$.check(BJ(xD,Q)),$.cidrv6=(Q)=>$.check(LJ(hD,Q)),$.e164=(Q)=>$.check(KJ(uD,Q)),$.datetime=(Q)=>$.check(s$(Q)),$.date=(Q)=>$.check(a$(Q)),$.time=(Q)=>$.check(e$(Q)),$.duration=(Q)=>$.check($8(Q))});function Z($){return aG(MD,$)}var G0=V("ZodStringFormat",($,W)=>{W0.init($,W),Ww.init($,W)}),qD=V("ZodEmail",($,W)=>{JG.init($,W),G0.init($,W)});var aJ=V("ZodGUID",($,W)=>{XG.init($,W),G0.init($,W)});var e4=V("ZodUUID",($,W)=>{GG.init($,W),G0.init($,W)});var ID=V("ZodURL",($,W)=>{wG.init($,W),G0.init($,W)});var ND=V("ZodEmoji",($,W)=>{YG.init($,W),G0.init($,W)});var ED=V("ZodNanoID",($,W)=>{bG.init($,W),G0.init($,W)});var TD=V("ZodCUID",($,W)=>{HG.init($,W),G0.init($,W)});var RD=V("ZodCUID2",($,W)=>{zG.init($,W),G0.init($,W)});var SD=V("ZodULID",($,W)=>{DG.init($,W),G0.init($,W)});var CD=V("ZodXID",($,W)=>{FG.init($,W),G0.init($,W)});var kD=V("ZodKSUID",($,W)=>{UG.init($,W),G0.init($,W)});var vD=V("ZodIPv4",($,W)=>{KG.init($,W),G0.init($,W)});var _D=V("ZodIPv6",($,W)=>{ZG.init($,W),G0.init($,W)});var xD=V("ZodCIDRv4",($,W)=>{PG.init($,W),G0.init($,W)});var hD=V("ZodCIDRv6",($,W)=>{VG.init($,W),G0.init($,W)});var yD=V("ZodBase64",($,W)=>{MG.init($,W),G0.init($,W)});var fD=V("ZodBase64URL",($,W)=>{qG.init($,W),G0.init($,W)});var uD=V("ZodE164",($,W)=>{IG.init($,W),G0.init($,W)});var cD=V("ZodJWT",($,W)=>{NG.init($,W),G0.init($,W)});var Qw=V("ZodNumber",($,W)=>{y$.init($,W),b0.init($,W),$.gt=(X,G)=>$.check(o4(X,G)),$.gte=(X,G)=>$.check(l6(X,G)),$.min=(X,G)=>$.check(l6(X,G)),$.lt=(X,G)=>$.check(d4(X,G)),$.lte=(X,G)=>$.check(m6(X,G)),$.max=(X,G)=>$.check(m6(X,G)),$.int=(X)=>$.check(eJ(X)),$.safe=(X)=>$.check(eJ(X)),$.positive=(X)=>$.check(o4(0,X)),$.nonnegative=(X)=>$.check(l6(0,X)),$.negative=(X)=>$.check(d4(0,X)),$.nonpositive=(X)=>$.check(m6(0,X)),$.multipleOf=(X,G)=>$.check(t4(X,G)),$.step=(X,G)=>$.check(t4(X,G)),$.finite=()=>$;let Q=$._zod.bag;$.minValue=Math.max(Q.minimum??Number.NEGATIVE_INFINITY,Q.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(Q.maximum??Number.POSITIVE_INFINITY,Q.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(Q.format??"").includes("int")||Number.isSafeInteger(Q.multipleOf??0.5),$.isFinite=!0,$.format=Q.format??null});function r($){return qJ(Qw,$)}var mD=V("ZodNumberFormat",($,W)=>{EG.init($,W),Qw.init($,W)});function eJ($){return IJ(mD,$)}var lD=V("ZodBoolean",($,W)=>{TG.init($,W),b0.init($,W)});function B0($){return NJ(lD,$)}var gD=V("ZodNull",($,W)=>{RG.init($,W),b0.init($,W)});function X8($){return EJ(gD,$)}var pD=V("ZodUnknown",($,W)=>{SG.init($,W),b0.init($,W)});function J0(){return TJ(pD)}var iD=V("ZodNever",($,W)=>{CG.init($,W),b0.init($,W)});function nD($){return RJ(iD,$)}var dD=V("ZodArray",($,W)=>{kG.init($,W),b0.init($,W),$.element=W.element,$.min=(Q,X)=>$.check(Q6(Q,X)),$.nonempty=(Q)=>$.check(Q6(1,Q)),$.max=(Q,X)=>$.check(r4(Q,X)),$.length=(Q,X)=>$.check(s4(Q,X)),$.unwrap=()=>$.element});function p($,W){return SJ(dD,$,W)}var Xw=V("ZodObject",($,W)=>{xG.init($,W),b0.init($,W),o.defineLazy($,"shape",()=>{return W.shape}),$.keyof=()=>I0(Object.keys($._zod.def.shape)),$.catchall=(Q)=>$.clone({...$._zod.def,catchall:Q}),$.passthrough=()=>$.clone({...$._zod.def,catchall:J0()}),$.loose=()=>$.clone({...$._zod.def,catchall:J0()}),$.strict=()=>$.clone({...$._zod.def,catchall:nD()}),$.strip=()=>$.clone({...$._zod.def,catchall:void 0}),$.extend=(Q)=>{return o.extend($,Q)},$.safeExtend=(Q)=>{return o.safeExtend($,Q)},$.merge=(Q)=>o.merge($,Q),$.pick=(Q)=>o.pick($,Q),$.omit=(Q)=>o.omit($,Q),$.partial=(...Q)=>o.partial(ww,$,Q[0]),$.required=(...Q)=>o.required(Yw,$,Q[0])});function E($,W){let Q={type:"object",shape:$??{},...o.normalizeParams(W)};return new Xw(Q)}function j0($,W){return new Xw({type:"object",shape:$,catchall:J0(),...o.normalizeParams(W)})}var Gw=V("ZodUnion",($,W)=>{f$.init($,W),b0.init($,W),$.options=W.options});function e($,W){return new Gw({type:"union",options:$,...o.normalizeParams(W)})}var oD=V("ZodDiscriminatedUnion",($,W)=>{Gw.init($,W),hG.init($,W)});function G8($,W,Q){return new oD({type:"union",options:W,discriminator:$,...o.normalizeParams(Q)})}var tD=V("ZodIntersection",($,W)=>{yG.init($,W),b0.init($,W)});function $9($,W){return new tD({type:"intersection",left:$,right:W})}var rD=V("ZodRecord",($,W)=>{fG.init($,W),b0.init($,W),$.keyType=W.keyType,$.valueType=W.valueType});function w0($,W,Q){return new rD({type:"record",keyType:$,valueType:W,...o.normalizeParams(Q)})}var W8=V("ZodEnum",($,W)=>{uG.init($,W),b0.init($,W),$.enum=W.entries,$.options=Object.values(W.entries);let Q=new Set(Object.keys(W.entries));$.extract=(X,G)=>{let J={};for(let w of X)if(Q.has(w))J[w]=W.entries[w];else throw Error(`Key ${w} not found in enum`);return new W8({...W,checks:[],...o.normalizeParams(G),entries:J})},$.exclude=(X,G)=>{let J={...W.entries};for(let w of X)if(Q.has(w))delete J[w];else throw Error(`Key ${w} not found in enum`);return new W8({...W,checks:[],...o.normalizeParams(G),entries:J})}});function I0($,W){let Q=Array.isArray($)?Object.fromEntries($.map((X)=>[X,X])):$;return new W8({type:"enum",entries:Q,...o.normalizeParams(W)})}var sD=V("ZodLiteral",($,W)=>{cG.init($,W),b0.init($,W),$.values=new Set(W.values),Object.defineProperty($,"value",{get(){if(W.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return W.values[0]}})});function T($,W){return new sD({type:"literal",values:Array.isArray($)?$:[$],...o.normalizeParams(W)})}var aD=V("ZodTransform",($,W)=>{mG.init($,W),b0.init($,W),$._zod.parse=(Q,X)=>{if(X.direction==="backward")throw new C6($.constructor.name);Q.addIssue=(J)=>{if(typeof J==="string")Q.issues.push(o.issue(J,Q.value,W));else{let w=J;if(w.fatal)w.continue=!1;w.code??(w.code="custom"),w.input??(w.input=Q.value),w.inst??(w.inst=$),Q.issues.push(o.issue(w))}};let G=W.transform(Q.value,Q);if(G instanceof Promise)return G.then((J)=>{return Q.value=J,Q});return Q.value=G,Q}});function Jw($){return new aD({type:"transform",transform:$})}var ww=V("ZodOptional",($,W)=>{lG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function Y0($){return new ww({type:"optional",innerType:$})}var eD=V("ZodNullable",($,W)=>{gG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function $w($){return new eD({type:"nullable",innerType:$})}var $F=V("ZodDefault",($,W)=>{pG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function WF($,W){return new $F({type:"default",innerType:$,get defaultValue(){return typeof W==="function"?W():o.shallowClone(W)}})}var QF=V("ZodPrefault",($,W)=>{iG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function XF($,W){return new QF({type:"prefault",innerType:$,get defaultValue(){return typeof W==="function"?W():o.shallowClone(W)}})}var Yw=V("ZodNonOptional",($,W)=>{nG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function GF($,W){return new Yw({type:"nonoptional",innerType:$,...o.normalizeParams(W)})}var JF=V("ZodCatch",($,W)=>{dG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function wF($,W){return new JF({type:"catch",innerType:$,catchValue:typeof W==="function"?W:()=>W})}var YF=V("ZodPipe",($,W)=>{oG.init($,W),b0.init($,W),$.in=W.in,$.out=W.out});function Q8($,W){return new YF({type:"pipe",in:$,out:W})}var bF=V("ZodReadonly",($,W)=>{tG.init($,W),b0.init($,W),$.unwrap=()=>$._zod.def.innerType});function HF($){return new bF({type:"readonly",innerType:$})}var bw=V("ZodCustom",($,W)=>{rG.init($,W),b0.init($,W)});function Hw($,W){return CJ(bw,$??(()=>!0),W)}function zF($,W={}){return kJ(bw,$,W)}function DF($){return vJ($)}function J8($,W){return Q8(Jw($),W)}f0(u$());var w8="2025-11-25";var zw=[w8,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],T1="io.modelcontextprotocol/related-task",Q9="2.0",A0=Hw(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Dw=e([Z(),r().int()]),Fw=Z(),qI=j0({ttl:e([r(),X8()]).optional(),pollInterval:r().optional()}),FF=E({ttl:r().optional()}),UF=E({taskId:Z()}),Y8=j0({progressToken:Dw.optional(),[T1]:UF.optional()}),_0=E({_meta:Y8.optional()}),i6=_0.extend({task:FF.optional()}),Uw=($)=>i6.safeParse($).success,O0=E({method:Z(),params:_0.loose().optional()}),u0=E({_meta:Y8.optional()}),c0=E({method:Z(),params:u0.loose().optional()}),K0=j0({_meta:Y8.optional()}),X9=e([Z(),r().int()]),Bw=E({jsonrpc:T(Q9),id:X9,...O0.shape}).strict(),b8=($)=>Bw.safeParse($).success,Lw=E({jsonrpc:T(Q9),...c0.shape}).strict(),Aw=($)=>Lw.safeParse($).success,H8=E({jsonrpc:T(Q9),id:X9,result:K0}).strict(),n6=($)=>H8.safeParse($).success;var i;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(i||(i={}));var z8=E({jsonrpc:T(Q9),id:X9.optional(),error:E({code:r().int(),message:Z(),data:J0().optional()})}).strict();var Ow=($)=>z8.safeParse($).success;var Kw=e([Bw,Lw,H8,z8]),II=e([H8,z8]),G9=K0.strict(),BF=u0.extend({requestId:X9.optional(),reason:Z().optional()}),J9=c0.extend({method:T("notifications/cancelled"),params:BF}),LF=E({src:Z(),mimeType:Z().optional(),sizes:p(Z()).optional(),theme:I0(["light","dark"]).optional()}),d6=E({icons:p(LF).optional()}),G6=E({name:Z(),title:Z().optional()}),Zw=G6.extend({...G6.shape,...d6.shape,version:Z(),websiteUrl:Z().optional(),description:Z().optional()}),AF=$9(E({applyDefaults:B0().optional()}),w0(Z(),J0())),OF=J8(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},$9(E({form:AF.optional(),url:A0.optional()}),w0(Z(),J0()).optional())),KF=j0({list:A0.optional(),cancel:A0.optional(),requests:j0({sampling:j0({createMessage:A0.optional()}).optional(),elicitation:j0({create:A0.optional()}).optional()}).optional()}),ZF=j0({list:A0.optional(),cancel:A0.optional(),requests:j0({tools:j0({call:A0.optional()}).optional()}).optional()}),PF=E({experimental:w0(Z(),A0).optional(),sampling:E({context:A0.optional(),tools:A0.optional()}).optional(),elicitation:OF.optional(),roots:E({listChanged:B0().optional()}).optional(),tasks:KF.optional()}),VF=_0.extend({protocolVersion:Z(),capabilities:PF,clientInfo:Zw}),D8=O0.extend({method:T("initialize"),params:VF});var jF=E({experimental:w0(Z(),A0).optional(),logging:A0.optional(),completions:A0.optional(),prompts:E({listChanged:B0().optional()}).optional(),resources:E({subscribe:B0().optional(),listChanged:B0().optional()}).optional(),tools:E({listChanged:B0().optional()}).optional(),tasks:ZF.optional()}),MF=K0.extend({protocolVersion:Z(),capabilities:jF,serverInfo:Zw,instructions:Z().optional()}),F8=c0.extend({method:T("notifications/initialized"),params:u0.optional()});var w9=O0.extend({method:T("ping"),params:_0.optional()}),qF=E({progress:r(),total:Y0(r()),message:Y0(Z())}),IF=E({...u0.shape,...qF.shape,progressToken:Dw}),Y9=c0.extend({method:T("notifications/progress"),params:IF}),NF=_0.extend({cursor:Fw.optional()}),o6=O0.extend({params:NF.optional()}),t6=K0.extend({nextCursor:Fw.optional()}),EF=I0(["working","input_required","completed","failed","cancelled"]),r6=E({taskId:Z(),status:EF,ttl:e([r(),X8()]),createdAt:Z(),lastUpdatedAt:Z(),pollInterval:Y0(r()),statusMessage:Y0(Z())}),J6=K0.extend({task:r6}),TF=u0.merge(r6),s6=c0.extend({method:T("notifications/tasks/status"),params:TF}),b9=O0.extend({method:T("tasks/get"),params:_0.extend({taskId:Z()})}),H9=K0.merge(r6),z9=O0.extend({method:T("tasks/result"),params:_0.extend({taskId:Z()})}),NI=K0.loose(),D9=o6.extend({method:T("tasks/list")}),F9=t6.extend({tasks:p(r6)}),U9=O0.extend({method:T("tasks/cancel"),params:_0.extend({taskId:Z()})}),Pw=K0.merge(r6),Vw=E({uri:Z(),mimeType:Y0(Z()),_meta:w0(Z(),J0()).optional()}),jw=Vw.extend({text:Z()}),U8=Z().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mw=Vw.extend({blob:U8}),a6=I0(["user","assistant"]),w6=E({audience:p(a6).optional(),priority:r().min(0).max(1).optional(),lastModified:p6.datetime({offset:!0}).optional()}),qw=E({...G6.shape,...d6.shape,uri:Z(),description:Y0(Z()),mimeType:Y0(Z()),annotations:w6.optional(),_meta:Y0(j0({}))}),RF=E({...G6.shape,...d6.shape,uriTemplate:Z(),description:Y0(Z()),mimeType:Y0(Z()),annotations:w6.optional(),_meta:Y0(j0({}))}),B8=o6.extend({method:T("resources/list")}),SF=t6.extend({resources:p(qw)}),CF=o6.extend({method:T("resources/templates/list")}),kF=t6.extend({resourceTemplates:p(RF)}),L8=_0.extend({uri:Z()}),vF=L8,A8=O0.extend({method:T("resources/read"),params:vF}),_F=K0.extend({contents:p(e([jw,Mw]))}),xF=c0.extend({method:T("notifications/resources/list_changed"),params:u0.optional()}),hF=L8,yF=O0.extend({method:T("resources/subscribe"),params:hF}),fF=L8,uF=O0.extend({method:T("resources/unsubscribe"),params:fF}),cF=u0.extend({uri:Z()}),mF=c0.extend({method:T("notifications/resources/updated"),params:cF}),lF=E({name:Z(),description:Y0(Z()),required:Y0(B0())}),gF=E({...G6.shape,...d6.shape,description:Y0(Z()),arguments:Y0(p(lF)),_meta:Y0(j0({}))}),pF=o6.extend({method:T("prompts/list")}),iF=t6.extend({prompts:p(gF)}),nF=_0.extend({name:Z(),arguments:w0(Z(),Z()).optional()}),dF=O0.extend({method:T("prompts/get"),params:nF}),O8=E({type:T("text"),text:Z(),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),K8=E({type:T("image"),data:U8,mimeType:Z(),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),Z8=E({type:T("audio"),data:U8,mimeType:Z(),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),oF=E({type:T("tool_use"),name:Z(),id:Z(),input:w0(Z(),J0()),_meta:w0(Z(),J0()).optional()}),tF=E({type:T("resource"),resource:e([jw,Mw]),annotations:w6.optional(),_meta:w0(Z(),J0()).optional()}),rF=qw.extend({type:T("resource_link")}),P8=e([O8,K8,Z8,rF,tF]),sF=E({role:a6,content:P8}),aF=K0.extend({description:Z().optional(),messages:p(sF)}),eF=c0.extend({method:T("notifications/prompts/list_changed"),params:u0.optional()}),$U=E({title:Z().optional(),readOnlyHint:B0().optional(),destructiveHint:B0().optional(),idempotentHint:B0().optional(),openWorldHint:B0().optional()}),WU=E({taskSupport:I0(["required","optional","forbidden"]).optional()}),Iw=E({...G6.shape,...d6.shape,description:Z().optional(),inputSchema:E({type:T("object"),properties:w0(Z(),A0).optional(),required:p(Z()).optional()}).catchall(J0()),outputSchema:E({type:T("object"),properties:w0(Z(),A0).optional(),required:p(Z()).optional()}).catchall(J0()).optional(),annotations:$U.optional(),execution:WU.optional(),_meta:w0(Z(),J0()).optional()}),V8=o6.extend({method:T("tools/list")}),QU=t6.extend({tools:p(Iw)}),B9=K0.extend({content:p(P8).default([]),structuredContent:w0(Z(),J0()).optional(),isError:B0().optional()}),EI=B9.or(K0.extend({toolResult:J0()})),XU=i6.extend({name:Z(),arguments:w0(Z(),J0()).optional()}),e6=O0.extend({method:T("tools/call"),params:XU}),GU=c0.extend({method:T("notifications/tools/list_changed"),params:u0.optional()}),TI=E({autoRefresh:B0().default(!0),debounceMs:r().int().nonnegative().default(300)}),$4=I0(["debug","info","notice","warning","error","critical","alert","emergency"]),JU=_0.extend({level:$4}),j8=O0.extend({method:T("logging/setLevel"),params:JU}),wU=u0.extend({level:$4,logger:Z().optional(),data:J0()}),YU=c0.extend({method:T("notifications/message"),params:wU}),bU=E({name:Z().optional()}),HU=E({hints:p(bU).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),zU=E({mode:I0(["auto","required","none"]).optional()}),DU=E({type:T("tool_result"),toolUseId:Z().describe("The unique identifier for the corresponding tool call."),content:p(P8).default([]),structuredContent:E({}).loose().optional(),isError:B0().optional(),_meta:w0(Z(),J0()).optional()}),FU=G8("type",[O8,K8,Z8]),W9=G8("type",[O8,K8,Z8,oF,DU]),UU=E({role:a6,content:e([W9,p(W9)]),_meta:w0(Z(),J0()).optional()}),BU=i6.extend({messages:p(UU),modelPreferences:HU.optional(),systemPrompt:Z().optional(),includeContext:I0(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:p(Z()).optional(),metadata:A0.optional(),tools:p(Iw).optional(),toolChoice:zU.optional()}),LU=O0.extend({method:T("sampling/createMessage"),params:BU}),M8=K0.extend({model:Z(),stopReason:Y0(I0(["endTurn","stopSequence","maxTokens"]).or(Z())),role:a6,content:FU}),q8=K0.extend({model:Z(),stopReason:Y0(I0(["endTurn","stopSequence","maxTokens","toolUse"]).or(Z())),role:a6,content:e([W9,p(W9)])}),AU=E({type:T("boolean"),title:Z().optional(),description:Z().optional(),default:B0().optional()}),OU=E({type:T("string"),title:Z().optional(),description:Z().optional(),minLength:r().optional(),maxLength:r().optional(),format:I0(["email","uri","date","date-time"]).optional(),default:Z().optional()}),KU=E({type:I0(["number","integer"]),title:Z().optional(),description:Z().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),ZU=E({type:T("string"),title:Z().optional(),description:Z().optional(),enum:p(Z()),default:Z().optional()}),PU=E({type:T("string"),title:Z().optional(),description:Z().optional(),oneOf:p(E({const:Z(),title:Z()})),default:Z().optional()}),VU=E({type:T("string"),title:Z().optional(),description:Z().optional(),enum:p(Z()),enumNames:p(Z()).optional(),default:Z().optional()}),jU=e([ZU,PU]),MU=E({type:T("array"),title:Z().optional(),description:Z().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({type:T("string"),enum:p(Z())}),default:p(Z()).optional()}),qU=E({type:T("array"),title:Z().optional(),description:Z().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({anyOf:p(E({const:Z(),title:Z()}))}),default:p(Z()).optional()}),IU=e([MU,qU]),NU=e([VU,jU,IU]),EU=e([NU,AU,OU,KU]),TU=i6.extend({mode:T("form").optional(),message:Z(),requestedSchema:E({type:T("object"),properties:w0(Z(),EU),required:p(Z()).optional()})}),RU=i6.extend({mode:T("url"),message:Z(),elicitationId:Z(),url:Z().url()}),SU=e([TU,RU]),CU=O0.extend({method:T("elicitation/create"),params:SU}),kU=u0.extend({elicitationId:Z()}),vU=c0.extend({method:T("notifications/elicitation/complete"),params:kU}),L9=K0.extend({action:I0(["accept","decline","cancel"]),content:J8(($)=>$===null?void 0:$,w0(Z(),e([Z(),r(),B0(),p(Z())])).optional())}),_U=E({type:T("ref/resource"),uri:Z()});var xU=E({type:T("ref/prompt"),name:Z()}),hU=_0.extend({ref:e([xU,_U]),argument:E({name:Z(),value:Z()}),context:E({arguments:w0(Z(),Z()).optional()}).optional()}),yU=O0.extend({method:T("completion/complete"),params:hU});var fU=K0.extend({completion:j0({values:p(Z()).max(100),total:Y0(r().int()),hasMore:Y0(B0())})}),uU=E({uri:Z().startsWith("file://"),name:Z().optional(),_meta:w0(Z(),J0()).optional()}),cU=O0.extend({method:T("roots/list"),params:_0.optional()}),I8=K0.extend({roots:p(uU)}),mU=c0.extend({method:T("notifications/roots/list_changed"),params:u0.optional()}),RI=e([w9,D8,yU,j8,dF,pF,B8,CF,A8,yF,uF,e6,V8,b9,z9,D9,U9]),SI=e([J9,Y9,F8,mU,s6]),CI=e([G9,M8,q8,L9,I8,H9,F9,J6]),kI=e([w9,LU,CU,cU,b9,z9,D9,U9]),vI=e([J9,Y9,YU,mF,xF,GU,eF,s6,vU]),_I=e([G9,MF,fU,aF,iF,SF,kF,_F,B9,QU,H9,F9,J6]);class l extends Error{constructor($,W,Q){super(`MCP error ${$}: ${W}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,W,Q){if($===i.UrlElicitationRequired&&Q){let X=Q;if(X.elicitations)return new Nw(X.elicitations,W)}return new l($,W,Q)}}class Nw extends l{constructor($,W=`URL elicitation${$.length>1?"s":""} required`){super(i.UrlElicitationRequired,W,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}function R1($){return $==="completed"||$==="failed"||$==="cancelled"}var lU=Symbol("Let zodToJsonSchema decide on which parser to use");var UN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function N8($){let Q=a4($)?.method;if(!Q)throw Error("Schema is missing a method literal");let X=_J(Q);if(typeof X!=="string")throw Error("Schema method literal must be a string");return X}function E8($,W){let Q=E1($,W);if(!Q.success)throw Q.error;return Q.data}var oU=60000;class T8{constructor($){if(this._options=$,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(J9,(W)=>{this._oncancel(W)}),this.setNotificationHandler(Y9,(W)=>{this._onprogress(W)}),this.setRequestHandler(w9,(W)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(b9,async(W,Q)=>{let X=await this._taskStore.getTask(W.params.taskId,Q.sessionId);if(!X)throw new l(i.InvalidParams,"Failed to retrieve task: Task not found");return{...X}}),this.setRequestHandler(z9,async(W,Q)=>{let X=async()=>{let G=W.params.taskId;if(this._taskMessageQueue){let w;while(w=await this._taskMessageQueue.dequeue(G,Q.sessionId)){if(w.type==="response"||w.type==="error"){let Y=w.message,b=Y.id,H=this._requestResolvers.get(b);if(H)if(this._requestResolvers.delete(b),w.type==="response")H(Y);else{let z=Y,F=new l(z.error.code,z.error.message,z.error.data);H(F)}else{let z=w.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${b}`))}continue}await this._transport?.send(w.message,{relatedRequestId:Q.requestId})}}let J=await this._taskStore.getTask(G,Q.sessionId);if(!J)throw new l(i.InvalidParams,`Task not found: ${G}`);if(!R1(J.status))return await this._waitForTaskUpdate(G,Q.signal),await X();if(R1(J.status)){let w=await this._taskStore.getTaskResult(G,Q.sessionId);return this._clearTaskQueue(G),{...w,_meta:{...w._meta,[T1]:{taskId:G}}}}return await X()};return await X()}),this.setRequestHandler(D9,async(W,Q)=>{try{let{tasks:X,nextCursor:G}=await this._taskStore.listTasks(W.params?.cursor,Q.sessionId);return{tasks:X,nextCursor:G,_meta:{}}}catch(X){throw new l(i.InvalidParams,`Failed to list tasks: ${X instanceof Error?X.message:String(X)}`)}}),this.setRequestHandler(U9,async(W,Q)=>{try{let X=await this._taskStore.getTask(W.params.taskId,Q.sessionId);if(!X)throw new l(i.InvalidParams,`Task not found: ${W.params.taskId}`);if(R1(X.status))throw new l(i.InvalidParams,`Cannot cancel task in terminal status: ${X.status}`);await this._taskStore.updateTaskStatus(W.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(W.params.taskId);let G=await this._taskStore.getTask(W.params.taskId,Q.sessionId);if(!G)throw new l(i.InvalidParams,`Task not found after cancellation: ${W.params.taskId}`);return{_meta:{},...G}}catch(X){if(X instanceof l)throw X;throw new l(i.InvalidRequest,`Failed to cancel task: ${X instanceof Error?X.message:String(X)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,W,Q,X,G=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(X,W),startTime:Date.now(),timeout:W,maxTotalTimeout:Q,resetTimeoutOnProgress:G,onTimeout:X})}_resetTimeout($){let W=this._timeoutInfo.get($);if(!W)return!1;let Q=Date.now()-W.startTime;if(W.maxTotalTimeout&&Q>=W.maxTotalTimeout)throw this._timeoutInfo.delete($),l.fromError(i.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:W.maxTotalTimeout,totalElapsed:Q});return clearTimeout(W.timeoutId),W.timeoutId=setTimeout(W.onTimeout,W.timeout),!0}_cleanupTimeout($){let W=this._timeoutInfo.get($);if(W)clearTimeout(W.timeoutId),this._timeoutInfo.delete($)}async connect($){this._transport=$;let W=this.transport?.onclose;this._transport.onclose=()=>{W?.(),this._onclose()};let Q=this.transport?.onerror;this._transport.onerror=(G)=>{Q?.(G),this._onerror(G)};let X=this._transport?.onmessage;this._transport.onmessage=(G,J)=>{if(X?.(G,J),n6(G)||Ow(G))this._onresponse(G);else if(b8(G))this._onrequest(G,J);else if(Aw(G))this._onnotification(G);else this._onerror(Error(`Unknown message type: ${JSON.stringify(G)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let W=l.fromError(i.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Q of $.values())Q(W)}_onerror($){this.onerror?.($)}_onnotification($){let W=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(W===void 0)return;Promise.resolve().then(()=>W($)).catch((Q)=>this._onerror(Error(`Uncaught error in notification handler: ${Q}`)))}_onrequest($,W){let Q=this._requestHandlers.get($.method)??this.fallbackRequestHandler,X=this._transport,G=$.params?._meta?.[T1]?.taskId;if(Q===void 0){let H={jsonrpc:"2.0",id:$.id,error:{code:i.MethodNotFound,message:"Method not found"}};if(G&&this._taskMessageQueue)this._enqueueTaskMessage(G,{type:"error",message:H,timestamp:Date.now()},X?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else X?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set($.id,J);let w=Uw($.params)?$.params.task:void 0,Y=this._taskStore?this.requestTaskStore($,X?.sessionId):void 0,b={signal:J.signal,sessionId:X?.sessionId,_meta:$.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:$.id};if(G)z.relatedTask={taskId:G};await this.notification(H,z)},sendRequest:async(H,z,F)=>{let U={...F,relatedRequestId:$.id};if(G&&!U.relatedTask)U.relatedTask={taskId:G};let B=U.relatedTask?.taskId??G;if(B&&Y)await Y.updateTaskStatus(B,"input_required");return await this.request(H,z,U)},authInfo:W?.authInfo,requestId:$.id,requestInfo:W?.requestInfo,taskId:G,taskStore:Y,taskRequestedTtl:w?.ttl,closeSSEStream:W?.closeSSEStream,closeStandaloneSSEStream:W?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(w)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,b)).then(async(H)=>{if(J.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:$.id};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"response",message:z,timestamp:Date.now()},X?.sessionId);else await X?.send(z)},async(H)=>{if(J.signal.aborted)return;let z={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(H.code)?H.code:i.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(G&&this._taskMessageQueue)await this._enqueueTaskMessage(G,{type:"error",message:z,timestamp:Date.now()},X?.sessionId);else await X?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:W,...Q}=$.params,X=Number(W),G=this._progressHandlers.get(X);if(!G){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let J=this._responseHandlers.get(X),w=this._timeoutInfo.get(X);if(w&&J&&w.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(Y){this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),J(Y);return}G(Q)}_onresponse($){let W=Number($.id),Q=this._requestResolvers.get(W);if(Q){if(this._requestResolvers.delete(W),n6($))Q($);else{let J=new l($.error.code,$.error.message,$.error.data);Q(J)}return}let X=this._responseHandlers.get(W);if(X===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(W),this._cleanupTimeout(W);let G=!1;if(n6($)&&$.result&&typeof $.result==="object"){let J=$.result;if(J.task&&typeof J.task==="object"){let w=J.task;if(typeof w.taskId==="string")G=!0,this._taskProgressTokens.set(w.taskId,W)}}if(!G)this._progressHandlers.delete(W);if(n6($))X($);else{let J=l.fromError($.error.code,$.error.message,$.error.data);X(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,W,Q){let{task:X}=Q??{};if(!X){try{yield{type:"result",result:await this.request($,W,Q)}}catch(J){yield{type:"error",error:J instanceof l?J:new l(i.InternalError,String(J))}}return}let G;try{let J=await this.request($,J6,Q);if(J.task)G=J.task.taskId,yield{type:"taskCreated",task:J.task};else throw new l(i.InternalError,"Task creation did not return a task");while(!0){let w=await this.getTask({taskId:G},Q);if(yield{type:"taskStatus",task:w},R1(w.status)){if(w.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:G},W,Q)};else if(w.status==="failed")yield{type:"error",error:new l(i.InternalError,`Task ${G} failed`)};else if(w.status==="cancelled")yield{type:"error",error:new l(i.InternalError,`Task ${G} was cancelled`)};return}if(w.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:G},W,Q)};return}let Y=w.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((b)=>setTimeout(b,Y)),Q?.signal?.throwIfAborted()}}catch(J){yield{type:"error",error:J instanceof l?J:new l(i.InternalError,String(J))}}}request($,W,Q){let{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J,task:w,relatedTask:Y}=Q??{};return new Promise((b,H)=>{let z=(M)=>{H(M)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),w)this.assertTaskCapability($.method)}catch(M){z(M);return}Q?.signal?.throwIfAborted();let F=this._requestMessageId++,U={...$,jsonrpc:"2.0",id:F};if(Q?.onprogress)this._progressHandlers.set(F,Q.onprogress),U.params={...$.params,_meta:{...$.params?._meta||{},progressToken:F}};if(w)U.params={...U.params,task:w};if(Y)U.params={...U.params,_meta:{...U.params?._meta||{},[T1]:Y}};let B=(M)=>{this._responseHandlers.delete(F),this._progressHandlers.delete(F),this._cleanupTimeout(F),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:F,reason:String(M)}},{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((C)=>this._onerror(Error(`Failed to send cancellation: ${C}`)));let S=M instanceof l?M:new l(i.RequestTimeout,String(M));H(S)};this._responseHandlers.set(F,(M)=>{if(Q?.signal?.aborted)return;if(M instanceof Error)return H(M);try{let S=E1(W,M.result);if(!S.success)H(S.error);else b(S.data)}catch(S){H(S)}}),Q?.signal?.addEventListener("abort",()=>{B(Q?.signal?.reason)});let K=Q?.timeout??oU,P=()=>B(l.fromError(i.RequestTimeout,"Request timed out",{timeout:K}));this._setupTimeout(F,K,Q?.maxTotalTimeout,P,Q?.resetTimeoutOnProgress??!1);let q=Y?.taskId;if(q){let M=(S)=>{let C=this._responseHandlers.get(F);if(C)C(S);else this._onerror(Error(`Response handler missing for side-channeled request ${F}`))};this._requestResolvers.set(F,M),this._enqueueTaskMessage(q,{type:"request",message:U,timestamp:Date.now()}).catch((S)=>{this._cleanupTimeout(F),H(S)})}else this._transport.send(U,{relatedRequestId:X,resumptionToken:G,onresumptiontoken:J}).catch((M)=>{this._cleanupTimeout(F),H(M)})})}async getTask($,W){return this.request({method:"tasks/get",params:$},H9,W)}async getTaskResult($,W,Q){return this.request({method:"tasks/result",params:$},W,Q)}async listTasks($,W){return this.request({method:"tasks/list",params:$},F9,W)}async cancelTask($,W){return this.request({method:"tasks/cancel",params:$},Pw,W)}async notification($,W){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let Q=W?.relatedTask?.taskId;if(Q){let w={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[T1]:W.relatedTask}}};await this._enqueueTaskMessage(Q,{type:"notification",message:w,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!W?.relatedRequestId&&!W?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let w={...$,jsonrpc:"2.0"};if(W?.relatedTask)w={...w,params:{...w.params,_meta:{...w.params?._meta||{},[T1]:W.relatedTask}}};this._transport?.send(w,W).catch((Y)=>this._onerror(Y))});return}let J={...$,jsonrpc:"2.0"};if(W?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[T1]:W.relatedTask}}};await this._transport.send(J,W)}setRequestHandler($,W){let Q=N8($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(X,G)=>{let J=E8($,X);return Promise.resolve(W(J,G))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,W){let Q=N8($);this._notificationHandlers.set(Q,(X)=>{let G=E8($,X);return Promise.resolve(W(G))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let W=this._taskProgressTokens.get($);if(W!==void 0)this._progressHandlers.delete(W),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,W,Q){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let X=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,W,Q,X)}async _clearTaskQueue($,W){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,W);for(let X of Q)if(X.type==="request"&&b8(X.message)){let G=X.message.id,J=this._requestResolvers.get(G);if(J)J(new l(i.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(G);else this._onerror(Error(`Resolver missing for request ${G} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,W){let Q=this._options?.defaultTaskPollInterval??1000;try{let X=await this._taskStore?.getTask($);if(X?.pollInterval)Q=X.pollInterval}catch{}return new Promise((X,G)=>{if(W.aborted){G(new l(i.InvalidRequest,"Request cancelled"));return}let J=setTimeout(X,Q);W.addEventListener("abort",()=>{clearTimeout(J),G(new l(i.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,W){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(X)=>{if(!$)throw Error("No request provided");return await Q.createTask(X,$.id,{method:$.method,params:$.params},W)},getTask:async(X)=>{let G=await Q.getTask(X,W);if(!G)throw new l(i.InvalidParams,"Failed to retrieve task: Task not found");return G},storeTaskResult:async(X,G,J)=>{await Q.storeTaskResult(X,G,J,W);let w=await Q.getTask(X,W);if(w){let Y=s6.parse({method:"notifications/tasks/status",params:w});if(await this.notification(Y),R1(w.status))this._cleanupTaskProgressHandler(X)}},getTaskResult:(X)=>{return Q.getTaskResult(X,W)},updateTaskStatus:async(X,G,J)=>{let w=await Q.getTask(X,W);if(!w)throw new l(i.InvalidParams,`Task "${X}" not found - it may have been cleaned up`);if(R1(w.status))throw new l(i.InvalidParams,`Cannot update task "${X}" from terminal status "${w.status}" to "${G}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(X,G,J,W);let Y=await Q.getTask(X,W);if(Y){let b=s6.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(b),R1(Y.status))this._cleanupTaskProgressHandler(X)}},listTasks:(X)=>{return Q.listTasks(X,W)}}}}function Ew($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Tw($,W){let Q={...$};for(let X in W){let G=X,J=W[G];if(J===void 0)continue;let w=Q[G];if(Ew(w)&&Ew(J))Q[G]={...w,...J};else Q[G]=J}return Q}var JH=RQ(jW(),1),wH=RQ(GH(),1);function Xj(){let $=new JH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return wH.default($),$}class kW{constructor($){this._ajv=$??Xj()}getValidator($){let W="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(Q)=>{if(W(Q))return{valid:!0,data:Q,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(W.errors)}}}}class vW{constructor($){this._server=$}requestStream($,W,Q){return this._server.requestStream($,W,Q)}async getTask($,W){return this._server.getTask({taskId:$},W)}async getTaskResult($,W,Q){return this._server.getTaskResult({taskId:$},W,Q)}async listTasks($,W){return this._server.listTasks($?{cursor:$}:void 0,W)}async cancelTask($,W){return this._server.cancelTask({taskId:$},W)}}function YH($,W,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${W})`);switch(W){case"tools/call":if(!$.tools?.call)throw Error(`${Q} does not support task creation for tools/call (required for ${W})`);break;default:break}}function bH($,W,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${W})`);switch(W){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${Q} does not support task creation for sampling/createMessage (required for ${W})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${Q} does not support task creation for elicitation/create (required for ${W})`);break;default:break}}class _W extends T8{constructor($,W){super(W);if(this._serverInfo=$,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($4.options.map((Q,X)=>[Q,X])),this.isMessageIgnored=(Q,X)=>{let G=this._loggingLevels.get(X);return G?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(G):!1},this._capabilities=W?.capabilities??{},this._instructions=W?.instructions,this._jsonSchemaValidator=W?.jsonSchemaValidator??new kW,this.setRequestHandler(D8,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(F8,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(j8,async(Q,X)=>{let G=X.sessionId||X.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Q.params,w=$4.safeParse(J);if(w.success)this._loggingLevels.set(G,w.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new vW(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Tw(this._capabilities,$)}setRequestHandler($,W){let X=a4($)?.method;if(!X)throw Error("Schema is missing a method literal");let G;if(X6(X)){let w=X;G=w._zod?.def?.value??w.value}else{let w=X;G=w._def?.value??w.value}if(typeof G!=="string")throw Error("Schema method literal must be a string");if(G==="tools/call"){let w=async(Y,b)=>{let H=E1(e6,Y);if(!H.success){let B=H.error instanceof Error?H.error.message:String(H.error);throw new l(i.InvalidParams,`Invalid tools/call request: ${B}`)}let{params:z}=H.data,F=await Promise.resolve(W(Y,b));if(z.task){let B=E1(J6,F);if(!B.success){let K=B.error instanceof Error?B.error.message:String(B.error);throw new l(i.InvalidParams,`Invalid task creation result: ${K}`)}return B.data}let U=E1(B9,F);if(!U.success){let B=U.error instanceof Error?U.error.message:String(U.error);throw new l(i.InvalidParams,`Invalid tools/call result: ${B}`)}return U.data};return super.setRequestHandler($,w)}return super.setRequestHandler($,W)}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${$})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${$})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);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 ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${$})`);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 ${$})`);break;case"ping":case"initialize":break}}assertTaskCapability($){bH(this._clientCapabilities?.tasks?.requests,$,"Client")}assertTaskHandlerCapability($){if(!this._capabilities)return;YH(this._capabilities.tasks?.requests,$,"Server")}async _oninitialize($){let W=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:zw.includes(W)?W:w8,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"},G9)}async createMessage($,W){if($.tools||$.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if($.messages.length>0){let Q=$.messages[$.messages.length-1],X=Array.isArray(Q.content)?Q.content:[Q.content],G=X.some((b)=>b.type==="tool_result"),J=$.messages.length>1?$.messages[$.messages.length-2]:void 0,w=J?Array.isArray(J.content)?J.content:[J.content]:[],Y=w.some((b)=>b.type==="tool_use");if(G){if(X.some((b)=>b.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!Y)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(Y){let b=new Set(w.filter((z)=>z.type==="tool_use").map((z)=>z.id)),H=new Set(X.filter((z)=>z.type==="tool_result").map((z)=>z.toolUseId));if(b.size!==H.size||![...b].every((z)=>H.has(z)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if($.tools)return this.request({method:"sampling/createMessage",params:$},q8,W);return this.request({method:"sampling/createMessage",params:$},M8,W)}async elicitInput($,W){switch($.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let X=$;return this.request({method:"elicitation/create",params:X},L9,W)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let X=$.mode==="form"?$:{...$,mode:"form"},G=await this.request({method:"elicitation/create",params:X},L9,W);if(G.action==="accept"&&G.content&&X.requestedSchema)try{let w=this._jsonSchemaValidator.getValidator(X.requestedSchema)(G.content);if(!w.valid)throw new l(i.InvalidParams,`Elicitation response content does not match requested schema: ${w.errorMessage}`)}catch(J){if(J instanceof l)throw J;throw new l(i.InternalError,`Error validating elicitation response: ${J instanceof Error?J.message:String(J)}`)}return G}}}createElicitationCompletionNotifier($,W){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:$}},W)}async listRoots($,W){return this.request({method:"roots/list",params:$},I8,W)}async sendLoggingMessage($,W){if(this._capabilities.logging){if(!this.isMessageIgnored($.level,W))return this.notification({method:"notifications/message",params:$})}}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}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 HH={name:"@sequenzy/mcp",version:"0.0.150",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",lint:"eslint src","type-check":"bunx --bun 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:"^7.0.2"},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 xW=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],zH={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}",landingPages:"/dashboard/company/{companyId}/landing-pages",landingPage:"/dashboard/company/{companyId}/landing-pages/{landingPageId}",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 Jj($){let Q=($??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return Q.length>0?Q:"https://sequenzy.com"}function e0($){let W=$?.trim();return W?W:void 0}function J1($){return encodeURIComponent($)}function D0($,W){return`${$}${W}`}function F0($,W=""){return`/dashboard/company/${J1($)}${W}`}function DH($,W,Q){return D0($,`${F0(W,"/settings")}?tab=${encodeURIComponent(Q)}`)}function wj($,W){let Q=xW.map((X)=>[X,W?DH($,W,X):""]);return Object.fromEntries(Q)}function A1($={},W){let Q=Jj(W),X=e0($.companyId),G={},J=wj(Q,X);if(!X)return{appUrl:Q,routeTemplates:zH,settingsTabValues:xW,urls:G,settingsUrls:J};G.dashboard=D0(Q,F0(X)),G.campaigns=D0(Q,F0(X,"/campaign")),G.landingPages=D0(Q,F0(X,"/landing-pages")),G.sequences=D0(Q,F0(X,"/sequences")),G.settings=D0(Q,F0(X,"/settings")),G.emails=D0(Q,F0(X,"/emails")),G.subscribers=D0(Q,F0(X,"/subscribers")),G.sentEmails=D0(Q,F0(X,"/sent-emails")),G.segments=D0(Q,F0(X,"/segments")),G.metrics=D0(Q,F0(X,"/metrics")),G.transactional=D0(Q,F0(X,"/transactional"));let w=e0($.campaignId);if(w)G.campaign=D0(Q,F0(X,`/campaign/${J1(w)}`)),G.campaignPreview=`${G.campaign}?step=review`;let Y=e0($.landingPageId);if(Y)G.landingPage=D0(Q,F0(X,`/landing-pages/${J1(Y)}`));let b=e0($.sequenceId);if(b)G.sequence=D0(Q,F0(X,`/sequences/${J1(b)}`));let H=e0($.emailId)??e0($.templateId);if(H)G.email=D0(Q,F0(X,`/emails/${J1(H)}`)),G.template=G.email;let z=e0($.transactionalId);if(z)G.transactionalEmail=D0(Q,F0(X,`/transactional/${J1(z)}`));let F=e0($.emailSendId);if(F)G.emailSend=D0(Q,F0(X,`/sent-emails/${J1(F)}`));let U=e0($.domainId);if(U)G.domain=D0(Q,F0(X,`/settings/domain/${J1(U)}`)),G.domainVerify=`${G.domain}/verify`;let B=e0($.status);if(B)G.campaignList=D0(Q,F0(X,`/campaign/list/${J1(B)}`)),G.sequenceList=D0(Q,F0(X,`/sequences/list/${J1(B)}`));let K=e0($.settingsTab);if(K)G.settingsTab=DH(Q,X,K);return{appUrl:Q,routeTemplates:zH,settingsTabValues:xW,urls:G,settingsUrls:J}}var FH=[{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 UH($){try{let W;switch($){case"sequenzy://dashboard":W=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let Q=await D("GET","/api/v1/account"),X=j1()??Q.currentCompanyId;if(!X)throw Error("No company available. Create or select a company first.");W=await D("GET",`/api/v1/companies/${X}`);break}case"sequenzy://campaigns/recent":W=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":W=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":W=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":W=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":W=await D("GET","/api/v1/templates");break;case"sequenzy://segments":W=await D("GET","/api/v1/segments");break;case"sequenzy://tags":W=await D("GET","/api/v1/tags");break;case"sequenzy://health":W=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://app-routes":W=A1();break;default:throw Error(`Unknown resource: ${$}`)}return{contents:[{uri:$,mimeType:"application/json",text:JSON.stringify(W,null,2)}]}}catch(W){return{contents:[{uri:$,mimeType:"text/plain",text:V1(W)}]}}}function h($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function L($,W){let Q=$[W];if(typeof Q!=="string")return;let X=Q.trim();return X.length>0?X:void 0}function hW($,W,Q){let X=W[Q];if(X===void 0||X===null)return[];if(typeof X==="string"){let J=X.trim();return J.length>0?[J]:[]}if(!Array.isArray(X))throw Error(`\`${Q}\` must be an array of strings when calling \`${$}\`.`);let G=[];return X.forEach((J,w)=>{if(typeof J!=="string")throw Error(`\`${Q}\` item ${w+1} must be a string when calling \`${$}\`.`);let Y=J.trim();if(Y.length>0&&!G.includes(Y))G.push(Y)}),G}function A($,W,Q){let X=L(W,Q);if(X===void 0)throw Error(`\`${Q}\` is required when calling \`${$}\`.`);return X}var $$=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"button","text":"Click Me","url":"https://example.com","variant":"primary"}; {"type":"image","src":"https://...","alt":"Description","width":100,"widthType":"percent","height":240,"objectFit":"cover","href":"https://example.com","align":"center"}. Heading and text use `content`; button uses `text` but also accepts `content` as an alias and defaults `variant` to `primary`. Image `widthType` accepts `percent` or `px`.';var yW=' Any block accepts a `conditions` array so it only renders for matching recipients. To branch on a value passed in transactional `variables` or an automation `event` payload, use { "id": "c1", "field": "variable", "operator": "is", "value": "plan:pro" }; "attribute" uses the same "name:value" form, while "email"/"firstName"/"lastName" use a plain comparison value. Live subscriber fields are "status", "tag", "list", "segment", "event", "emailProvider", "phone", "smsStatus", "added", "stripeProduct", "stripeCurrentProduct", "stripeTrialProduct", "commerceProduct", "commerceCollection", "emailSent", "emailDelivered", "emailOpened", "emailClicked", "emailBounced", and "emailComplained". They use the same field-specific values and operators as segment filters, for example { "id": "c2", "field": "segment", "operator": "is", "value": "seg_123" }, { "id": "c3", "field": "tag", "operator": "contains", "value": "vip" }, or { "id": "c4", "field": "event", "operator": "at_least", "value": "purchase:3:30d" }. Supported operators across fields are is, is_not, contains, not_contains, gt, gte, lt, lte, less_than, more_than, at_least, less_than_count, is_empty, is_not_empty, is_temporary_bounce, and is_permanent_bounce; each field accepts only its segment-filter operators. Recipients without a stored subscriber match use the OTHERWISE branch or hide a conditionally displayed block. For if/else, use a { type: "conditional-group", conditions: [...], ifBranch: { children: [...] }, elseBranch: { children: [...] } } block.',fW=' Polls and NPS surveys use a native poll block. For answer buttons use { "type": "poll", "variant": "options", "question": "What did you think?", "options": [{ "label": "Loved it", "value": "loved" }, { "label": "Not for me", "value": "not_for_me" }], "attributeKey": "email_feedback" }. For NPS use { "type": "poll", "variant": "nps", "question": "How likely are you to recommend us?", "options": [], "attributeKey": "nps_score", "npsLowLabel": "Not likely", "npsHighLabel": "Very likely" }. `attributeKey` stores the latest response for segmentation. Set `allowMultiple: true` on a text-only options poll to let recipients pick several answers: answer links then open a hosted selection page where the recipient checks any number of options and saves them in one submit, and `attributeKey` stores the list of selected values (filter with attribute `contains`). Multi-select polls cannot use option images or configurations whose encoded signed links exceed the delivery-safe size limit. Optional `appearance` picks the answer style: "soft" (default), "pill", "outline", "filled", "pop" (hard-shadow boxes), "brutal" (square uppercase slabs), "quiz" (A/B/C letter badges), or "minimal" (bare ruled rows). `accentColor` recolors every appearance, including "brutal". `optionRadius` sets answer-button corners in px (0 is square) independently of `styles.borderRadius`, while `questionColor` recolors only the question. `fontFamily` applies to the poll; `optionFontSize`, `optionFontWeight`, `optionLetterSpacing`, and `optionTextTransform` style answers, and the matching `questionFontSize`, `questionFontWeight`, `questionLetterSpacing`, and `questionTextTransform` fields style the question. Sizes and spacing are px, weights are 100-900, and transforms are "none" or "uppercase". Optional `confirmationMessage` customizes the hosted thank-you page; set `redirectUrl` only when respondents should land on another page.',uW=' For a new image, call `upload_image_asset` first and insert its returned `imageBlock`. A responsive fixed-height screenshot crop uses { "type": "image", "src": "https://...", "alt": "Product dashboard", "width": 100, "widthType": "percent", "height": 320, "objectFit": "cover", "align": "center" }.',cW="Raw HTML is stored as one opaque block. Sequenzy preserves that markup but does not add a company logo, branded native sections, or theme-driven block design. Use blocks for editor-native design, or a drafting prompt when you want Sequenzy to compose a new branded email.",W$=" Merge tags resolve in this content but are always HTML-escaped; prefix a tag with 'html.' - e.g. {{html.subscriber.body_html}} - to insert a trusted subscriber attribute or variable holding prebuilt HTML unescaped. Injected HTML is sanitized (scripts, event handlers, and dangerous URLs stripped), must be final HTML, and renders raw only in HTML text position, never inside attributes.",U0=`${cW}${W$}`,Q$=' The code is minted per subscriber at run time and reaches every later email in the same sequence as {{discount.code}}. Also available: {{discount.value}} (pre-formatted, e.g. "20% off" or "$10 off"), {{discount.percentOff}}, {{discount.amountOff}}, {{discount.currency}}, and {{date.discount.expiresAt}} (locale-formatted expiry). Present the code with a { "type": "discount-code", "code": "{{discount.code}}", "label": "Your discount code" } block, or inline {{discount.code}} in any text block. These tags resolve only in emails downstream of the discount step; render_email substitutes a clearly fake sample code so the email can be previewed before anyone is enrolled, and lists anything it could not resolve under unresolvedMergeTags.',y1='For exact historical Poll/NPS respondents, use field `pollResponse`, operator `is`, and a JSON value shaped like {"v":1,"campaignId":"camp_123","blockId":"poll_1","match":{"kind":"answer","value":"loved"}}. For NPS buckets, use match {"kind":"npsBucket","bucket":"promoters"}; bucket may be `promoters`, `passives`, or `detractors`.',mW=" `styles` applies to the block's own container, not to an inner rendered element. On a button block, `styles.backgroundColor` colors the band behind the button and `styles.textColor` does not reach the label - set the top-level `buttonColor` and `buttonTextColor` fields instead, or leave them unset to inherit the email theme's primary color.",d1=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",x0=`Sequenzy email blocks. Use this for editor-compatible content, including conditional and repeat blocks. For provider-migrated HTML from another email platform, prefer the \`html\` field instead; Sequenzy stores it as one raw HTML block to preserve the original design. 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\`. Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${W$}${yW}${mW}${d1}${fW}${uW}${$$}`,X$=" Replacing a step's blocks keeps that step's existing Style > Format rather than the company default: a step that already had a logo or footer gets them back even if you omit them, and every block added that way is listed in the response `warnings`. Pass `emailPreset` to change the format. A step whose stored content is a single raw HTML block has no format, so replacing it with another single raw HTML block is stored exactly as sent; replacing it with native blocks converts the step and does add a footer.",Yj=` For action_email:${X$}`,O1=`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\`.${W$}${yW}${mW}${d1}${fW}${uW}${$$}`,K6=`Sequenzy email blocks. Provide blocks or html for email steps. For migrated provider HTML, prefer \`html\`; Sequenzy stores it as one raw HTML block and does not recreate it as native 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\`. Blocks can include repeat blocks over array variables such as items.${W$}${yW}${mW}${d1}${fW}${uW}${$$}`,o1="Display name recipients see, e.g. 'Brennon at TradeTally'. Selects the sender identity of that name on fromEmail, creating it when the address has no identity by that name; the mailbox's other display names, and everything pinned to them, are untouched. Requires fromEmail; omit it when using senderProfileId, which already carries its own display name.",t1="Display name for the Reply-To address. Requires replyTo; omit it when using replyProfileId, which already carries its own display name. An address carries one Reply-To name company-wide: if replyTo already has a saved profile under a different name, that saved name is kept and the response `warnings` array says so. Rename it with update_sender_profile (type 'reply') to change it everywhere.",I4="Complete Sequenzy landing page content JSON. Use this when replacing the page structure. The content must be the editor-compatible landing page schema with version, template, seo, theme, and blocks. Landing pages must include exactly one footer block and at most one form block.",BH="Optional template key for default content, such as from-scratch, waitlist, lead-magnet, launch, demo-request, webinar, newsletter, product-hunt, pricing-offer, agency-lead-gen, or feature-announcement.",lW=500,gW=500,G$=["is","contains","gt","gte","lt","lte","is_not_empty"],h0={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},N4=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],E4=N4.join(", "),J$={type:"object",description:"Optional send window for every email step in the sequence. When set, email actions that become due outside the window wait until the next allowed local time. Omit days to allow every day. Changing the window does not move contacts already waiting on a delay step - they keep their existing wait time, and narrowing the window can defer them to the next allowed day. Call realign_sequence_enrollments after the change to pull those waits back to the new opening.",properties:{enabled:{type:"boolean",description:"Set false to disable the sending window when creating a sequence. For updates, prefer clearSendingWindow."},timezone:{type:"string",description:"IANA timezone for the window, e.g. Europe/Kiev or America/New_York."},startTime:{type:"string",description:"Earliest local send time in 24-hour HH:mm format, e.g. 08:00."},endTime:{type:"string",description:"Latest local send cutoff in 24-hour HH:mm format, e.g. 20:00, or 24:00 for the end-of-day boundary. Must be later than startTime."},days:{type:"array",description:"Allowed local days. Use full names or short names such as monday, tuesday, mon, tue. Omit for every day.",items:{type:"string"}}},additionalProperties:!1},bj={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},Z6={type:"object",description:"Wait until a date from the trigger event before this step. Use this for renewal reminders, appointment follow-ups, trial-expiry nudges, and other subscriber-specific dates. The field value must be an ISO date string or Unix timestamp.",properties:{field:{type:"string",description:"Dot-path into the trigger event properties, e.g. renews_at or booking.startsAt."},untilDateField:{type:"string",description:"Alias for field."},offset:bj,days:{type:"number",description:"Offset days shorthand. Ignored when offset is provided."},hours:{type:"number",description:"Offset hours shorthand. Ignored when offset is provided."},minutes:{type:"number",description:"Offset minutes shorthand. Ignored when offset is provided."},direction:{type:"string",enum:["before","after"],description:"Whether the offset applies before or after the resolved date. Defaults to after."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"Alias for direction."},missingAction:{type:"string",enum:["continue","exit"],description:"What to do if the event field is missing or invalid. Defaults to continue."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"Alias for missingAction."}},additionalProperties:!1},P6={type:"object",description:"Wait until the next occurrence of a weekday inside a local-time window before this step, e.g. { day: 'sunday', startTime: '09:00', endTime: '12:00', timezone: 'America/Los_Angeles' }. Continues immediately when the step is reached inside the window, so a Sunday-morning enrollment is not pushed a full week. Place it immediately before the email when the send day matters - it controls when the flow resumes, so any step between it and the email shifts the send off the window (a sequence-level sendingWindow only holds emails at send time; it does not reschedule the graph).",properties:{day:{type:"string",description:"Single weekday convenience alias for days, e.g. sunday or sun."},days:{type:"array",items:{type:"string"},description:"Weekdays the wait may release on. Full or short names such as sunday, sun. The nearest upcoming day wins."},startTime:{type:"string",description:"Window start in 24-hour HH:mm local time, e.g. 09:00. Required."},endTime:{type:"string",description:"Window end in 24-hour HH:mm local time. Defaults to the end-of-day boundary 24:00. If the wake-up is missed past endTime (rare operational failure), the wait rolls to the next configured day instead of releasing late."},timezone:{type:"string",description:"IANA timezone the window is evaluated in, e.g. America/Los_Angeles. Required."},untilStartTime:{type:"string",description:"Alias for startTime."},untilEndTime:{type:"string",description:"Alias for endTime."},untilTimezone:{type:"string",description:"Alias for timezone."}},additionalProperties:!1},V6={type:"object",description:"Fixed delay before this step. For a dynamic wait-until-date delay, either set mode:'until_date' plus untilDateField here, or use waitUntil. For a wait-until-weekday-window delay, either set mode:'until_weekday' plus untilDays/untilStartTime/untilTimezone here, or use waitUntilWeekday.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"},mode:{type:"string",enum:["duration","until_date","until_weekday"],description:"Use duration for a fixed wait, until_date to resolve a date from the trigger event, or until_weekday to wait for the next weekday/time window."},untilDays:{type:"array",items:{type:"string"},description:"For mode:'until_weekday', weekday names the wait may release on."},untilStartTime:{type:"string",description:"For mode:'until_weekday', window start in 24-hour HH:mm local time."},untilEndTime:{type:"string",description:"For mode:'until_weekday', window end in 24-hour HH:mm local time. Defaults to the end-of-day boundary 24:00."},untilTimezone:{type:"string",description:"For mode:'until_weekday', IANA timezone the window is evaluated in."},untilDateField:{type:"string",description:"For mode:'until_date', dot-path into the trigger event properties."},field:{type:"string",description:"Alias for untilDateField."},untilOffsetDirection:{type:"string",enum:["before","after"],description:"For mode:'until_date', whether days/hours/minutes are before or after the event date. Defaults to after."},direction:{type:"string",enum:["before","after"],description:"Alias for untilOffsetDirection."},untilMissingAction:{type:"string",enum:["continue","exit"],description:"For mode:'until_date', what to do when the field is missing or invalid. Defaults to continue."},missingAction:{type:"string",enum:["continue","exit"],description:"Alias for untilMissingAction."}},additionalProperties:!1},pW={type:"object",description:`Type-aware patch for the existing node. Start from get_sequence.sequence.nodes[].config. For logic_delay, set exactly one of delay ({ days, hours, minutes }), delayMs, waitUntil, or waitUntilWeekday ({ day, startTime, endTime, timezone } - hold until the next weekday window); optional label is also accepted. For action_email, use name/label, subject, previewText, html/htmlContent or blocks, emailPreset, isTransactional, attachments ([{ filename, path }] URL-backed files fetched at send time; path may use {{event.*}} from the enrollment event; [] removes them), and sender/reply identity fields. For action_sms, use text, blocks, imageUrls, label, or ineligibleAction. Other node types accept their editable config keys. For an existing random logic_branch, randomPercentages may be updated with one non-negative value per branch summing to 100. splitMode cannot be converted in place because condition and random splits have different graph topology; build a new random split with insert_sequence_step. Managed IDs, nodeType conversion, and branch path IDs/count are not editable here; use edit_sequence_graph for topology. Webhook header patches are merged, and redacted values from get_sequence must be omitted or replaced with a real new value.${Yj}`,properties:{emailPreset:{type:"string",enum:["branded","minimal"],description:"For an action_email node with native Sequenzy blocks, set the linked email's per-email Style > Format. Native block emails may include supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded to restore branded chrome. This does not change the company-wide default. Not a lossless toggle: minimal deletes standalone logo blocks, so switching back to branded generates a new logo block with a new id and the company name as alt text - send the authored logo block in `blocks` alongside the branded update to keep it. A standalone raw HTML email does not support this field, and emailPreset must not be combined with html/htmlContent."}},additionalProperties:!0},w$={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:pW,expectedUpdatedAt:{type:"string",description:"Required optimistic-concurrency value from get_sequence.sequence.nodes[].updatedAt. The update is rejected if that node or its linked email content changed after it was read."}},required:["nodeId","changes","expectedUpdatedAt"],additionalProperties:!1},j6=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],M6=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","sequence.finished","sequence.failed","poll.answered"];var Hj=new Set(["get_account","get_app_urls","get_company","get_sync_rules","get_shopify_automation_settings","list_api_keys","request_api_key_handoff","list_websites","list_integrations","get_integration","get_integration_pixel","list_integration_capabilities","list_integration_activity","get_event_schema","list_sender_profiles","get_notification_preferences","get_tracking_settings","get_sending_status","check_website","get_integration_guide","get_subscriber","get_subscriber_import","list_subscriber_notes","search_subscribers","list_products","list_tags","list_lists","list_segments","get_segment_count","list_audience_syncs","list_ad_accounts","list_templates","get_template","list_email_components","get_email_component","get_default_email_component","list_ab_tests","get_ab_test","get_ab_test_stats","list_campaigns","get_campaign","get_campaign_audience","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","list_popups","get_popup","get_popup_embed","get_recipient_suppression","list_landing_pages","get_landing_page","list_sequences","get_sequence","list_sequence_enrollments","get_sequence_enrollment_realignment","list_sequence_goals","get_sequence_inbound_webhook","list_transactional_emails","get_transactional_email","get_stats","get_transactional_stats","get_campaign_stats","list_poll_responses","get_sequence_stats","list_campaign_events","list_sequence_events","list_email_metrics","get_subscriber_activity","list_team_members","list_conversations","get_conversation","list_webhooks","list_webhook_deliveries","generate_email","generate_subject_lines","generate_sms","get_sms_settings"]),zj=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","update_sms_number_label","resume_sending","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","sync_integration","activate_integration_pixel","create_api_key","update_api_key","revoke_api_key","delete_api_key","add_sending_domain","add_website","verify_sending_domain","add_subscriber","create_subscriber_import","update_subscriber","add_subscriber_note","remove_subscriber","delete_subscriber_note","trigger_subscriber_event","trigger_subscriber_events","bulk_add_subscriber_tags","bulk_remove_subscriber_tags","upsert_products","delete_product","attach_product_file","remove_product_file","upload_image_asset","sync_products","create_tag","update_tag","delete_tag","create_list","update_list","delete_list","add_subscribers_to_list","remove_subscribers_from_list","create_segment","update_segment","delete_segment","create_audience_sync","update_audience_sync","delete_audience_sync","sync_audience_now","create_template","update_template","set_template_localization","sync_template_localizations","delete_template","create_email_component","update_email_component","set_default_email_component","delete_email_component","restart_ab_test","update_ab_test_variant","update_ab_test","create_ab_test","add_ab_test_variant","delete_ab_test_variant","delete_ab_test","create_campaign","update_campaign","schedule_campaign","send_test_email","send_test_sms","share_campaign","unshare_campaign","share_template","unshare_template","unschedule_campaign","cancel_campaign","pause_campaign","resume_campaign","delete_campaign","duplicate_campaign","resend_campaign_to_non_openers","create_form","update_form","create_popup","update_popup","duplicate_popup","delete_popup","create_landing_page","update_landing_page","duplicate_landing_page","delete_landing_page","publish_landing_page","unpublish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","create_sequence","generate_sequence","send_sequence_test_email","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","duplicate_sequence","archive_sequence","unarchive_sequence","create_sequence_goal","update_sequence_goal","delete_sequence_goal","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","pause_sequence_enrollments","resume_sequence_enrollments","enroll_subscribers_in_sequence","cancel_sequence_enrollments","move_sequence_enrollments","realign_sequence_enrollments","delete_sequence","create_transactional_email","update_transactional_email","delete_transactional_email","send_email","invite_team_member","cancel_team_invitation","reply_to_conversation","update_conversation_status","mark_conversation_read","create_webhook","update_webhook","delete_webhook","test_webhook","replay_webhook_delivery","submit_feedback","remove_recipient_suppression"]),Dj=new Set(["send_test_email","send_test_sms","send_sequence_test_email","schedule_campaign","resume_campaign","publish_landing_page","connect_landing_page_domain","update_landing_page_domain_settings","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","enable_sequence","unarchive_sequence","resume_sequence_enrollments","move_sequence_enrollments","send_email","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),Fj=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","remove_product_file","delete_tag","delete_list","remove_subscribers_from_list","bulk_remove_subscriber_tags","delete_segment","delete_audience_sync","delete_template","delete_email_component","restart_ab_test","delete_ab_test_variant","delete_ab_test","cancel_campaign","delete_campaign","delete_landing_page","unpublish_landing_page","delete_popup","set_integration_sync_enabled","disable_sequence","archive_sequence","delete_sequence_goal","rotate_sequence_inbound_webhook_secret","edit_sequence_graph","cancel_sequence_enrollments","move_sequence_enrollments","realign_sequence_enrollments","delete_sequence","cancel_team_invitation","delete_webhook","delete_transactional_email","remove_recipient_suppression","unshare_campaign","unshare_template"]);function Uj($){let W=Hj.has($),Q=zj.has($);if(W===Q)throw Error(`MCP tool "${$}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:W,destructiveHint:W?!1:Fj.has($),openWorldHint:Dj.has($)}}function LH($){return{...$,annotations:{...$.annotations,...Uj($.name)}}}var iW={status:["is","is_not"],phone:["is_not_empty","is_empty"],smsStatus:["is","is_not"],tag:["contains","not_contains","is_empty","is_not_empty"],email:["contains","not_contains","is","is_not"],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"],pollResponse:["is"],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"],commerceProduct:["is","is_not","at_least","less_than_count"],commerceCollection:["is","is_not","at_least","less_than_count"]},Bj=Object.entries(iW).map(([$,W])=>`${$}: ${W.join(", ")}`).join("; "),nW={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","phone","smsStatus","tag","email","emailProvider","added","firstName","lastName","list","emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained","attribute","event","pollResponse","segment","stripeProduct","stripeCurrentProduct","stripeTrialProduct","commerceProduct","commerceCollection"],description:`Filter field. Use \`email\` with is/is_not for exact, case-insensitive address matching (allowlists and exclusions) and with contains/not_contains for domain or substring matching. Use \`phone\` with is_not_empty/is_empty to check whether a subscriber has a phone number, and \`smsStatus\` (is/is_not one of \`subscribed\`, \`unsubscribed\`, \`not_subscribed\`) for SMS marketing consent. Use \`event\` for custom subscriber events, \`segment\` for saved segment membership, \`stripeProduct\`/\`stripeCurrentProduct\`/\`stripeTrialProduct\` for Stripe product-based segments, and \`commerceProduct\` for products purchased through commerce orders - the value is \`provider:productId\` (provider one of \`shopify\`, \`woocommerce\`, \`api\`; product ids are provider-scoped), optionally with an order-count threshold (\`provider:productId:count\`) for at_least/less_than_count; a bare product id matches the id on any provider. Use \`commerceCollection\` to segment on anyone who bought ANY product in a store collection - the value is the collection id or handle (e.g. \`skincare\`), optionally provider-prefixed and/or with an order-count threshold (\`shopify:skincare:2\`); collection membership is resolved from the synced catalog as it stands now, and only Shopify collections and WooCommerce categories are synced. Engagement fields (\`emailSent\`, \`emailDelivered\`, \`emailOpened\`, \`emailClicked\`, \`emailBounced\`, \`emailComplained\`) accept a time range as the value, a specific campaign via \`campaign:<campaign_id>\`, or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${y1}`},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: ${Bj}.`},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, \`campaign:<campaign_id>\` to scope to a specific sent campaign (use \`list_campaigns\` to find IDs), or \`count:timeRange\` like \`10:30d\` / \`10:all\` with at_least/less_than_count operators (e.g. emailClicked at_least \`10:all\` = clicked 10 or more times ever). ${y1}`}},required:["field","operator","value"],additionalProperties:!1},dW={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 Y$($){if(!Array.isArray($))return $;return $.map((W)=>{if(typeof W!=="object"||W===null)return W;let Q=W;if(typeof Q.id==="string"&&Q.id.trim()!=="")return Q;return{...Q,id:crypto.randomUUID()}})}function b$($){if(typeof $!=="object"||$===null)return $;let W=$;if(W.kind==="filter"||"field"in W||"operator"in W||"value"in W){let Q=Y$([W]);return Array.isArray(Q)?Q[0]:W}if(W.kind!=="group")return $;return{...W,id:typeof W.id==="string"&&W.id.trim()!==""?W.id:crypto.randomUUID(),children:Array.isArray(W.children)?W.children.map(b$):[]}}function Lj($){let W=$.indexOf(":");return W!==-1&&$.substring(0,W).trim().length>0}function Aj($){let W=$.indexOf(":");return W!==-1&&$.substring(W+1).trim().length>0}function AH($){if($==="all")return!0;let W=$.match(/^(\d+)d$/);if(!W?.[1])return!1;let Q=Number.parseInt(W[1],10);return Number.isInteger(Q)&&Q>0}function Oj($,W){let Q=W.split(":");if($==="at_least"||$==="less_than_count"){if(Q.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let J=Q.slice(0,-2).join(":").trim(),w=Q.at(-2),Y=Q.at(-1),b=w===void 0?Number.NaN:Number.parseInt(w,10);return J&&Number.isInteger(b)&&b>0&&Y!==void 0&&AH(Y)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(Q.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let X=Q.slice(0,-1).join(":").trim(),G=Q.at(-1);return X&&G!==void 0&&AH(G)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function Kj($){let W=$.indexOf(":");if(W===-1)return{productId:$,subfilter:null,rawValue:null};let Q=$.substring(0,W),X=$.substring(W+1),G=X.indexOf(":");if(G===-1)return{productId:Q,subfilter:X,rawValue:null};return{productId:Q,subfilter:X.substring(0,G),rawValue:X.substring(G+1)}}function Zj($){return $.trim().toLowerCase().replace(/[-\s]+/g,"_")}function Pj($){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($)}function Vj($,W){if(W==="cancels_at"||W==="cancel_at"||W==="cancellation_at")return!0;if($==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(W);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(W)}function jj($){return["is","is_not","gte","lte","gt","lt"].includes($)}function Mj($,W,Q){if($==="stripeProduct"){if(W!=="at_least"&&W!=="less_than_count")return null;let Y=Q.indexOf(":");if(Y===-1)return null;let b=Q.substring(0,Y).trim(),H=Number.parseInt(Q.substring(Y+1).trim(),10);return b&&Number.isInteger(H)&&H>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if($!=="stripeCurrentProduct"&&$!=="stripeTrialProduct")return null;let{productId:X,subfilter:G,rawValue:J}=Kj(Q);if(!X.trim())return"Stripe product filters must include a product ID.";if(!G)return W==="is"||W==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let w=Zj(G);if(Pj(w))return W==="is"||W==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!Vj($,w))return`Unsupported Stripe product subfilter "${G}".`;if(!jj(W))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return J?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var OH=new Set(["shopify","woocommerce","api"]);function qj($,W){let Q=W.trim(),X=Q.indexOf(":");if(X!==-1&&OH.has(Q.substring(0,X).trim()))Q=Q.substring(X+1).trim();if(!Q)return'Purchased Product filters must include a product ID, like "shopify:42".';if($!=="at_least"&&$!=="less_than_count")return null;let G=Q.lastIndexOf(":");if(G===-1)return null;let J=Q.substring(0,G).trim(),w=Number.parseInt(Q.substring(G+1).trim(),10);return J&&Number.isInteger(w)&&w>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function Ij($,W){let Q=W.trim(),X=Q.indexOf(":");if(X!==-1&&OH.has(Q.substring(0,X).trim()))Q=Q.substring(X+1).trim();if(!Q)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if($!=="at_least"&&$!=="less_than_count")return null;let G=Q.lastIndexOf(":");if(G===-1)return null;let J=Q.substring(0,G).trim(),w=Number.parseInt(Q.substring(G+1).trim(),10);return J&&Number.isInteger(w)&&w>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function Nj($){let W;try{W=JSON.parse($)}catch{return`Poll response filters must use valid JSON. ${y1}`}if(!h(W)||W.v!==1||typeof W.campaignId!=="string"||!W.campaignId.trim()||typeof W.blockId!=="string"||!W.blockId.trim()||!h(W.match))return`Poll response filter context is invalid. ${y1}`;let Q=W.match;if(Q.kind==="answer"&&typeof Q.value==="string"&&Q.value.length>0)return null;if(Q.kind==="npsBucket"&&(Q.bucket==="promoters"||Q.bucket==="passives"||Q.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${y1}`}function H$($){if(typeof $!=="object"||$===null)return"Segment filters must be objects.";let W=$,Q=W.field,X=W.operator,G=W.value;if(typeof Q!=="string"||!(Q in iW))return`Unsupported segment filter field "${String(Q)}".`;if(typeof X!=="string")return`Segment filter "${Q}" must include an operator.`;let J=iW[Q];if(!J.includes(X))return`Operator "${X}" is not supported for ${Q} filters. Use one of: ${J.join(", ")}.`;if(X!=="is_empty"&&X!=="is_not_empty"&&(typeof G!=="string"||G.trim().length===0))return`Segment filter "${Q}" must include a value.`;if(Q==="attribute"){if(typeof G!=="string")return'Attribute filters must include a value: "attributeName:value", or "attributeName:" for empty checks.';if(!Lj(G))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(X!=="is_empty"&&X!=="is_not_empty"&&!Aj(G))return'Attribute filters must include a value after "attributeName:".'}if(Q==="event"&&typeof G==="string"){let w=Oj(X,G);if(w)return w}if(Q==="pollResponse"&&typeof G==="string"){let w=Nj(G);if(w)return w}if((Q==="stripeProduct"||Q==="stripeCurrentProduct"||Q==="stripeTrialProduct")&&typeof G==="string"){let w=Mj(Q,X,G);if(w)return w}if(Q==="commerceProduct"&&typeof G==="string"){let w=qj(X,G);if(w)return w}if(Q==="commerceCollection"&&typeof G==="string"){let w=Ij(X,G);if(w)return w}if(Q==="tag"&&(X==="contains"||X==="not_contains")){if(!(typeof G==="string"&&G.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function z$($){if(typeof $!=="object"||$===null)return[];let W=$;if(W.kind==="filter"||"field"in W||"operator"in W||"value"in W){let Q=H$(W);return Q?[Q]:[]}if(Array.isArray(W.children))return W.children.flatMap(z$);return[]}function y0($,W,Q){if(W.html!==void 0&&W.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${$}\`, not both.`);if(W.blocks!==void 0&&!Array.isArray(W.blocks))throw Error(`\`blocks\` must be an array when calling \`${$}\`.`);if(Q?.requireContent&&W.html===void 0&&W.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${$}\`.`)}function K1($,W){if(W.labels===void 0)return;if(!Array.isArray(W.labels))throw Error(`\`labels\` must be an array when calling \`${$}\`.`);if(W.labels.some((Q)=>typeof Q!=="string"||Q.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${$}\`.`)}function PH($){let W=$.filters!==void 0,Q=$.root!==void 0;if(W&&Q)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!W&&!Q)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(W){if(!Array.isArray($.filters))throw Error("`filters` must be an array when calling `create_segment`.");if($.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(Q&&(typeof $.root!=="object"||$.root===null))throw Error("`root` must be an object when calling `create_segment`.");let X=W?$.filters.flatMap((G)=>{let J=H$(G);return J?[J]:[]}):z$($.root);if(X.length>0)throw Error(X[0]??"Invalid segment filter in `create_segment`.")}function VH($){let W=$.filters!==void 0,Q=$.root!==void 0;if(W&&Q)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if($.name===void 0&&$.filterJoinOperator===void 0&&!W&&!Q)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(W){if(!Array.isArray($.filters))throw Error("`filters` must be an array when calling `update_segment`.");if($.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(Q&&(typeof $.root!=="object"||$.root===null))throw Error("`root` must be an object when calling `update_segment`.");let X=W?$.filters.flatMap((G)=>{let J=H$(G);return J?[J]:[]}):Q?z$($.root):[];if(X.length>0)throw Error(X[0]??"Invalid segment filter in `update_segment`.")}var oW=["name","description","logoUrl","founderName","primaryColor","brandColors","valueProps","testimonials","toneVoice","companyContext","emailDesignPrompt","emailLengthPreference","socialLinks","privacyPolicyUrl","termsUrl","address","language","pricing","fontFamily","emailTheme","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingEnabled","replyTrackingDomainMode","forwardReplies"];function tW($,W,Q){if(W[Q]!==void 0&&!h(W[Q]))throw Error(`\`${Q}\` must be an object when calling \`${$}\`.`)}function KH($,W,Q){if(W[Q]!==void 0&&!Array.isArray(W[Q]))throw Error(`\`${Q}\` must be an array when calling \`${$}\`.`)}function jH($){let W=new Set(["companyId",...oW]),Q=Object.keys($).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);let X={};for(let G of oW)if($[G]!==void 0)X[G]=$[G];if(Object.keys(X).length===0)throw Error(`Provide at least one of ${oW.map((G)=>`\`${G}\``).join(", ")} when calling \`update_company\`.`);for(let G of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailDesignPrompt","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if($[G]!==void 0&&typeof $[G]!=="string")throw Error(`\`${G}\` must be a string when calling \`update_company\`.`);if(tW("update_company",$,"brandColors"),tW("update_company",$,"socialLinks"),tW("update_company",$,"pricing"),$.emailTheme!==void 0&&$.emailTheme!==null&&!h($.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");KH("update_company",$,"valueProps"),KH("update_company",$,"testimonials");for(let G of["replyTrackingEnabled","forwardReplies"])if($[G]!==void 0&&typeof $[G]!=="boolean")throw Error(`\`${G}\` must be a boolean when calling \`update_company\`.`);if($.replyTrackingDomainMode!==void 0&&$.replyTrackingDomainMode!=="sequenzy"&&$.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof $.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test($.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let G of["fromEmail","replyTo"]){let J=$[G];if(typeof J==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(J.trim()))throw Error(`\`${G}\` must be a valid email address when calling \`update_company\`.`)}return X}var rW=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],sW=["source","medium","campaign","content","term"];function MH($){let W=new Set(["companyId",...rW]),Q=Object.keys($).filter((G)=>!W.has(G));if(Q.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let X={};for(let G of rW)if($[G]!==void 0)X[G]=$[G];if(Object.keys(X).length===0)throw Error(`Provide at least one of ${rW.map((G)=>`\`${G}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let G of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if($[G]!==void 0&&typeof $[G]!=="boolean")throw Error(`\`${G}\` must be a boolean when calling \`update_tracking_settings\`.`);if($.defaultAttributionWindowHours!==void 0&&(typeof $.defaultAttributionWindowHours!=="number"||!Number.isInteger($.defaultAttributionWindowHours)||$.defaultAttributionWindowHours<1||$.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if($.autoUtmSettings!==void 0&&$.autoUtmSettings!==null&&!h($.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(h($.autoUtmSettings)){let G=$.autoUtmSettings,J=Object.keys(G).filter((w)=>!sW.includes(w));if(J.length>0)throw Error(`\`autoUtmSettings\` accepts only ${sW.map((w)=>`\`${w}\``).join(", ")}. Unsupported: ${J.map((w)=>`\`${w}\``).join(", ")}.`);for(let w of sW){let Y=G[w];if(Y!==void 0&&Y!==null&&typeof Y!=="string")throw Error(`\`autoUtmSettings.${w}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return X}var eW={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},$Q={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function WQ($){let{profileKey:W,emailKey:Q,nameKey:X,addressLabel:G}=$.pair,J=$.args[W]!==void 0,w=$.args[Q]!==void 0,Y=$.args[X]!==void 0,b=$.location?`for ${$.location} when calling \`${$.toolName}\``:`when calling \`${$.toolName}\``,H=`\`${W}\` already sets both the ${G} address and the display name, so send it without \`${Q}\`${$.nameIsOverride?"":` and \`${X}\``}.`;if(J&&w){let[z,F]=$.profileFirst?[W,Q]:[Q,W];throw Error(`Provide either \`${z}\` or \`${F}\` ${b}, not both. ${H}`)}if(J&&Y&&!$.nameIsOverride)throw Error(`\`${X}\` cannot be combined with \`${W}\` ${b}. ${H}`);if(Y&&!w&&!$.nameIsOverride)throw Error(`\`${X}\` requires \`${Q}\` ${b}. Send \`${X}\` with the \`${Q}\` it names, or send \`${W}\` on its own to use an existing profile's address and name.`)}function q6($,W,Q){let X=Q?.replyFirst?[$Q,eW]:[eW,$Q];for(let G of X)WQ({toolName:$,args:W,pair:G})}var qH=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function Ej($){return qH.some((W)=>$[W]!==void 0)}function Tj($){if(typeof $.nodeType==="string")return $.nodeType==="action_email";return $.type===void 0||$.type==="email"}function D$($,W,Q){for(let X of qH){let G=Q[X];if(G!==void 0&&typeof G!=="string")throw Error(`\`${X}\` must be a string for ${W} when calling \`${$}\`.`)}WQ({toolName:$,args:Q,pair:eW,location:W,profileFirst:!0,nameIsOverride:!0}),WQ({toolName:$,args:Q,pair:$Q,location:W,profileFirst:!0})}function QQ($,W,Q){if(Ej(Q)&&!Tj(Q))throw Error(`Sender identity fields are only supported for email steps at ${W} when calling \`${$}\`.`);D$($,W,Q)}function ZH($,W,Q){if(!Array.isArray(Q))return;Q.forEach((X,G)=>{if(h(X))D$($,`${W}[${G}]`,X)})}function aW($,W,Q){if(!Array.isArray(Q))return;Q.forEach((X,G)=>{if(h(X))QQ($,`${W}[${G}]`,X)})}function Rj($){if(ZH("update_sequence","emails",$.emails),ZH("update_sequence","steps",$.steps),h($.insertSteps))aW("update_sequence","insertSteps.steps",$.insertSteps.steps);if(!h($.branch))return;if(Array.isArray($.branch.branches))$.branch.branches.forEach((Q,X)=>{if(h(Q))aW("update_sequence",`branch.branches[${X}].steps`,Q.steps)});aW("update_sequence","branch.elseSteps",$.branch.elseSteps)}function IH($){K1("update_sequence",$);let W=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if($.trigger===void 0&&W.some((X)=>$[X]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(q6("update_sequence",$),$.clearEnrollmentFieldPath===!0&&$.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if($.clearSendingWindow===!0&&$.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if($.clearBccEmails===!0&&$.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if($.branch!==void 0&&$.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");Rj($);let Q={...$};if(delete Q.clearEnrollmentFieldPath,delete Q.clearSendingWindow,delete Q.clearBccEmails,$.clearEnrollmentFieldPath===!0)Q.enrollmentFieldPath=null;if($.clearSendingWindow===!0)Q.sendingWindow=null;if($.clearBccEmails===!0)Q.bccEmails=null;return Q}function Sj($,W){if((W.triggerType??"event")==="event"){if(typeof W.triggerEventName!=="string"||W.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${$}\` with an event goal (the default \`triggerType\`).`);return}if(typeof W.attributePath!=="string"||W.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${$}\` with \`triggerType: "attribute_change"\`.`);let X=W.attributeCondition??"changed",G=typeof W.attributeValue==="string"&&W.attributeValue.trim().length>0,J=typeof W.attributePreviousValue==="string"&&W.attributePreviousValue.trim().length>0;if((X==="changed_to"||X==="changed_from_to")&&!G)throw Error(`\`attributeValue\` is required when calling \`${$}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(X==="changed_from_to"&&!J)throw Error(`\`attributePreviousValue\` is required when calling \`${$}\` with \`attributeCondition: "changed_from_to"\`.`)}function NH($){Sj("create_sequence_goal",$)}function EH($){if(typeof $.triggerEventName==="string"&&$.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof $.attributePath==="string"&&$.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function vH($,W,Q){let X=A($,W,"nodeId");if(!h(W.changes)||Object.keys(W.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${Q} when calling \`${$}\`.`);let G=A($,W,"expectedUpdatedAt");return{nodeId:X,changes:W.changes,expectedUpdatedAt:G}}function _H($){let W=vH("update_sequence_node",$,"the node update");return{...$.confirmLiveChange!==void 0&&{confirmLiveChange:$.confirmLiveChange},nodeUpdates:[W]}}function xH($){if(!Array.isArray($.updates)||$.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let W=new Set,Q=$.updates.map((X,G)=>{if(!h(X))throw Error(`\`updates[${G}]\` must be an object when calling \`update_sequence_nodes\`.`);let J=vH("update_sequence_nodes",X,`updates[${G}]`),w=String(J.nodeId);if(W.has(w))throw Error(`\`updates[${G}]\` targets duplicate nodeId '${w}' when calling \`update_sequence_nodes\`.`);return W.add(w),J});return{...$.confirmLiveChange!==void 0&&{confirmLiveChange:$.confirmLiveChange},nodeUpdates:Q}}function hH($){let W=A("edit_sequence_graph",$,"action"),Q=A("edit_sequence_graph",$,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(W))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let G=L($,"nodeId"),J=L($,"afterNodeId"),w=L($,"beforeNodeId"),Y=$.edges;if(W!=="replace_edges"&&!G)throw Error(`\`nodeId\` is required for ${W} when calling \`edit_sequence_graph\`.`);if(W==="replace_edges"&&G)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let b=W==="move_node"||W==="duplicate_node";if(b&&(J?1:0)+(w?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${W} when calling \`edit_sequence_graph\`.`);if(!b&&(J||w))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${W} when calling \`edit_sequence_graph\`.`);if((W==="replace_edges"||W==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${W} when calling \`edit_sequence_graph\`.`);if((W==="move_node"||W==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${W} when calling \`edit_sequence_graph\`.`);let H=Array.isArray(Y)?Y.map((z,F)=>{if(!h(z))throw Error(`\`edges\` item ${F+1} must be an object when calling \`edit_sequence_graph\`.`);let U=A("edit_sequence_graph",z,"sourceNodeId"),B=A("edit_sequence_graph",z,"targetNodeId");if(z.condition!==void 0&&z.condition!==null&&!h(z.condition))throw Error(`\`edges\` item ${F+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:U,targetNodeId:B,...h(z.condition)?{condition:z.condition}:{}}}):void 0;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},graphEdit:{action:W,expectedRevision:Q,...G?{nodeId:G}:{},...J?{afterNodeId:J}:{},...w?{beforeNodeId:w}:{},...H?{edges:H}:{}}}}function Cj($,W,Q){if(($==="has_tag"||$==="does_not_have_tag")&&!L(W,"tagId")&&!L(W,"tagName"))throw Error(`\`${Q}\` must provide \`tagId\` or \`tagName\` for ${$} when calling \`insert_sequence_step\`.`);if($==="in_list"&&!L(W,"listId"))throw Error(`\`${Q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if($==="in_segment"&&!L(W,"segmentId"))throw Error(`\`${Q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if($==="event_received"&&!L(W,"eventName"))throw Error(`\`${Q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if($.startsWith("field_")&&(!L(W,"fieldName")||!L(W,"fieldValue")))throw Error(`\`${Q}\` must provide \`fieldName\` and \`fieldValue\` for ${$} when calling \`insert_sequence_step\`.`)}var kj=["conditionType","tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"];function yH($){let W=L($,"type")??"email";if(!new Set(["email","sms","delay","create_discount","update_subscriber","condition","add_tag","remove_tag","add_to_list","remove_from_list","webhook","ai","logic_wait_for_event","logic_branch"]).has(W))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(W==="logic_wait_for_event"){let w=A("insert_sequence_step",$,"eventName"),Y=$.timeoutDays,b=Y===void 0?7:Y;if(typeof b!=="number"||!Number.isInteger(b)||b<1||b>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let H=L($,"timeoutAction")??"continue";if(H!=="continue"&&H!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let z={steps:[{nodeType:"logic_wait_for_event",config:{label:L($,"label")??`Wait for ${w}`,eventName:w,timeoutDays:b,timeoutAction:H}}]},F=L($,"afterNodeId");if(F)z.afterNodeId=F;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},insertSteps:z}}if(W==="logic_branch"){let w=A("insert_sequence_step",$,"afterNodeId");if(!Array.isArray($.branches)||$.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let Y=new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]),b=L($,"splitMode")??"condition";if(b!=="condition"&&b!=="random")throw Error("`splitMode` must be `condition` or `random` when inserting `logic_branch` with `insert_sequence_step`.");let H=b==="random";if(H){if(!Array.isArray($.randomPercentages)||$.randomPercentages.length!==$.branches.length)throw Error("`randomPercentages` must contain one percentage per entry in `branches` when `splitMode` is `random`.");if($.randomPercentages.some((q)=>typeof q!=="number"||!Number.isFinite(q)||q<0))throw Error("`randomPercentages` must contain non-negative numbers when `splitMode` is `random`.");let P=$.randomPercentages.reduce((q,M)=>q+M,0);if(Math.abs(P-100)>0.001)throw Error(`\`randomPercentages\` must sum to 100 when \`splitMode\` is \`random\`, received ${P}.`);if(Array.isArray($.elseSteps)&&$.elseSteps.length>0||L($,"elseTargetNodeId"))throw Error("`elseSteps` and `elseTargetNodeId` are not valid when `splitMode` is `random`. Every path is weighted by `randomPercentages`, so add another entry to `branches` instead.")}else if($.randomPercentages!==void 0)throw Error("`randomPercentages` is only valid when `splitMode` is `random`.");let z=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],F=$.allowEmptyPaths===!0,U=$.branches.map((P,q)=>{if(!h(P))throw Error(`\`branches[${q}]\` must be an object when calling \`insert_sequence_step\`.`);let M=`branches[${q}]`;if(H){let v=kj.find((k)=>P[k]!==void 0);if(v)throw Error(`\`${M}.${v}\` must be omitted when \`splitMode\` is \`random\`, because the path is chosen by percentage rather than by evaluating the subscriber.`)}else{let v=A("insert_sequence_step",P,"conditionType");if(!Y.has(v))throw Error(`\`branches[${q}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);Cj(v,P,M)}if(P.steps!==void 0&&!Array.isArray(P.steps))throw Error(`\`branches[${q}].steps\` must be an array when calling \`insert_sequence_step\`.`);let S=L(P,"targetNodeId"),C=Array.isArray(P.steps)&&P.steps.length>0;if(!S&&!C&&!F)throw Error(`\`branches[${q}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(z.flatMap((v)=>P[v]===void 0?[]:[[v,P[v]]]))});if($.elseSteps!==void 0&&!Array.isArray($.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let B=L($,"elseTargetNodeId"),K=Array.isArray($.elseSteps)&&$.elseSteps.length>0;if(!H&&!B&&!K&&!F)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},branch:{afterNodeId:w,...L($,"label")?{label:L($,"label")}:{},...H?{splitMode:b,randomPercentages:$.randomPercentages}:{},branches:U,...Array.isArray($.elseSteps)?{elseSteps:$.elseSteps}:{},...B?{elseTargetNodeId:B}:{},...F?{allowEmptyPaths:!0}:{}}}}if(W==="delay"||W==="create_discount"||W==="update_subscriber"||W==="condition"||W==="add_tag"||W==="remove_tag"||W==="add_to_list"||W==="remove_from_list"||W==="webhook"||W==="ai"){let w;if(W==="delay"){w={type:"delay"};for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if($[H]!==void 0)w[H]=$[H];if(w.delay===void 0&&w.delayMs===void 0&&w.waitUntil===void 0&&w.waitUntilWeekday===void 0)throw Error("Provide `delay`, `delayMs`, `waitUntil`, or `waitUntilWeekday` when inserting a delay step.")}else if(W==="create_discount"){w={type:"create_discount"};for(let H of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if($[H]!==void 0)w[H]=$[H]}else if(W==="update_subscriber"){if(!h($.config))throw Error("`config` is required when inserting an update_subscriber step.");w={type:"update_subscriber",nodeType:"action_update_attributes",config:$.config}}else if(W==="webhook"){let H=L($,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(H))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if($.headers!==void 0&&(!h($.headers)||Object.values($.headers).some((B)=>typeof B!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=L($,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if($.body!==void 0&&typeof $.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if($.resultKey!==void 0&&typeof $.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let F=L($,"body"),U=L($,"resultKey");w={type:"webhook",nodeType:"action_webhook",config:{label:L($,"label")??"Webhook",url:A("insert_sequence_step",$,"url"),method:H,...$.headers!==void 0?{headers:$.headers}:{},...F?{body:F}:{},...U?{resultKey:U}:{},...z?{onError:z}:{}}}}else if(W==="ai"){let H=L($,"onError");if(H&&!["continue","exit","fail"].includes(H))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting an ai step.");if(!Array.isArray($.outputFields)||$.outputFields.length===0)throw Error("`outputFields` is required when inserting an ai step, e.g. [{ key: 'subject_line', fallback: 'We miss you' }].");if($.includeAttributes!==void 0){if(!Array.isArray($.includeAttributes)||$.includeAttributes.some((z)=>typeof z!=="string"))throw Error("`includeAttributes` must be an array of attribute names when inserting an ai step.")}if($.recentEventLimit!==void 0&&typeof $.recentEventLimit!=="number")throw Error("`recentEventLimit` must be a number between 1 and 50 when inserting an ai step.");w={type:"ai",nodeType:"action_ai",config:{label:L($,"label")??"Ask AI",prompt:A("insert_sequence_step",$,"prompt"),resultKey:A("insert_sequence_step",$,"resultKey"),outputFields:$.outputFields,...$.includeTags!==void 0?{includeTags:$.includeTags===!0}:{},...$.includeEventProperties!==void 0?{includeEventProperties:$.includeEventProperties===!0}:{},...$.includeRecentEvents!==void 0?{includeRecentEvents:$.includeRecentEvents===!0}:{},...$.recentEventLimit!==void 0?{recentEventLimit:$.recentEventLimit}:{},...$.includeAttributes!==void 0?{includeAttributes:$.includeAttributes}:{},...H?{onError:H}:{}}}}else if(W==="condition"){let H=A("insert_sequence_step",$,"conditionType");if(!new Set(["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"]).has(H))throw Error("`conditionType` is not supported for condition steps.");if((H==="has_tag"||H==="does_not_have_tag")&&!L($,"tagId")&&!L($,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!L($,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!L($,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!L($,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!L($,"fieldName")||!L($,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let F={label:L($,"label")??"Condition",conditionType:H};for(let U of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if($[U]!==void 0)F[U]=$[U];w={type:"condition",nodeType:"logic_condition",config:F}}else{let H=W==="add_tag"||W==="remove_tag",z=W==="add_tag"?"action_add_tag":W==="remove_tag"?"action_remove_tag":W==="add_to_list"?"action_add_to_list":"action_remove_from_list",F={label:L($,"label")??(W==="add_tag"?"Add Tag":W==="remove_tag"?"Remove Tag":W==="add_to_list"?"Add to List":"Remove from List")};if(H){let U=L($,"tagId"),B=L($,"tagName");if(!U&&!B)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(U)F.tagId=U;if(B)F.tagName=B}else{F.listId=A("insert_sequence_step",$,"listId");let U=L($,"listName");if(U)F.listName=U}w={nodeType:z,config:F}}for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if(W!=="delay"&&$[H]!==void 0)w[H]=$[H];let Y={steps:[w]},b=L($,"afterNodeId");if(b)Y.afterNodeId=b;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},insertSteps:Y}}let X=W==="sms",G;if(X){QQ("insert_sequence_step","SMS step",$);let w=L($,"text"),Y=Array.isArray($.blocks)&&$.blocks.length>0;if(w===void 0&&!Y)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");G={type:"sms"};for(let b of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil","waitUntilWeekday"])if($[b]!==void 0)G[b]=$[b]}else{y0("insert_sequence_step",$,{requireContent:!0}),D$("insert_sequence_step","email step",$),G={subject:A("insert_sequence_step",$,"subject")};for(let w of["name","previewText","html","blocks","delay","delayMs","waitUntil","waitUntilWeekday","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if($[w]!==void 0)G[w]=$[w]}let J={steps:[G]};if($.afterNodeId!==void 0)J.afterNodeId=$.afterNodeId;return{...$.confirmStructuralChange!==void 0&&{confirmStructuralChange:$.confirmStructuralChange},insertSteps:J}}function TH($,W){let Q=$[W];if(Q===void 0)return[];if(!Array.isArray(Q))throw Error(`\`${W}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let X=Q.map((G)=>typeof G==="string"?G.trim():"").filter((G)=>G.length>0);if(Q.some((G)=>typeof G!=="string")||X.length===0)throw Error(`\`${W}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return X}function RH($,W){let Q=$[W];if(Q===void 0)return[];if(!Array.isArray(Q))throw Error(`\`${W}\` must be an array when calling \`realign_sequence_enrollments\`.`);let X=Q.map((G)=>typeof G==="string"?G.trim():"").filter((G)=>G.length>0);if(Q.some((G)=>typeof G!=="string")||X.length===0)throw Error(`\`${W}\` must contain at least one non-empty string when calling \`realign_sequence_enrollments\`.`);return X}function fH($){let W=RH($,"nodeIds"),Q=RH($,"subscriberIds"),X=L($,"cursor");if($.dryRun!==void 0&&typeof $.dryRun!=="boolean")throw Error("`dryRun` must be a boolean when calling `realign_sequence_enrollments`.");return{...W.length>0&&{nodeIds:W},...Q.length>0&&{subscriberIds:Q},...X!==void 0&&{cursor:X},...typeof $.dryRun==="boolean"&&{dryRun:$.dryRun}}}function uH($){let W=L($,"subscriberId"),Q=TH($,"subscriberIds"),X=TH($,"fieldValues");if($.cancelAll!==void 0&&typeof $.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let G=$.cancelAll===!0;if((W!==void 0?1:0)+(Q.length>0?1:0)+(X.length>0?1:0)+(G?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let w=L($,"fieldPath"),Y=L($,"reason");return{...G&&{cancelAll:!0},...W!==void 0&&{subscriberId:W},...Q.length>0&&{subscriberIds:Q},...w!==void 0&&{fieldPath:w},...X.length>0&&{fieldValues:X},...typeof $.dryRun==="boolean"&&{dryRun:$.dryRun},...Y!==void 0&&{reason:Y}}}var SH=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function CH($,W){let Q=$[W];if(Q===void 0||Q===null)return;let X=typeof Q==="string"?Number(Q):Q,G=W==="dailyLimit"?0:1;if(typeof X!=="number"||!Number.isSafeInteger(X)||X<G)throw Error(`\`${W}\` must be an integer of at least ${G} when calling \`move_sequence_enrollments\`.`);return X}function kH($,W){let Q=$[W];if(Q===void 0)return[];if(!Array.isArray(Q)||Q.some((G)=>typeof G!=="string"))throw Error(`\`${W}\` must be an array of strings when calling \`move_sequence_enrollments\`.`);let X=Q.map((G)=>G.trim()).filter((G)=>G.length>0);if(X.length===0)throw Error(`\`${W}\` must contain at least one non-empty string when calling \`move_sequence_enrollments\`.`);return X}function cH($){let W=A("move_sequence_enrollments",$,"fromNodeId"),Q=L($,"targetNodeId"),X=L($,"reason"),G=L($,"sort");if(G!==void 0&&!SH.includes(G))throw Error(`\`sort\` must be one of ${SH.join(", ")} when calling \`move_sequence_enrollments\`.`);let J=kH($,"subscriberIds"),w=kH($,"tags"),Y=CH($,"limit"),b=CH($,"dailyLimit");return{fromNodeId:W,...Q!==void 0&&{targetNodeId:Q},...Y!==void 0&&{limit:Y},...b!==void 0&&{dailyLimit:b},...G!==void 0&&{sort:G},...J.length>0&&{subscriberIds:J},...w.length>0&&{tags:w},...X!==void 0&&{reason:X},...typeof $.dryRun==="boolean"&&{dryRun:$.dryRun}}}function mH($){y0("create_campaign",$),K1("create_campaign",$);let W=L($,"prompt")!==void 0,Q=$.html!==void 0,X=$.blocks!==void 0,G=$.templateId!==void 0;if($.prompt!==void 0&&!W)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(W&&(Q||X||G))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!W&&($.style!==void 0||$.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!W&&L($,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function lH($){y0("create_template",$),K1("create_template",$);let W=L($,"prompt")!==void 0,Q=[W,$.html!==void 0,$.blocks!==void 0].filter(Boolean).length;if($.prompt!==void 0&&!W)throw Error("`prompt` cannot be empty when calling `create_template`.");if(Q!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!W&&($.style!==void 0||$.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!W&&L($,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function gH($){if(L($,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if($.targetLists!==void 0&&!h($.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if($.listIds!==void 0&&$.targetLists!==void 0)throw Error("Provide either `listIds` or `targetLists` when calling `schedule_campaign`, not both.");if($.listIds!==void 0&&(!Array.isArray($.listIds)||$.listIds.length===0||$.listIds.some((W)=>typeof W!=="string")))throw Error("`listIds` must be a non-empty array of list ID strings when calling `schedule_campaign`.");if($.sendTimeOptimization!==void 0){if(typeof $.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if($.spreadOverHours!==void 0){if(typeof $.spreadOverHours!=="number"||!Number.isInteger($.spreadOverHours)||$.spreadOverHours<1||$.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if($.recurringInterval!==void 0&&$.recurringInterval!=="weekly"&&$.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function F$($,W,Q){let X=new Set(["companyId","landingPageId","name","slug","content"]),G=Object.keys(W).filter((J)=>!X.has(J));if(G.length>0)throw Error(`\`${$}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${G.length===1?"":"s"}: ${G.map((J)=>`\`${J}\``).join(", ")}.`);if(Q.requireUpdate&&W.name===void 0&&W.slug===void 0&&W.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${$}\`.`);return{...W.name!==void 0&&{name:W.name},...W.slug!==void 0&&{slug:W.slug},...W.content!==void 0&&{content:W.content}}}function pH($){let W=new Set(["companyId","domain","verify"]),Q=Object.keys($).filter((X)=>!W.has(X));if(Q.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}.`);if($.domain===void 0&&$.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...$.domain!==void 0&&{domain:$.domain},...typeof $.verify==="boolean"&&{verify:$.verify}}}function iH($){y0("create_transactional_email",$);let W=L($,"prompt")!==void 0,Q=$.html!==void 0,X=$.blocks!==void 0;if($.prompt!==void 0&&!W)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(W&&(Q||X))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!W&&($.style!==void 0||$.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!W&&!Q&&!X)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!W&&L($,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var I6={type:"object",description:"Update Subscriber config. firstName, lastName, and customAttributeUpdates values may use trigger-event merge tags such as {{event.plan}}. Number and boolean values must be a literal or one standalone merge tag and are coerced after resolution.",properties:{label:{type:"string"},firstName:{type:["string","null"],description:"First name literal or merge tag; null clears the field."},lastName:{type:["string","null"],description:"Last name literal or merge tag; null clears the field."},status:{type:"string",enum:["active","unsubscribed","bounced"]},customAttributeUpdates:{type:"array",items:{type:"object",properties:{name:{type:"string"},value:{type:["string","number","boolean","null"],description:"Literal scalar, null to delete, or a standalone merge tag such as {{event.plan}}, {{event.amount}}, or {{event.active}}."},valueType:{type:"string",enum:["text","number","boolean"]}},required:["name","value"]}}},additionalProperties:!0},vj={type:"object",description:"Config for advanced nodeType steps. Required fields depend on nodeType: action_add_tag and action_remove_tag need tagId or tagName; action_add_to_list and action_remove_from_list need listId; action_update_attributes uses the Update Subscriber fields (firstName, lastName, status, customAttributeUpdates) and may use trigger-event merge tags; logic_wait_for_event needs eventName plus optional timeoutDays and timeoutAction; logic_condition needs conditionType plus that condition's resource field; action_webhook needs an HTTPS url plus optional method, headers, body, resultKey, and onError; action_ai generates short per-contact fragments (a sentence or two each) that later email steps insert with {{ai.KEY.field}} merge tags, not whole emails, and needs prompt, resultKey, and outputFields plus optional includeTags, includeEventProperties, includeRecentEvents, recentEventLimit, includeAttributes, and onError; logic_delay uses delayDays/delayHours/delayMinutes. Fields that do not apply to the node type are dropped.",properties:{...I6.properties,tagId:{type:"string",description:"action_add_tag / action_remove_tag: tag ID. Pass a name in tagName instead, because tag actions resolve tagId by ID only. has_tag / does_not_have_tag also accept a tag name here. Missing tag definitions are created automatically."},tagName:{type:"string",description:"action_add_tag / action_remove_tag / has_tag / does_not_have_tag: tag name. Use instead of tagId when you only know the name."},listId:{type:"string",description:"action_add_to_list / action_remove_from_list / in_list: list ID. It must match an existing list in this company; listName is filled in for you."},listName:{type:"string",description:"Optional cached list display name for list actions."},eventName:{type:"string",description:"logic_wait_for_event and event_received conditions: event to wait for or check, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"logic_condition: condition evaluated before continuing. has_phone and sms_subscribed need no resource fields."},segmentId:{type:"string",description:"logic_condition: segment ID for in_segment."},segmentName:{type:"string",description:"Optional cached segment display name."},linkUrl:{type:"string",description:"logic_condition: optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"logic_condition: scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"logic_condition: subscriber attribute name/path for field comparisons."},fieldValue:{type:"string",description:"logic_condition: comparison value for field comparisons."},url:{type:"string",description:"action_webhook: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}} resolved at execution time."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"action_webhook: HTTP method. Defaults to POST."},headers:{type:"object",description:"action_webhook: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'action_webhook: optional JSON body template for POST/PUT/PATCH. Must be valid JSON as written, with merge tags inside quoted string values ({"email": "{{email}}"}); a tag in a bare value position is rejected. Tags are resolved at execution time; when omitted, the default payload with subscriber and sequence context is sent.'},resultKey:{type:"string",description:"action_webhook / action_ai: where the result is saved. Later steps reference it via {{webhooks.KEY.data.field}} (webhook) or {{ai.KEY.field}} (AI) merge tags. Required for action_ai. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"action_webhook / action_ai: behavior when the step fails. continue proceeds to the next step, exit ends the sequence for the subscriber, fail marks the enrollment failed. Defaults to fail for webhooks and continue for AI steps (fallbacks fill the output fields)."},prompt:{type:"string",description:"action_ai: prompt template sent to the model, resolved per contact at execution time. Supports merge tags like {{first_name}}, {{event.plan}}, and {{webhooks.KEY.data.field}}. Max 8000 chars."},outputFields:{type:"array",description:"action_ai: named values the model must return (1-10). Each key becomes a {{ai.KEY.<key>}} merge tag for later steps. fallback is used when generation fails, so emails still send with sensible copy. Combined field maxLength values must fit the step's conservative 2000-token multilingual response budget plus JSON overhead.",items:{type:"object",properties:{key:{type:"string",description:"Field key, e.g. subject_line. Must start with a letter; letters, numbers, underscores; max 64 chars; unique within the step."},description:{type:"string",description:"What the model should produce for this field, e.g. 'A subject line under 50 characters'. Max 300 chars."},maxLength:{type:"integer",minimum:1,maximum:4000,description:"Hard cap on stored characters (1-4000). Defaults to 500. Output beyond it is cut."},fallback:{type:"string",description:"Text used verbatim when generation fails or the model omits the field."}},required:["key"],additionalProperties:!1}},includeTags:{type:"boolean",description:"action_ai: include the contact's tags in the prompt context."},includeEventProperties:{type:"boolean",description:"action_ai: include the enrollment's trigger event name and properties in the prompt context."},includeRecentEvents:{type:"boolean",description:"action_ai: include the contact's most recent custom events (newest first) in the prompt context."},recentEventLimit:{type:"number",description:"action_ai: how many recent events to include when includeRecentEvents is true (1-50, default 10)."},includeAttributes:{type:"array",items:{type:"string"},description:"action_ai: custom attribute keys to include in the prompt context (max 30). Only the listed keys are sent."},delayDays:{type:"number",description:"logic_delay: whole days to wait."},delayHours:{type:"number",description:"logic_delay: hours to wait."},delayMinutes:{type:"number",description:"logic_delay: minutes to wait."}},additionalProperties:!0},T4={senderProfileId:{type:"string",description:"Sender profile for this step's From identity. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"From address for this step. Its domain must be configured and verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this step. Alone it only changes the visible name; with fromEmail it also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this step's Reply-To. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Reply-To address for this step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Reply-To display name override for this step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."}},R4={type:"object",description:"A typed step to create inside a sequence path, including email, SMS, delay, discount, subscriber actions, conditions, waits, webhooks, and AI steps.",properties:{type:{type:"string",enum:["email","sms","delay","create_discount","discount","update_subscriber","condition","webhook","ai"],description:"Sequence path step type. Omit for email steps; use delay for fixed/date waits or update_subscriber for action_update_attributes. For an event gate, use nodeType:'logic_wait_for_event' with an explicit config object. A path is one linear chain, so it cannot contain a nested 'logic_branch' step: end the path with the step the nested branch should follow, then insert that branch with its own insert_sequence_step call using an afterNodeId from addedBranchPathNodeIds."},nodeType:{type:"string",enum:["logic_delay","action_email","action_sms","action_create_discount","action_add_tag","action_remove_tag","action_add_to_list","action_remove_from_list","action_update_attributes","logic_wait_for_event","logic_condition","action_webhook","action_ai"],description:"Advanced sequence path node type. Prefer type unless creating a non-email action. Tag, list, subscriber-update, wait, condition, webhook, and AI node types carry their fields in config, for example nodeType:'action_add_tag' with config:{ tagName:'newsletter-confirmed' }. SMS steps still use the step-level text/imageUrls/ineligibleAction, discount steps the step-level discount fields, and delays the step-level delay/delayMs/waitUntil."},config:vj,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:K6,items:{type:"object"}},html:{type:"string",description:"HTML content for email steps. Stored as one raw HTML block. Use this for imported provider HTML."},isTransactional:{type:"boolean",description:"Email only: omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses CC'd on this step."},bccEmails:{type:"array",items:{type:"string"},description:"Email only: addresses BCC'd on this step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"Email only: URL-backed file attachments (max 10, 7MB total per email). path may be a public HTTPS URL or an {{event.*}} URL template resolved from the enrollment event at send time."},text:{type:"string",description:"SMS only: plain-text message body."},imageUrls:{type:"array",items:{type:"string"},description:"SMS only: up to two public MMS image URLs."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS only: behavior when the contact cannot receive SMS."},delay:V6,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:Z6,waitUntilWeekday:P6,name:{type:"string",description:"Email template name for email steps."},senderProfileId:{type:"string",description:"Sender profile for this email step. Omit to inherit the effective identity of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},fromEmail:{type:"string",description:"From address for this email step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Display name override for this email step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Reply profile for this email step. Omit to inherit the effective Reply-To of the nearest sequence email. After a branch merge, only fields shared by every incoming path are inherited; conflicting fields use sequence or company defaults."},replyTo:{type:"string",description:"Reply-To address for this email step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Reply-To display name override for this email step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},discount:{type:"object",description:`Discount configuration for create_discount steps. Same shape as create_sequence steps.${Q$}`,additionalProperties:!0},label:{type:"string",description:"Node label for discount or advanced node steps."},provider:{type:"string",enum:["stripe","shopify"],description:"Discount provider. Use stripe to dynamically create a Stripe coupon plus promotion code, or shopify to dynamically create a Shopify Admin discount code."},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},XQ={type:"object",properties:{id:{type:"string",description:"Optional stable path ID. Defaults to branch-0, branch-1, and so on. The value 'else' is reserved."},label:{type:"string",description:"Display label, for example 'Replied in this sequence'."},conditionType:{type:"string",enum:["has_tag","does_not_have_tag","in_list","in_segment","event_received","link_clicked","field_equals","field_contains","field_greater_than","field_less_than","has_phone","sms_subscribed"],description:"Condition for this path. has_phone and sms_subscribed need no resource fields. Required unless the branch sets splitMode 'random', where paths are chosen by percentage and this field must be omitted."},tagName:{type:"string",description:"Tag name for has_tag and does_not_have_tag. This can be used instead of tagId."},tagId:{type:"string",description:"Tag ID or tag name for has_tag and does_not_have_tag."},listId:{type:"string",description:"List ID for in_list."},segmentId:{type:"string",description:"Segment ID for in_segment."},segmentName:{type:"string",description:"Optional display name for in_segment."},eventName:{type:"string",description:"Event name for event_received, for example email.replied."},linkUrl:{type:"string",description:"Optional URL substring for link_clicked. Omit to match any tracked click."},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"],description:"Scope for event_received and link_clicked. Use this_sequence to restrict activity to the current enrollment."},fieldName:{type:"string",description:"Subscriber attribute name/path for field conditions."},fieldValue:{type:"string",description:"Comparison value for field conditions."},targetNodeId:{type:"string",description:"Optional existing node to route this branch path to. Use a node ID from get_sequence, including the sequence completion node when this path should stop. If steps are also provided, they run before this target."},steps:{type:"array",description:"Optional new steps for this path. When targetNodeId is also set, the last new step connects to that existing node.",items:R4}},additionalProperties:!1},GQ="Branch paths. On the default condition split they are evaluated in order and an else fallback is created automatically. On a random split (splitMode 'random') each entry is a weighted variant, conditionType and condition-specific fields are omitted, and there is no else path. Each path can create steps, route directly to an existing targetNodeId, or do both.",JQ={type:"string",enum:["condition","random"],description:"How subscribers are routed. 'condition' (default) evaluates each branch's conditionType in order. 'random' assigns each subscriber a path by percentage when they reach the node, which is how you build a concurrent A/B split inside a sequence - for example testing two abandoned-cart offers against each other at the same time instead of running them one after another. Random splits require randomPercentages, omit conditionType and condition-specific fields on every branch, and must not define an else path. To A/B test the content of a single existing email step instead of branching the flow, use create_ab_test with automationNodeId, which tracks variants and picks a winner for you."},wQ={type:"array",items:{type:"number"},description:"Required when splitMode is 'random': one non-negative percentage per entry in branches, in the same order, summing to 100. For an even two-way test use [50, 50]."};function nH($){if(!$||typeof $!=="object")return null;let W=$;if(W.success!==!1)return null;if(typeof W.error==="string")return Error(W.error);if(W.error&&typeof W.error==="object"&&typeof W.error.message==="string")return Error(W.error.message);if(typeof W.message==="string")return Error(W.message);return Error("The tool returned an unsuccessful response.")}var YQ=1000,bQ=1000,HQ=YQ*bQ-1;function zQ($){return $.trim().toLowerCase().replace(/\s+/g,"-")}function _j($,W){let Q=L(W,"attribute"),X=L(W,"attributeValue"),G=u($,W,"attributeOperator",G$);if(!Q){if(X!==void 0||G!==void 0)throw Error(`\`attributeValue\` and \`attributeOperator\` require \`attribute\` when calling \`${$}\`.`);return{}}let J=G??"is",w;if(X!==void 0)w=`${Q}:${X}`;else if(Q.includes(":"))w=Q;else if(J==="is_not_empty")w=`${Q}:`;else throw Error(`Provide \`attributeValue\` (or use \`attribute: "name:value"\`) when \`attributeOperator\` is \`${J}\` in \`${$}\`. Only \`is_not_empty\` may omit a value.`);return{attribute:w,attributeOperator:J}}function xj($){let W=new URLSearchParams;if(typeof $.query==="string"&&$.query.trim()!=="")W.set("query",$.query.trim());if(Array.isArray($.tags)&&$.tags.length>0)W.set("tags",$.tags.filter((Q)=>typeof Q==="string"&&Q.trim()!=="").join(","));if(typeof $.list==="string"&&$.list.trim()!=="")W.set("list",$.list.trim());if(typeof $.listId==="string"&&$.listId.trim()!=="")W.set("listId",$.listId.trim());if(typeof $.listName==="string"&&$.listName.trim()!=="")W.set("listName",$.listName.trim());if(typeof $.segmentId==="string"&&$.segmentId.trim()!=="")W.set("segmentId",$.segmentId);if(typeof $.status==="string"&&$.status.trim()!=="")W.set("status",$.status.trim());if(typeof $.unsubscribedAfter==="string"&&$.unsubscribedAfter.trim()!=="")W.set("unsubscribedAfter",$.unsubscribedAfter.trim());if(typeof $.unsubscribedBefore==="string"&&$.unsubscribedBefore.trim()!=="")W.set("unsubscribedBefore",$.unsubscribedBefore.trim());if($.attribute){if(W.set("attribute",$.attribute),$.attributeOperator)W.set("attributeOperator",$.attributeOperator)}if($.cursor)W.set("cursor",$.cursor);else W.set("page",String($.page));if(W.set("limit",String($.pageSize)),$.includeTotal===!1)W.set("includeTotal","false");return W}async function tH($,W){let X=sH("search_subscribers",$,"limit"),G=L($,"cursor"),J=G?hj("search_subscribers",$):yj("search_subscribers",$,X),w=X===void 0?void 0:J+X,Y=Math.min(YQ,Math.max(1,w??YQ)),b=_j("search_subscribers",$),H=[],z=1,F=G,U,B=null,K=0,P=!1,q=!1;while(!0){let k=w===void 0?void 0:w-H.length,S0=F?Math.min(Y,Math.max(1,k??Y)):Y,g0=xj({query:$.query,tags:$.tags,list:$.list,listId:$.listId,listName:$.listName,segmentId:$.segmentId,status:$.status,unsubscribedAfter:$.unsubscribedAfter,unsubscribedBefore:$.unsubscribedBefore,attribute:b.attribute,attributeOperator:b.attributeOperator,page:z,pageSize:S0,cursor:F}),C0=await D("GET",`/api/v1/subscribers?${g0.toString()}`,void 0,W);if(K===0)B=C0.pagination?.total??null;K+=1,H.push(...C0.subscribers??[]);let a1=(C0.subscribers??[]).length,p0=C0.pagination?.nextCursor??void 0;U=p0;let R6=w!==void 0&&H.length>=w,P1;if(p0)P1=!1;else if(C0.pagination?.hasMore!==void 0)P1=!C0.pagination.hasMore;else if(C0.pagination?.totalPages!==void 0&&C0.pagination.totalPages!==null)P1=z>=C0.pagination.totalPages;else P1=a1<S0;if(P1||a1===0&&!p0){P=!0;break}if(R6)break;if(K>=bQ){q=!0;break}if(p0)F=p0;else if(F)break;else z+=1}if(q&&(H.length<J||H.length===J&&U===void 0))throw Error(`Could not reach offset ${J} within ${bQ} requests because too few matches were returned per page. Start without \`offset\` and follow \`pagination.nextCursor\` instead.`);if(B===null&&P&&!G)B=H.length;let M=H.slice(J,w),S=P?!1:B!==null?J+M.length<B:!P||H.length>J+M.length,C=U!==void 0&&H.length===J+M.length,v=J+M.length;return{success:!0,subscribers:M,pagination:{page:X===void 0?1:Math.floor(J/X)+1,limit:X??Y,offset:J,total:B,totalPages:B===null?null:Math.ceil(B/(X??Y)),fetchedPages:K,hasMore:S,nextOffset:S&&!G&&v<=HQ?v:null,nextCursor:S&&C?U??null:null},returned:M.length,truncated:S}}function hj($,W){if(W.offset!==void 0||W.page!==void 0)throw Error(`\`cursor\` cannot be combined with \`offset\` or \`page\` when calling \`${$}\`. Keep following \`pagination.nextCursor\` instead.`);return 0}function yj($,W,Q){let X=rH($,W,"offset"),G=sH($,W,"page");if(X!==void 0&&G!==void 0)throw Error(`Provide either \`offset\` or \`page\` when calling \`${$}\`, not both.`);if(G!==void 0){if(Q===void 0)throw Error(`\`page\` requires \`limit\` when calling \`${$}\` so the page size is defined. Omit both to fetch every match in one call.`);return dH($,(G-1)*Q)}return dH($,X??0)}function dH($,W){if(W>HQ)throw Error(`\`offset\` must be ${HQ} or less when calling \`${$}\`. Use \`cursor\` to continue beyond that point.`);return W}function rH($,W,Q){let X=W[Q];if(X===void 0||X===null)return;if(typeof X!=="number"||!Number.isInteger(X)||X<0)throw Error(`\`${Q}\` must be a non-negative integer when calling \`${$}\`.`);return X}function sH($,W,Q){let X=rH($,W,Q);if(X!==void 0&&X<1)throw Error(`\`${Q}\` must be 1 or greater when calling \`${$}\`.`);return X}function DQ($){let W=typeof $.email==="string"&&$.email.trim()!==""?$.email.trim():void 0,Q=typeof $.externalId==="string"&&$.externalId.trim()!==""?$.externalId.trim():void 0;return{...W?{email:W}:{},...Q?{externalId:Q}:{}}}function $1($,W){let Q=DQ(W);if(!Q.email&&!Q.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${$}\`.`);return Q}function U$($,W){let Q=new URLSearchParams;if(W?.includeMachineEngagement)Q.set("includeMachineEngagement","true");let X=Q.toString(),G=X?`?${X}`:"";if($.email)return`/api/v1/subscribers/${encodeURIComponent($.email)}${G}`;return Q.set("externalId",String($.externalId)),`/api/v1/subscribers/external?${Q.toString()}`}function FQ($){if($.email)return`/api/v1/subscribers/${encodeURIComponent($.email)}/notes`;let W=new URLSearchParams;return W.set("externalId",String($.externalId)),`/api/v1/subscribers/external/notes?${W.toString()}`}async function S4($,W,Q){return D("GET",U$($,Q),void 0,W)}function u($,W,Q,X){let G=L(W,Q);if(G===void 0)return;if(!X.includes(G))throw Error(`\`${Q}\` must be one of ${X.join(", ")} when calling \`${$}\`.`);return G}function C4($,W,Q,X){let G=A($,W,Q);if(!X.includes(G))throw Error(`\`${Q}\` must be one of ${X.join(", ")} when calling \`${$}\`.`);return G}function X0($,W,Q,X,G){let J=W[Q];if(J===void 0)return;if(typeof J!=="number"||!Number.isInteger(J)||J<X||J>G)throw Error(`\`${Q}\` must be an integer between ${X} and ${G} when calling \`${$}\`.`);return J}function fj($,W){let Q=[],X=u($,W,"eventType",N4);if(X)Q.push(X);if(W.eventTypes!==void 0){if(!Array.isArray(W.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${$}\`.`);W.eventTypes.forEach((G,J)=>{if(typeof G!=="string")throw Error(`\`eventTypes\` item ${J+1} must be a string when calling \`${$}\`.`);let w=G.trim();if(!N4.includes(w))throw Error(`\`eventTypes\` item ${J+1} must be one of ${N4.join(", ")} when calling \`${$}\`.`);Q.push(w)})}return[...new Set(Q)]}function UQ($,W){let Q=new URLSearchParams,X=fj($,W);if(X.length>0)Q.set("eventTypes",X.join(","));let G=u($,W,"period",["1h","24h","7d","30d","90d"]);if(G)Q.set("period",G);let J=L(W,"start");if(J)Q.set("start",J);let w=L(W,"end");if(w)Q.set("end",w);let Y=X0($,W,"page",1,1e6);if(Y!==void 0)Q.set("page",String(Y));let b=X0($,W,"limit",1,500);if(b!==void 0)Q.set("limit",String(b));if(W.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");return Q}function BQ($,W){if(W.events===void 0)return;if(!Array.isArray(W.events))throw Error(`\`events\` must be an array when calling \`${$}\`.`);let Q=W.events.map((X,G)=>{if(typeof X!=="string"||!M6.includes(X))throw Error(`\`events\` item ${G+1} must be one of ${M6.join(", ")} when calling \`${$}\`.`);return X});if(Q.length===0)throw Error(`\`events\` must include at least one event type when calling \`${$}\`.`);return Q}function LQ($,W){if(!Array.isArray(W.emails))throw Error(`\`emails\` must be an array when calling \`${$}\`.`);let Q=[];if(W.emails.forEach((X,G)=>{if(typeof X!=="string")throw Error(`\`emails\` item ${G+1} must be a string when calling \`${$}\`.`);let J=X.trim();if(J.length>0)Q.push(J)}),Q.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${$}\`.`);if(Q.length>lW)throw Error(`\`emails\` must include no more than ${lW} email addresses when calling \`${$}\`. Split larger batches into multiple calls.`);return Q}function oH($,W,Q,X){let G=W[Q];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${Q}\` must be an array when calling \`${$}\`.`);let J=[];if(G.forEach((w,Y)=>{if(typeof w!=="string")throw Error(`\`${Q}\` item ${Y+1} must be a string when calling \`${$}\`.`);let b=w.trim();if(b.length>0)J.push(b)}),J.length===0)throw Error(`\`${Q}\` must include at least one ${X} when calling \`${$}\`.`);return J}function aH($){let Q=oH("enroll_subscribers_in_sequence",$,"emails","email address"),X=oH("enroll_subscribers_in_sequence",$,"subscriberIds","subscriber ID"),G=(Q?.length??0)+(X?.length??0);if(G===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(G>gW)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${gW} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let J=L($,"targetNodeId");return{...Q!==void 0&&{emails:Q},...X!==void 0&&{subscriberIds:X},...J!==void 0&&{targetNodeId:J}}}import{readFileSync as uj,statSync as cj}from"node:fs";import{basename as mj}from"node:path";var lj={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 gj($){let W=$.split(".").pop()?.toLowerCase()??"";return lj[W]??null}var pj=104857600;async function eH($,W){if(!k4())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 Q=gj($);if(!Q)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let X=cj($).size;if(X>pj)throw Error(`File is too large (${Math.round(X/1048576)}MB). Delivery files must be 100MB or smaller.`);let G=uj($),J=await D("POST","/api/v1/products/delivery/upload-url",{filename:mj($),contentType:Q,fileSizeBytes:X},W),w=await fetch(J.uploadUrl,{method:"PUT",headers:{"Content-Type":Q},body:G});if(!w.ok)throw Error(`File upload failed (${w.status})`);return{url:J.publicUrl,fileName:J.fileName,fileSizeBytes:X,mimeType:Q}}async function B$($){let W=L($,"companyId");if(W)return W;let Q=j1();if(Q)return Q;try{return(await D("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function T6($,W){let Q=await B$(W);if(!Q)throw Error(`A company is required when calling \`${$}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return Q}function E6($,W){if(!h($)||!W)return $;return{...$,url:W}}function $3($,W){if(!h($))return $;return{...$,...W.campaign!==void 0&&{url:W.campaign},...W.campaignPreview!==void 0&&{previewUrl:W.campaignPreview}}}function N6($,W,Q){if(!Array.isArray($)||!W)return $;return $.map((X)=>{if(!h(X))return X;let G=L(X,"id");if(!G)return X;let J=A1({companyId:W,...Q==="campaign"&&{campaignId:G},...Q==="landingPage"&&{landingPageId:G},...Q==="sequence"&&{sequenceId:G},...Q==="template"&&{emailId:G},...Q==="transactional"&&{transactionalId:G},...Q==="emailSend"&&{emailSendId:G}});if(Q==="campaign")return $3(X,J.urls);let w=Q==="sequence"?J.urls.sequence:Q==="landingPage"?J.urls.landingPage:Q==="template"?J.urls.email:Q==="transactional"?J.urls.transactionalEmail:J.urls.emailSend;return E6(X,w)})}function ij($){if(!Array.isArray($))return $;return $.map((W)=>{if(!h(W))return W;let Q=L(W,"id");if(!Q)return W;let X=A1({companyId:Q});return{...W,url:X.urls.dashboard,settingsUrl:X.urls.settings}})}var AQ=new Set(["get_account","select_company","create_company","get_company","update_company","list_campaigns","get_campaign","get_email_send","list_email_sends","create_campaign","update_campaign","schedule_campaign","unschedule_campaign","send_test_email","cancel_campaign","pause_campaign","resume_campaign","duplicate_campaign","resend_campaign_to_non_openers","list_landing_pages","get_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","enable_sequence","disable_sequence","pause_sequence_enrollments","resume_sequence_enrollments","cancel_sequence_enrollments","move_sequence_enrollments","realign_sequence_enrollments","get_sequence_enrollment_realignment","list_ab_tests","get_ab_test","get_ab_test_stats","update_ab_test_variant","update_ab_test","list_templates","get_template","create_template","update_template","set_template_localization","sync_template_localizations","list_transactional_emails","get_transactional_email","create_transactional_email","update_transactional_email"]);async function W3($,W,Q){if(!h(Q)||!AQ.has($))return Q;let X=h(Q.company)?Q.company:void 0,J=L(Q,"selectedCompanyId")??L(Q,"currentCompanyId")??L(Q,"companyId")??(X?L(X,"id"):void 0)??(X?L(X,"companyId"):void 0)??await B$(W);if(!J)return Q;let w=h(Q.campaign)?Q.campaign:void 0,Y=h(Q.sequence)?Q.sequence:void 0,b=h(Q.landingPage)?Q.landingPage:void 0,H=h(Q.template)?Q.template:void 0,z=h(Q.transactional)&&!Array.isArray(Q.transactional)?Q.transactional:void 0,F={companyId:J,campaignId:L(W,"campaignId")??L(Q,"campaignId")??(w?L(w,"id"):void 0),landingPageId:L(W,"landingPageId")??L(Q,"landingPageId")??(b?L(b,"id"):void 0),sequenceId:L(W,"sequenceId")??L(Q,"sequenceId")??(Y?L(Y,"id"):void 0),emailId:L(Q,"templateId")??(H?L(H,"id"):void 0)??(z?L(z,"emailId"):void 0)??L(W,"templateId"),transactionalId:L(W,"transactionalId")??(z?L(z,"id"):void 0)??L(W,"idOrSlug"),emailSendId:L(W,"emailSendId")??L(Q,"emailSendId")??(h(Q.emailSend)?L(Q.emailSend,"id"):void 0),status:L(W,"status")},U=A1(F),B=X?A1({companyId:J}):void 0;return{...Q,...Array.isArray(Q.companies)&&{companies:ij(Q.companies)},...Array.isArray(Q.campaigns)&&{campaigns:N6(Q.campaigns,J,"campaign")},...Array.isArray(Q.landingPages)&&{landingPages:N6(Q.landingPages,J,"landingPage")},...Array.isArray(Q.sequences)&&{sequences:N6(Q.sequences,J,"sequence")},...Array.isArray(Q.templates)&&{templates:N6(Q.templates,J,"template")},...Array.isArray(Q.transactional)&&{transactional:N6(Q.transactional,J,"transactional")},...Array.isArray(Q.emailSends)&&{emailSends:N6(Q.emailSends,J,"emailSend")},...X&&B!==void 0&&{company:{...X,url:B.urls.dashboard,settingsUrl:B.urls.settings}},...w&&U.urls.campaign!==void 0&&{campaign:$3(w,U.urls)},...Y&&U.urls.sequence!==void 0&&{sequence:E6(Y,U.urls.sequence)},...b&&U.urls.landingPage!==void 0&&{landingPage:E6(b,U.urls.landingPage)},...H&&U.urls.email!==void 0&&{template:E6(H,U.urls.email)},...z&&U.urls.transactionalEmail!==void 0&&{transactional:E6(z,U.urls.transactionalEmail)},...h(Q.emailSend)&&U.urls.emailSend!==void 0&&{emailSend:E6(Q.emailSend,U.urls.emailSend)},appUrls:U.urls}}import{readFileSync as nj,statSync as dj}from"node:fs";import{basename as oj,extname as X3}from"node:path";var KQ=5242880,tj=Math.ceil(KQ/3)*4,rj=Math.ceil(tj*1.05)+256,G3={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},sj=new Set(Object.values(G3));function OQ($){return $?.split(";")[0]?.trim().toLowerCase()||void 0}function aj($){return G3[X3($).toLowerCase()]}function ej($){let W=X3($);return(W?$.slice(0,-W.length):$).replace(/[-_]+/g," ").trim()||"Image"}function $M($){if($.length>rj)throw Error("Image assets must be 5MB or smaller.")}function WM($){let W=0,Q=0;for(let G=0;G<$.length;G+=1){let J=$.charCodeAt(G);if(J===9||J===10||J===11||J===12||J===13||J===32)continue;W+=1,Q=J===61?Q+1:0}if(Math.floor(W*3/4)-Math.min(Q,2)>KQ)throw Error("Image assets must be 5MB or smaller.")}function QM($){$M($);let W=$.trim(),Q=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(W),X=Q?.[2]??W;WM(X);let G=X.replace(/\s+/g,"");if(G.length===0||G.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(G))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(G,"base64"),...Q?.[1]?{dataUrlContentType:OQ(Q[1])}:{}}}function Q3($){if($<=0)throw Error("The image file is empty.");if($>KQ)throw Error("Image assets must be 5MB or smaller.")}function XM($){let W=aj($.filename)??OQ($.explicitContentType)??OQ($.dataUrlContentType);if(!W||!sj.has(W))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return W}function GM($){let W,Q,X;if($.filePath!==void 0){if(!k4())throw Error("`filePath` is only supported when the MCP server runs locally on your machine. For a remote MCP connection, pass `imageBase64` and `filename` instead.");let J=dj($.filePath).size;Q3(J),W=nj($.filePath),Q=$.filename??oj($.filePath)}else{if(!$.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!$.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let J=QM($.imageBase64);W=J.bytes,X=J.dataUrlContentType,Q=$.filename,Q3(W.byteLength)}let G=XM({filename:Q,explicitContentType:$.contentType,dataUrlContentType:X});return{bytes:W,filename:Q,contentType:G,altText:$.altText??ej(Q)}}async function J3($){let W=GM($),Q=W.bytes.byteLength,X=await D("POST","/api/v1/media/upload-url",{filename:W.filename,contentType:W.contentType,fileSizeBytes:Q},$.companyId);return await uQ(X.uploadUrl,W.bytes,W.contentType,$.companyId),(await D("POST","/api/v1/media/complete-upload",{key:X.key,filename:X.fileName,contentType:W.contentType,fileSizeBytes:Q,...$.sourceWidth!==void 0&&{width:$.sourceWidth},...$.sourceHeight!==void 0&&{height:$.sourceHeight},altText:W.altText},$.companyId)).asset}var JM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},r1={type:"string",description:"Human-readable status, confirmation, or next-step message."},ZQ={type:"string",description:"Additional context about the result."};function I($){return{type:"object",description:$,additionalProperties:!0}}function Z1($){return{type:"array",description:$,items:I("One item in the returned collection.")}}function O($){return{type:"string",description:$}}function w1($){return{type:["object","null"],description:$,additionalProperties:!0}}function H0($){return{type:["string","null"],description:$}}function _($){return{type:"number",description:$}}function w3($){return{type:["number","null"],description:$}}function c($){return{type:"boolean",description:$}}function j($){return I(`The ${$} record returned by Sequenzy.`)}function y($){return Z1(`List of ${$} records returned by Sequenzy.`)}var f1="`opened` and `clicked` are unique counts deduplicated by email send (one recipient opening five times counts once), not total open events. Every count is attributed to the sends made inside the requested window, including engagement that arrives after the window ends, so `opened <= delivered <= sent` always holds. Rates use `rateDenominator` (`delivered`, or `sent` when no delivery events were recorded, reported as `rateDenominatorBasis`); `deliveryRate` and `bounceRate` divide by `sent`.",b3="Run state: branch on effectiveStatus (draft, live, enrollment_paused, paused, or archived) rather than on status, which reads `active` even when new enrollments are paused. acceptsNewEnrollments and processesExistingEnrollments answer the two questions behind it, and effectiveStatusSummary is a plain-language sentence. The legacy triggerConfig.active flag is not read by the runtime; it is reported as a mirror of acceptsNewEnrollments.",s1=I(`The sequence record returned by Sequenzy. ${b3}`),wM=Z1(`List of sequence records returned by Sequenzy. ${b3}`),L$={effectiveStatus:{type:"string",enum:["draft","live","enrollment_paused","paused","archived"],description:"Resolved run state. The one field to branch on: `status` still reads `active` while new enrollments are paused."},acceptsNewEnrollments:c("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:c("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:O("One plain-language sentence describing the run state, safe to show a user verbatim.")},Y3={...s1,properties:{migratedRecipientCount:_("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:_("Recipients completed because a deleted step had no surviving successor.")}},YM={appUrls:I("Dashboard URLs for relevant Sequenzy resources."),url:O("Primary dashboard URL for this result."),settingsUrl:O("Company settings URL when available.")},bM={success:JM,message:r1,note:ZQ,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:O("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:I("One returned item.")},value:I("Fallback object wrapper used only when a tool returns a non-object value.")},HM={get_account:{account:j("account"),companies:y("company"),apiKeyPermissions:I("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, and the API Keys management URL."),currentCompanyId:O("Company ID selected by the authenticated API key, when available."),selectedCompanyId:O("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:O("Selected company ID."),companyName:O("Selected company name.")},get_app_urls:{dashboard:O("Company dashboard URL."),settings:O("Company settings URL."),campaign:O("Campaign editor URL."),landingPage:O("Landing page editor URL."),sequence:O("Sequence editor URL."),email:O("Email editor URL."),transactionalEmail:O("Transactional email URL."),emailSend:O("Sent email detail URL."),domain:O("Sending domain settings URL."),urls:I("All generated URLs keyed by resource type.")},create_company:{company:j("company"),autoSelected:c("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:j("company")},get_company:{company:j("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:I("One sync rule.")},isDefault:c("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:I("One sync rule.")},isDefault:c("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:I("Effective cart-abandonment settings (defaults applied)."),priceDrop:I("Effective price-drop settings (defaults applied)."),shopDomain:O("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:I("Effective browse-abandonment settings after the update."),cartAbandonment:I("Effective cart-abandonment settings after the update."),priceDrop:I("Effective price-drop settings after the update."),shopDomain:O("Connected Shopify store domain.")},create_api_key:{apiKey:I("Created API key metadata: the newly created secret in `key`, plus `scopes` listing the assigned permission scopes (null when the key has full access)."),key:O("Newly created API key if the API response uses the short key field.")},request_api_key_handoff:{handoff:I("The prepared handoff: `url` opens the dashboard create-key form prefilled with the requested `name`, `preset` or `scopes`, and `replaces` when rotating. `canSelfServe` is true when the active key already holds api_keys:manage and could create the key directly. `deliversKeyToCaller` is always false - the new key is shown in the owner's browser and never returned here."),message:O("What to tell the operator about this handoff."),nextSteps:{type:"array",description:"Ordered steps to finish the rotation, including verifying the replacement and revoking the predecessor.",items:O("One step in the handoff.")}},list_api_keys:{apiKeys:y("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:j("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:j("revoked non-secret API key metadata")},delete_api_key:{apiKey:j("deleted non-secret API key metadata")},list_websites:{websites:y("sending domain, including DNS verification and readyToSend sending readiness")},list_integrations:{integrations:y("connected integration, including provider, provider account ID, active and sync status, last sync time, last sync error, allowlisted non-secret details, and lastSyncSkipped (records the last sync could not import normally: suppressed profiles that cannot receive email, plus any that were not imported). Credentials are never included")},get_integration:{integration:I("The connected integration: provider, display name, category, provider account ID, active and sync status, last sync time and error, and allowlisted non-secret details. Credentials are never included."),capabilities:w1("What this provider does: category, connect method, what it syncs, every event it emits with when it fires, attributes it writes, supported actions, availability, and caveats. Null for a provider with no catalog entry."),events:Z1("Each event the provider emits, every matching tag rule and its conditions, listening sequences, and account-wide observation fields. Use activity for integration-specific delivery."),unusedEvents:{type:"array",description:"Events the provider emits that no sequence triggers on. These are the concrete automation gaps for this integration.",items:O("Event name with no listening sequence.")},accountNeverReceivedEvents:{type:"array",description:"Provider event names this account has never received from any source. This is not integration-specific delivery evidence.",items:O("Event name never seen account-wide.")},activity:I("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),pixel:w1("Shopify only: live storefront pixel state (installed, endpoint, endpointCurrent, configurationCurrent, healthy, error, dependentEvents). Null for providers without a pixel. When error is null and healthy is false, every dependentEvent is confirmed dark; an error means Shopify could not confirm the state."),recommendations:Z1("Prioritized problems and suggestions, each with a code, severity (error, warning, info), message, and a concrete action."),availableActions:{type:"array",description:"Action ids callable on this integration right now, given its current state.",items:O("Available action id.")}},list_integration_capabilities:{providers:y("integration provider, including category, connect method, what it syncs, every event it emits with the moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats")},get_event_schema:{eventName:{type:["string","null"],description:"Normalized name of the event described, or null when listing every documented event."},events:{type:"array",description:"One entry per event. Listing mode returns summaries only; asking for a single eventName adds `providers`, each with an `examplePayload` and a `properties` array of { path, type, description?, mergeTag? }. `documented: false` means no reference sample is published - the event name is still valid to trigger and to build a sequence on.",items:I("An event: eventName, documented, label, category, description, documentedProviders, and (single-event mode) providers, mergeTagPrefix, and notes.")},note:ZQ},list_integration_activity:{activity:y("integration activity row, including provider, action, status, event type, matched contact, message, and error. Payloads are sanitized, so no credentials appear"),windowHours:{type:"number",description:"Retention window in hours for integration activity."},note:ZQ},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:O("URL to configure in the provider's webhook settings with the same secret. Always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:c("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:c("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog only: outcome of the optional history import request ({ requested, queued, error }). The webhook connection succeeds even if queueing the import failed."}},set_integration_sync_enabled:{integrationId:O("The integration that was updated."),provider:O("Provider of the updated integration."),syncEnabled:c("Sync state after the update."),changed:c("False when the integration was already in the requested state."),message:r1},get_integration_pixel:{integrationId:O("The Shopify integration inspected."),provider:O("Always `shopify`."),shopDomain:O("Store the pixel was read from."),pixel:I("Live pixel state: installed, id, endpoint it posts to, endpointCurrent (including the supported compatibility route), configurationCurrent (endpoint plus signed connection settings), healthy, and error when Shopify could not confirm."),dependentEvents:{type:"array",description:"Event names that depend on this pixel. They are confirmed unable to arrive only when pixel.error is null and pixel.healthy is false.",items:O("Pixel-dependent event name.")},message:r1},activate_integration_pixel:{integrationId:O("The Shopify integration updated."),provider:O("Always `shopify`."),shopDomain:O("Store the pixel was installed on."),pixel:I("Pixel state after activation."),changed:c("False when the pixel was already installed and reporting to this account."),created:c("True when a new pixel was installed."),updated:c("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:O("Pixel-dependent event name.")},message:r1},sync_integration:{integrationId:O("The integration being synced."),provider:O("Provider of the synced integration."),jobId:H0("Background job id for the queued sync, when one was created."),syncStatus:O("Sync status after queueing. Poll get_integration to watch it progress."),syncTarget:w1("For Supabase, the project ref, schema, and table the backfill reads. Absent for providers whose sync has no configurable source."),message:r1},list_sender_profiles:{senderProfiles:y("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether the address is fully ready to send"),replyProfiles:y("reply-to profile"),defaultSenderProfileId:H0("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:H0("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:j("renamed sender (From) profile, present when type was sender"),replyProfile:j("renamed reply-to profile, present when type was reply"),renamed:c("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:Z1("One entry per notification event with its current mode: off, instant, or daily. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:Z1("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:I("Modes each event accepts, keyed by event. campaign_completed does not accept daily."),defaults:I("Mode each event uses when the user has never configured it.")},get_sending_status:{status:O("Company-level sending state: active, paused, or suspended. Anything other than active blocks every send, including test sends."),pauseReason:H0("Exact enforcement message, including the measured rate, the threshold it crossed, and the send volume it was measured over. Null when sending is active."),pauseReasonKind:H0("Machine-readable pause cause: high_hard_bounce_rate, high_soft_bounce_rate, high_complaint_rate, phishing_guard, manual, or other. Only high_hard_bounce_rate can be cleared with resume_sending."),pausedAt:H0("ISO timestamp when sending was paused. Null when sending is active."),selfResume:I("Whether the account can clear this pause itself: canSelfResume, supported, allowedByAdmin, ownerIsTrusted, the automated aiReviewStatus (not_required, pending, approved, flagged, failed) with its reason and timestamps, and unavailableReason naming the blocking gate (unsupported_reason, waiting_for_review, blocked_by_ai, review_failed, blocked_by_admin)."),senderHealth:w1("Enforcement counts and the thresholds that apply at this volume for hard bounces, soft bounces, and complaints. bounceScopedSent is the denominator for bounce rates, complaintScopedSent is the denominator for complaint rates, and scopedSent remains as a backward-compatible alias for bounceScopedSent. Also includes enforcementMode. Null when the account has no metrics record yet or sender-health analytics are temporarily unavailable; pause state and remediation remain authoritative."),metricsWindow:I("Proof that enforcement is not time-windowed: kind is always all_time_since_reset and expiresAt is always null. bounceResetAt and complaintResetAt are the watermarks the totals are counted from. Do not tell the user to wait for a window to expire - there is none."),remediation:I("Ordered steps for the current state, plus supportEmail, docsUrl, and the dashboard URL. Relay these verbatim instead of improvising recovery advice.")},resume_sending:{resumed:c("True when this call restored sending. False when sending was already active."),message:r1,status:O("Sending state after the request. active on success."),selfResume:I("Self-resume state after the request, including the automated review status and how many gates remain."),metricsWindow:I("Enforcement watermarks after the resume. bounceResetAt moves to now, so the paused rate is recalculated from later sends."),remediation:I("Steps to keep sending healthy after the resume, plus supportEmail and docsUrl.")},get_tracking_settings:{tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:I("Signup consent settings: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled)."),autoUtm:I("Automatic UTM tagging state and its configured parameters."),trackingDomain:w1("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration.")},update_tracking_settings:{message:r1,tracking:I("Open, click, and unsubscribe tracking flags, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:I("Signup consent settings after the update: doubleOptInEnabled, and doubleOptInEmailId for the confirmation email, which is provisioned automatically the first time double opt-in is enabled."),autoUtm:I("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:w1("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:I("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:j("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:j("sending domain with separate DNS verification and readyToSend sending readiness; readiness.reason explains a domain that cannot send yet"),ready:c("Whether the sender website is ready."),status:O("Current processing or verification status.")},verify_sending_domain:{website:j("Sending domain with current DNS verification, readyToSend sending readiness, SPF, DKIM, and MAIL FROM details. When readyToSend is false, readiness.reason carries why: activation runs after the DNS records are correct, so it can still be pending while dkim.status reads verified."),verified:c("Whether the sending domain passed the fresh DNS verification check. Correct DNS alone does not mean the domain can send yet."),readyToSend:c("Whether DNS and the selected home transport are both ready for sending."),message:O("Verification result summary.")},get_integration_guide:{guide:j("integration guide"),code:O("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:I("One setup step.")}},add_subscriber:{subscriber:j("subscriber")},create_subscriber_import:{import:j("subscriber import")},get_subscriber_import:{import:j("subscriber import")},update_subscriber:{subscriber:j("subscriber")},remove_subscriber:{subscriber:j("subscriber"),hardDeleted:c("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:j("subscriber")},list_subscriber_notes:{notes:y("subscriber note")},add_subscriber_note:{note:j("subscriber note")},delete_subscriber_note:{id:O("Deleted subscriber note ID."),deleted:c("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:j("subscriber"),event:j("recorded event with its name and whether the event definition was created"),sideEffectFailures:{type:"array",description:"Sync-rule or automation side effects that failed. The event itself is still recorded.",items:O("One failed side effect.")}},trigger_subscriber_events:{subscriber:j("subscriber"),events:y("recorded event")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:O("One tag name.")},requested:_("Identifiers supplied in the request."),matched:_("Existing subscribers resolved."),updated:_("Subscribers whose tags actually changed."),unchanged:_("Subscribers that already carried every tag."),failed:_("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:y("per-subscriber failure (up to 50)"),triggeredAutomations:c("Whether tag_added sequences were allowed to enroll these contacts.")},bulk_remove_subscriber_tags:{tags:{type:"array",description:"Normalized tag names removed from every matched subscriber.",items:O("One tag name.")},requested:_("Identifiers supplied in the request."),matched:_("Existing subscribers resolved."),updated:_("Subscribers whose tags actually changed."),unchanged:_("Subscribers that did not carry any of the tags."),failed:_("Subscribers whose update failed."),notFound:I("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:y("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:y("subscriber"),pagination:I("Pagination metadata: page, limit, offset, total (null when the server skipped the count, which it does for attribute filters), totalPages, fetchedPages, hasMore, nextOffset, and nextCursor. When hasMore is true, repeat the call with cursor set to nextCursor, or with offset set to nextOffset when nextCursor is null."),returned:_("Number of subscribers returned."),truncated:c("Whether matches remain beyond the returned window. Same as pagination.hasMore.")},list_products:{products:y("product"),pagination:I("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:y("product"),created:_("Number of products created."),updated:_("Number of products updated.")},delete_product:{productId:O("Deleted product ID.")},attach_product_file:{product:j("product"),delivery:j("digital delivery file")},remove_product_file:{product:j("product")},upload_image_asset:{asset:j("hosted image asset"),imageBlock:I("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:j("product sync job"),jobId:O("Queued product sync job ID.")},list_tags:{tags:y("tag")},create_tag:{tag:j("tag")},update_tag:{tag:j("tag")},delete_tag:{tagId:O("Deleted tag ID.")},list_lists:{lists:y("list")},create_list:{list:j("list")},update_list:{list:j("list")},delete_list:{listId:O("Deleted list ID.")},add_subscribers_to_list:{list:j("list"),added:_("Number of subscribers added to the list."),skipped:_("Number of subscribers skipped.")},remove_subscribers_from_list:{list:j("list"),removed:_("Number of subscribers removed from the list."),skipped:_("Number of subscribers skipped.")},list_segments:{segments:y("segment")},create_segment:{segment:j("segment")},update_segment:{segment:j("segment")},delete_segment:{segmentId:O("Deleted segment ID.")},get_segment_count:{count:_("Number of subscribers matching the segment."),segmentId:O("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:y("audience sync")},list_ad_accounts:{adAccounts:y("ad account")},create_audience_sync:{audienceSync:j("audience sync")},update_audience_sync:{audienceSync:j("audience sync")},delete_audience_sync:{audienceSyncId:O("Deleted audience sync ID.")},sync_audience_now:{audienceSync:j("audience sync"),job:j("audience sync job"),jobId:O("Queued audience sync job ID.")},list_templates:{templates:y("email template"),pagination:I("Pagination metadata: limit, offset, count (this page), total (every email body) and hasMore. Page with offset when hasMore is true.")},get_template:{template:j("email template")},create_template:{template:j("email template")},update_template:{template:j("email template")},set_template_localization:{templateId:O("Localized template ID."),localization:j("template localization")},sync_template_localizations:{templateId:O("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:O("One queued locale code.")},queuedVariantCount:_("Number of localized variants queued for translation.")},delete_template:{templateId:O("Deleted template ID.")},list_email_components:{components:y("email component")},get_email_component:{component:j("email component")},get_default_email_component:{component:j("default email component for the slot")},set_default_email_component:{component:j("saved default email component")},create_email_component:{component:j("email component")},update_email_component:{component:j("email component")},delete_email_component:{id:O("Deleted email component ID.")},list_ab_tests:{abTests:y("A/B test")},get_ab_test:{abTest:j("A/B test")},get_ab_test_stats:{abTest:j("A/B test"),stats:j("A/B test statistics")},restart_ab_test:{abTest:j("A/B test")},update_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},update_ab_test:{abTest:j("A/B test")},create_ab_test:{abTest:j("A/B test")},add_ab_test_variant:{abTest:j("A/B test"),variant:j("A/B test variant")},delete_ab_test_variant:{abTest:j("A/B test"),variantId:O("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:O("Deleted A/B test ID.")},list_campaigns:{campaigns:y("campaign"),pagination:I("Campaign page window: `limit`, `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`. Keep calling with an advanced `offset` while `hasMore` is true to enumerate every campaign.")},get_campaign:{campaign:j("campaign")},get_campaign_audience:{campaignId:O("Campaign the audience was resolved for."),campaignName:O("Campaign name."),status:O("Campaign status."),audience:I("Resolved targeting: `type`, a plain-language `summary`, `isUnset` (true when scheduling would fall back to every active subscriber), resolved `lists` and `segments` with names and a `missing` flag, `filters`, `include`/`exclude` rules, and individual subscriber adjustments."),recipientCount:_("Number of subscribers matching the effective targeting right now."),targetLists:w1("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:j("email send, including copied-recipient identity and primary email send ID when applicable"),events:y("email delivery event")},list_email_sends:{emailSends:y("email send"),pagination:j("email send pagination"),retentionDays:_("Number of days sent-email rows remain queryable in this collection.")},get_recipient_suppression:{suppression:j("recipient suppression status")},remove_recipient_suppression:{removed:c("Whether stale bounce suppression was removed."),removedLocalBounce:c("Whether the platform-local bounce block was removed."),removedSesRegions:{type:"array",description:"AWS SES regions where a bounce suppression was removed.",items:O("One AWS SES region.")},remainingSuppression:j("recipient suppression status after cleanup")},create_campaign:{campaign:j("campaign")},update_campaign:{campaign:j("campaign")},schedule_campaign:{campaign:j("campaign"),scheduledAt:O("Scheduled send timestamp.")},unschedule_campaign:{campaign:j("draft campaign")},share_campaign:{shareUrl:O("Public anonymized view-in-browser URL for the campaign."),shareToken:O("Capability token embedded in the URL."),created:c("False when an already-active link was returned instead of minted.")},unshare_campaign:{revoked:c("False when the campaign had no active public link.")},share_template:{shareUrl:O("Public anonymized view-in-browser URL for the email."),shareToken:O("Capability token embedded in the URL."),created:c("False when an already-active link was returned instead of minted.")},unshare_template:{revoked:c("False when the email had no active public link.")},send_test_email:{emailSendId:O("Durable test email delivery ID."),recipientEmail:O("Test email recipient.")},send_test_sms:{smsSendId:O("Created test SMS send ID."),toPhone:O("Normalized E.164 destination phone.")},update_sms_number_label:{number:j("updated SMS number (label + brandPrefix override)")},cancel_campaign:{campaign:j("campaign")},pause_campaign:{campaign:j("campaign")},resume_campaign:{campaign:j("campaign")},delete_campaign:{campaignId:O("Deleted campaign ID.")},duplicate_campaign:{campaign:j("duplicated campaign")},resend_campaign_to_non_openers:{campaign:j("non-opener resend draft campaign"),estimatedNonOpenerCount:_("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:y("saved form")},create_form:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:j("saved form"),embed:I("Public action URL plus JavaScript, native form, and fetch snippets.")},list_popups:{popups:y("saved popup")},get_popup:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},create_popup:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},update_popup:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},get_popup_embed:{popup:j("saved popup"),embed:I("Script URL plus HTML, React, WordPress, and Shopify snippets.")},duplicate_popup:{popup:j("popup copy, created as a draft")},delete_popup:{popupId:O("Deleted popup ID.")},list_landing_pages:{landingPages:y("landing page")},get_landing_page:{landingPage:j("landing page")},create_landing_page:{landingPage:j("landing page")},update_landing_page:{landingPage:j("landing page")},duplicate_landing_page:{landingPage:j("landing page")},delete_landing_page:{landingPageId:O("Deleted landing page ID.")},publish_landing_page:{landingPage:j("landing page")},unpublish_landing_page:{landingPage:j("landing page")},connect_landing_page_domain:{landingPage:j("landing page"),domain:O("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:j("landing page"),domain:O("Landing page domain.")},list_sequences:{sequences:wM,pagination:I("Sequence page window: `limit` (null when limit and offset were both omitted and every sequence was returned), `offset`, `count` returned in this page, `total` matching the filters, and `hasMore`.")},get_sequence:{sequence:s1},list_sequence_enrollments:{sequenceId:O("Sequence ID these enrollments belong to."),sequenceName:O("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},enrollments:{type:"array",description:"Contact-level enrollments matching the filters, one row per enrollment token.",items:{type:"object",description:"One subscriber's enrollment in this sequence.",properties:{enrollmentId:O("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:O("Sequence ID."),subscriberId:O("Subscriber ID."),email:H0("Subscriber email address. Falls back to the address captured at enrollment when the subscriber record no longer exists, and is null when neither is known."),firstName:H0("Subscriber first name, or null when unset."),lastName:H0("Subscriber last name, or null when unset."),subscriberStatus:H0("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:O("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:O("Sequence node this enrollment is currently sitting on."),currentNodeType:O("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:O("Current sequence node label or email subject when available."),currentNodeMissing:c("Whether the current node no longer exists in the sequence graph."),enrollmentKey:O("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:O("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:H0("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:O("ISO 8601 timestamp of the last change to this enrollment. For a waiting enrollment this is when it arrived at its current node; the platform does not separately track node entry time."),failedReason:H0("Why this enrollment stopped, for status `failed`. Null for every other status and for failures recorded before this field existed. A reason repeated across enrollments on the same currentNodeId points at that step's configuration or content rather than at the contacts."),movedFromNodeId:H0("Step this enrollment was released from by move_sequence_enrollments, or null when it reached its current step on its own."),movedAt:H0("ISO 8601 timestamp of that release, or null when the enrollment was never moved."),moveReason:H0("Note recorded with that release, or null when none was given.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:I("Pagination metadata.")},send_sequence_test_email:{sequenceId:O("Sequence ID."),nodeId:O("Tested sequence email-step node ID."),results:Z1("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:s1,eventTrackingCode:O("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:I("Custom-event endpoint, payload contract, example payload, documentation URL, and get_integration_guide arguments."),requiredEvents:{type:"array",description:"Event names the application or an integration must send.",items:O("One required event name.")}},update_sequence:{sequence:Y3},update_sequence_node:{sequence:j("sequence")},update_sequence_nodes:{sequence:j("sequence")},edit_sequence_graph:{sequence:Y3},insert_sequence_step:{sequence:j("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:O("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:O("Inserted email template ID.")},insertedEmailCount:_("Number of email steps inserted."),addedBranchNodeId:O("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:I("Created path node IDs keyed by branch ID, plus else, in path order. Directly wired paths have empty arrays. Use a path's last node ID as afterNodeId to insert a nested branch on that path.")},enable_sequence:{sequenceId:O("Sequence ID."),status:O("Stored lifecycle status after the change."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},disable_sequence:{sequenceId:O("Sequence ID."),status:O("Stored lifecycle status after the change."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},duplicate_sequence:{sequence:s1,nodes:y("sequence node"),edges:y("sequence edge")},archive_sequence:{sequence:s1},unarchive_sequence:{sequence:s1},list_sequence_goals:{goals:y("sequence goal")},create_sequence_goal:{goal:j("sequence goal")},update_sequence_goal:{goal:j("sequence goal")},delete_sequence_goal:{goalId:O("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:j("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:j("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:O("Sequence ID."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},resume_sequence_enrollments:{sequenceId:O("Sequence ID."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...L$},enroll_subscribers_in_sequence:{sequence:j("sequence"),enrollments:y("sequence enrollment"),enrolled:_("Number of subscribers enrolled."),skipped:_("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:O("Sequence ID."),dryRun:c("Whether this call only reported matches instead of cancelling them."),target:I("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:_("Active/waiting enrollments matching the target when the request started."),cancelledCount:_("Enrollments cancelled by this call."),remainingCount:_("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:y("sequence enrollment sample (up to 50)"),hasMore:c("Whether more enrollments matched than the returned sample.")},move_sequence_enrollments:{sequenceId:O("Sequence ID."),dryRun:c("Whether this call only reported the batch instead of moving it."),fromNodeId:O("Step the enrollments were taken from."),targetNodeId:O("Step the enrollments were moved onto, resolved from the source step's next step when not supplied."),sort:O("Order the batch was selected in."),requestedLimit:_("limit as requested."),effectiveLimit:_("How many this call was allowed to move after the daily guardrail was applied."),matchedCount:_("Movable enrollments parked on fromNodeId when the request started."),movedCount:_("Enrollments moved by this call."),remainingCount:_("Movable enrollments still on fromNodeId. Repeat the same request while this is above zero."),skippedCount:_("Enrollments excluded because they are active, a worker is mid-step on them, or they are parked awaiting double opt-in. Only safely parked waiting tokens can be moved."),dailyLimit:w3("Applied daily guardrail, or null when none was requested."),movedInWindow:_("Moves onto targetNodeId already recorded in the rolling 24-hour window."),dailyRemaining:w3("How many more can be moved onto targetNodeId today, or null when no dailyLimit was requested."),enqueuedCount:_("Moved enrollments handed to the worker queue. Zero while the sequence is not running."),enqueueErrors:{type:"array",description:"Moved enrollments whose queue handoff failed. They stay active on the target step and are recovered by the stuck-enrollment sweeper.",items:I("One tokenId with its enqueue error.")},tagResult:w1("Tagging outcome for the moved contacts: tags, updated, unchanged, failed, failures. Null when no tags were requested."),enrollments:y("moved (or, on a dry run, would-move) sequence enrollment sample (up to 50)"),hasMore:c("Whether more enrollments matched than the returned sample.")},realign_sequence_enrollments:{sequenceId:O("Sequence ID."),dryRun:c("Whether this call only previewed the new wait times instead of writing them."),sendingWindow:w1("The sequence sending window realignment anchored on (timezone, startTime, endTime, days), or null when only per-step weekday gates applied."),scannedCount:_("Waiting enrollments inspected by this call."),realignedCount:_("Waiting enrollments moved earlier (or that would move, on a dry run)."),unchangedCount:_("Waiting enrollments left exactly as they were."),unchangedReasons:I("Counts per reason an enrollment did not move: already_at_window_start, already_due, day_not_allowed, no_shared_opening, no_window, not_email_bound, send_retry, raced."),requeueFailedCount:_("Enrollments whose new wait time was stored but whose wake-up could not be re-queued. The stuck-enrollment sweeper recovers these within a few minutes."),changes:y("realigned enrollment sample (up to 50) with waitUntil, newWaitUntil, and movedEarlierMinutes"),hasMore:c("Whether a per-call cap stopped the scan early. Continue with nextCursor while this is true."),nextCursor:O("Opaque continuation cursor to pass as cursor on the next call when hasMore is true."),status:O("For an applied request, queued while the background job is pending."),jobId:O("Background job ID to pass to get_sequence_enrollment_realignment.")},get_sequence_enrollment_realignment:{sequenceId:O("Sequence ID."),dryRun:c("Always false for an applied job."),status:O("queued, running, completed, or failed."),jobId:O("Background realignment job ID."),result:w1("Completed realignment result, including counts, changes, hasMore, and nextCursor; null until completion."),error:H0("Safe recovery guidance when the job failed, otherwise null.")},delete_sequence:{sequenceId:O("Deleted sequence ID.")},list_transactional_emails:{transactional:y("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:j("transactional email")},create_transactional_email:{transactional:j("transactional email")},update_transactional_email:{transactional:j("transactional email")},delete_transactional_email:{deleted:I("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:O("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},transactional:j("transactional email")},get_stats:{stats:I(`Account-wide delivery funnel for the requested window. ${f1}`),emailType:O("Applied structural email type filter when one was requested."),commerceForecast:j("Optional background-computed commerce AOV, 12-month customer value, and 90-day revenue forecast. Omitted when no snapshot is available; insufficient_data is returned only after eligibility was evaluated successfully.")},get_campaign_stats:{campaign:j("campaign"),stats:I(`Delivery funnel for this campaign. ${f1}`),clickedLinks:{type:"array",description:"Per-link click breakdown, most clicked first (top 20). Each entry has url, clicks, and percentage (that link's share of every recorded link click). Present only when the campaign has tracked link clicks.",items:I("One clicked link with url/clicks/share.")},polls:{type:"array",description:`Poll and NPS summaries. Each subscriber counts once per campaign poll block using their latest answer to that block; NPS entries include score, average, and promoter/passive/detractor counts. Multi-select polls set allowMultiple: true, count each subscriber once per selected option (answer percentages can sum past 100), and report totalResponses as the respondent count. To read the exact historical respondents with their answers and response times, call list_poll_responses with this campaignId (and the summary blockId to scope it). To build a reusable audience from one answer, use the summary blockId and this campaignId with create_segment. ${y1} A summary's attributeKey identifies the subscriber attribute that stores their current/latest response (a value list for multi-select polls) and may be overwritten by a later poll that reuses the key.`,items:I("One poll or NPS results summary.")},recommendations:I("Product recommendation funnel: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts (per-product impressions/clicks). Orders count when a subscriber buys a recommended product within 7 days of clicking it. Present only when the campaign rendered product recommendation blocks.")},list_poll_responses:{campaignId:O("Campaign the responses belong to."),blockId:O("Poll block the results were scoped to. Present only when blockId was requested."),responses:{type:"array",description:"Individual responses, newest answer first. Each entry has subscriberId, email, externalId, firstName, lastName, blockId, variant (options or nps), question, attributeKey (the subscriber attribute the answer was stored under), allowMultiple, answers (selected option labels), values (their stored values), and respondedAt. Only each subscriber's latest answer per block appears. email is null when the subscriber has since been deleted.",items:I("One respondent's latest answer.")},pagination:I("Pagination metadata: page, limit, total (response rows across every page; one row per subscriber per poll block), and totalPages. Keep paging while page < totalPages.")},get_transactional_stats:{transactional:j("transactional email"),stats:I(`Delivery funnel for this transactional email. ${f1}`),complaints:j("complaint count and rate for the selected transactional email"),clickedLinks:y("clicked link with click count and percentage share"),bounceBreakdown:j("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:j("human and machine open and click counts")},get_sequence_stats:{sequence:s1,stats:I(`Delivery funnel across every email step in this sequence. ${f1}`),steps:{type:"array",description:`Per-step delivery funnel: one entry per email step of the sequence, in graph order, each with its own sent/delivered/opened/clicked counts. Read this to answer "how many of step N went out" - do not recount list_sequence_events. Counts come from the retained event stream, so they are not limited to the 14-day list_email_sends history. ${f1}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:_("1-based position of this email step in graph order. Step 4 is the fourth email a contact receives on the traversed path; on a branching graph, positions are assigned by traversal, so cross-check nodeId when a sequence forks."),nodeId:O("Automation node ID of this email step. Pass it to list_sequence_events or list_email_sends as automationNodeId to reach the individual recipients behind these counts, and it is the emailId that list_email_metrics reports for sequence emails."),subject:H0("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:I(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${f1}`),failedCount:_("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:Z1("Up to 20 of the failed contacts on this step, as { subscriberId, email, failedAt, failedReason }.")},required:["step","nodeId","stats"],additionalProperties:!0}},enrollmentCounts:{type:"object",description:"Live enrollment-token counts for this sequence. Includes only active and waiting enrollments and is always a current snapshot, independent of historical period/start/end filters.",properties:{active:_("Active enrollment count."),waiting:_("Waiting enrollment count."),total:_("Total active plus waiting enrollment count."),byCurrentNode:{type:"array",description:"Live active and waiting enrollment counts grouped by the token's current sequence node.",items:{type:"object",description:"Enrollment counts for one current sequence node.",properties:{currentNodeId:O("Current sequence node ID."),currentNodeType:O("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:O("Current sequence node label or email subject when available."),currentNodeMissing:c("Whether the current node no longer exists in the sequence graph."),active:_("Active enrollment count at this node."),waiting:_("Waiting enrollment count at this node."),total:_("Total active plus waiting enrollment count at this node.")},required:["currentNodeId","currentNodeMissing","active","waiting","total"],additionalProperties:!1}}},required:["active","waiting","total","byCurrentNode"],additionalProperties:!1},enrollmentSkipped:{type:"object",description:"Trigger matches where an unsubscribed or bounced contact could not be enrolled, including the total count and counts grouped by reason. Uses the requested period or start/end range; without an explicit range, this field defaults to the last 30 days.",properties:{count:_("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:_("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:I("Product recommendation funnel aggregated across the sequence's email nodes: impressions, recipients, clicks, clickers, orders, legacy revenueCents, currency-safe revenueByCurrency totals, and topProducts. Present only when the sequence rendered product recommendation blocks.")},list_campaign_events:{events:y("campaign email event"),pagination:I("Pagination metadata.")},list_sequence_events:{events:y("sequence email event"),pagination:I("Pagination metadata.")},list_email_metrics:{emails:{type:"array",description:"One entry per email in scope: each campaign and each sequence email step, sorted by the requested sort/order.",items:{type:"object",description:"Metrics for one campaign or one sequence email step.",properties:{emailType:{type:"string",enum:["campaign","sequence"],description:"Whether this row is a campaign or a sequence email."},emailId:O("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:O("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:H0("Campaign ID, or null for sequence emails."),sequenceId:H0("Sequence ID, or null for campaigns."),sequenceName:H0("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:H0("Automation node ID of this step, or null for campaigns. Pass it as automationNodeId to list_sequence_events or list_email_sends to reach the recipients behind these counts."),step:{type:["number","null"],description:"1-based position of this email in its sequence, counted in graph order, or null for campaigns. Matches the step number in get_sequence_stats steps[]."},stats:I(`Delivery funnel for this email alone. ${f1}`),conversions:_("Attributed conversions credited to this email."),revenueCents:_("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:I(`Summed funnel across every email matching the filters, not just the returned page, plus \`emails\` (the number of matching emails), \`conversions\`, and \`revenueCents\`. Read totals.sent for "how many of this step went out in total". ${f1}`),pagination:I("Pagination metadata."),sort:O("Sort field the response was ordered by."),order:O("Sort order the response was ordered by."),step:_("Echo of the step filter, present only when one was requested."),sequenceIds:{type:"array",description:"Echo of the sequence IDs the breakdown was scoped to, present only when scoped.",items:O("Sequence ID.")}},get_subscriber_activity:{activity:y("subscriber activity event"),subscribers:y("subscriber"),pagination:I("Pagination metadata.")},list_team_members:{members:y("team member"),invitations:y("team invitation")},invite_team_member:{invitation:j("team invitation")},cancel_team_invitation:{invitationId:O("Cancelled invitation ID.")},list_conversations:{conversations:y("inbox conversation"),pagination:I("Pagination metadata.")},get_conversation:{conversation:j("inbox conversation"),messages:y("conversation message")},reply_to_conversation:{conversation:j("inbox conversation"),message:j("conversation message")},update_conversation_status:{conversation:j("inbox conversation")},mark_conversation_read:{conversation:j("inbox conversation")},list_webhooks:{webhooks:y("outbound webhook")},create_webhook:{webhook:j("outbound webhook")},update_webhook:{webhook:j("outbound webhook")},delete_webhook:{webhookId:O("Deleted outbound webhook ID.")},test_webhook:{webhook:j("outbound webhook"),delivery:j("test webhook delivery")},list_webhook_deliveries:{deliveries:y("webhook delivery")},replay_webhook_delivery:{delivery:j("webhook delivery"),job:j("webhook replay job")},generate_email:{email:j("generated email"),html:O("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:I("One generated email block.")},subject:O("Generated subject line."),previewText:O("Generated inbox preview text.")},generate_sequence:{sequence:j("persisted AI-generated sequence draft"),deprecated:c("Always true for this deprecated alias."),deprecationMessage:O("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:O("One generated subject line.")},variants:y("generated subject line variant")},generate_sms:{prompt:O("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:I("One generated SMS message.")}},get_sms_settings:{sms:I("SMS add-on status: enabled, planEligible, creditsBalance, brandPrefix (account-wide default), numbers (each with id, e164, label tag, brandPrefix override, status), readyToSend (paid plan or credits plus an active number).")},submit_feedback:{},render_email:{html:O("Email-safe HTML document, rendered exactly as it would be sent."),subject:O("Subject line with merge tags resolved."),previewText:H0("Inbox preview text with merge tags resolved, or null when unset."),locale:O("Localization locale the render resolved to."),personalized:c("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:c("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:Z1(`Merge tags that rendered as an empty string, as [{ tag, reason }]. reason "unknown" means nothing provides that name, so it stays empty for every recipient - usually a typo or a tag copied from another platform. reason "no_value" means the name is recognized, or could not be checked, but is blank for this contact. A name is only called unknown when the render had a source to check it against. Without the contact's attributes nothing is checkable, since a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass a stored subscriberId or an inline subscriber carrying customAttributes. Beyond that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event; {{recommendedProducts.*}} needs a stored subscriberId the catalog has something to recommend for; and {{discount.*}} is only checkable on a sequence step whose incoming paths all run the same discount step, never on a standalone template. Rendering a transactional email is checkable only when variables is passed, because its tags come from the variables of each send call and carry no prefix marking them. Otherwise those tags land in no_value rather than in unknown. An optional attribute this contact never had set is kept out of unknown by checking the names other contacts in the account carry, which needs the subscribers:read scope; a key without it may report such a name as unknown. An empty array means every tag in the email resolved.`),entity:I("Which entity was rendered: type, id, and variantId.")}};function zM($){let W=HM[$];if(W===void 0)throw Error(`MCP tool "${$}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${$}\` MCP tool.`,properties:{...bM,...W,...AQ.has($)?YM:{}},additionalProperties:!0}}function H3($){return{...$,outputSchema:zM($.name)}}function z3($){if(h($))return $;if(Array.isArray($))return{items:$};return{value:$}}var D3=[{name:"list_ab_tests",description:"List A/B tests and their variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Optional sequence ID to filter automation A/B tests."}}}},{name:"get_ab_test",description:"Get A/B test details, variants, and per-locale localization sync status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"}},required:["abTestId"]}},{name:"get_ab_test_stats",description:"Get A/B test aggregate stats and per-variant stats. Supports period or custom start/end ranges.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},period:{type:"string",description:"Optional period: 1h, 24h, 7d, 30d, or 90d."},start:{type:"string",description:"Custom range start as ISO 8601. Requires end."},end:{type:"string",description:"Custom range end as ISO 8601. Requires start."},includeMachineEngagement:h0},required:["abTestId"]}},{name:"restart_ab_test",description:"Run another sequence A/B test after a winner is selected. By default the winner becomes the new control; pass sourceVariantId to use another variant as the control email.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to restart"},sourceVariantId:{type:"string",description:"Optional variant ID to use as the new control email. Defaults to the selected winner."},testType:{type:"string",description:"Optional test type: subject or content."},winnerThreshold:{type:"number",description:"Optional number of subscribers before selecting a winner. Must be from 10 to 1000."},variantCount:{type:"number",description:"Optional total variants including the control. Must be from 2 to 4."}},required:["abTestId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update an A/B test variant. Campaign variants are editable only in draft. Sequence variants can be edited after activity with confirmLiveChange, but earlier sends stay unchanged and combined results may no longer be accurate. Provide at least one of subject, previewText, html, or blocks. Use either html or blocks, not both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID"},subject:{type:"string",description:"Variant subject line"},previewText:{type:"string",description:"Variant preview text. Pass an empty string to clear it."},html:{type:"string",description:`Replacement HTML body. Mutually exclusive with blocks. ${U0}`},blocks:{type:"array",description:`${O1}${d1} Mutually exclusive with html.`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the sequence is active, the test is no longer a draft, or it has recorded activity. The edit affects future sends and can make combined results inaccurate."}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test",description:"Update A/B test settings. Campaign tests use testPercentage, testDurationMinutes, and winnerCriteria. Sequence tests use testType, winnerThreshold, and winnerCriteria; changing live or already-used sequence settings requires confirmLiveChange. Provide at least one setting.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50."},testDurationMinutes:{type:"number",description:"Campaign-only test duration in minutes, from 15 to 1440."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Applies to both campaign and sequence tests."},testType:{type:"string",enum:["subject","content"],description:"Sequence-only variant strategy. When winnerCriteria is omitted, subject defaults to open_rate and content defaults to click_rate."},winnerThreshold:{type:"number",description:"Sequence-only number of recipients before selecting a winner, from 10 to 1000."},confirmLiveChange:{type:"boolean",description:"Required as true when sequence settings affect an active test or a test with recorded activity."}},required:["abTestId"],additionalProperties:!1}},{name:"create_ab_test",description:"Create a campaign A/B test or convert a sequence email node into a typed A/B test node. Provide exactly one of campaignId or automationNodeId. Control variant A is created automatically from the current email. Campaign tests may add variants later; automationNodeId conversions require at least one variants[] entry to compete with control variant A.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Draft campaign ID. Mutually exclusive with automationNodeId."},automationNodeId:{type:"string",description:"Sequence email-node ID to convert to action_ab_test. Mutually exclusive with campaignId."},confirmLiveChange:{type:"boolean",description:"Required as true when converting an email node in an active sequence."},name:{type:"string",description:"Optional A/B test name."},testPercentage:{type:"number",description:"Campaign-only percentage of the audience used for the test phase, from 5 to 50. Defaults to 20. Sequence tests use winnerThreshold instead."},testDurationMinutes:{type:"number",description:"Campaign-only test phase duration in minutes, from 15 to 1440. Defaults to 240. Sequence tests select after winnerThreshold recipients instead."},winnerCriteria:{type:"string",enum:["open_rate","click_rate"],description:"Winner selection criteria. Campaign tests default to open_rate. For sequence tests, an explicit value overrides the testType default."},testType:{type:"string",enum:["subject","content"],description:"Sequence A/B test variant strategy. Subject defaults to open_rate and content defaults to click_rate unless winnerCriteria is explicit. Defaults to content."},winnerThreshold:{type:"number",description:"Sequence test sample size from 10 to 1000. Defaults to 100."},variants:{type:"array",maxItems:4,description:"Extra variants to create in addition to control variant A. Optional for campaign tests; automationNodeId conversions require at least one entry.",items:{type:"object",properties:{subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${O1}${d1}`,items:{type:"object"}}},required:["subject"]}}}}},{name:"add_ab_test_variant",description:"Add a variant to a draft campaign or sequence A/B test. Sequence variants receive their own editable email template. Variants cannot be added after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},subject:{type:"string",description:"Variant subject line."},previewText:{type:"string",description:"Variant preview text."},blocks:{type:"array",description:`${O1}${d1}`,items:{type:"object"}},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because new variants immediately enter the live rotation."}},required:["abTestId","subject"]}},{name:"delete_ab_test_variant",description:"Permanently delete a variant from a draft campaign or sequence A/B test. This cannot be undone. Variant A is the control and cannot be deleted, and the test must keep at least the minimum number of variants. Variants cannot be removed after the test has started. Sequence tests whose parent sequence is active require confirmLiveChange.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID"},variantId:{type:"string",description:"A/B test variant ID to delete."},confirmLiveChange:{type:"boolean",description:"Required as true when the A/B test belongs to an active sequence, because deletion immediately changes the live rotation."}},required:["abTestId","variantId"]}},{name:"delete_ab_test",description:"Permanently delete a campaign A/B test and all of its variants. This cannot be undone. Running tests (testing or winner_selected) cannot be deleted, and the linked campaign must be in draft or rejected status.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"A/B test ID to delete."}},required:["abTestId"]}}];var F3=[{name:"get_account",description:`Get current account information including available companies, the current API key's permission scopes, and the API Keys management URL. Call this after a missing-scope error to inspect access and find the replacement-key settings. 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
|
|
|
33
|
-
The response shows 'companies' (all available) and 'selectedCompanyId' (currently active). All subsequent operations will use the selected company unless you pass a companyId override.`,inputSchema:{type:"object",properties:{}}},{name:"select_company",description:"Select which company to operate on (for user-scoped API keys with access to multiple companies). Use get_account to see available companies. After selecting, all subsequent operations will use this company unless you pass a companyId override.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to select (from get_account's companies list)"}},required:["companyId"]}},{name:"get_app_urls",description:"Generate Sequenzy dashboard URLs for known resource IDs. Use this when the user asks where to review or edit a generated sequence, campaign, template, or company settings. If companyId is omitted, the selected/current company is used when available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},campaignId:{type:"string",description:"Campaign ID for the campaign editor URL."},landingPageId:{type:"string",description:"Landing page ID for the landing page editor URL."},sequenceId:{type:"string",description:"Sequence ID for the sequence editor URL."},templateId:{type:"string",description:"Template/email ID for the email editor URL."},emailId:{type:"string",description:"Email ID for the email editor URL."},transactionalId:{type:"string",description:"Transactional email ID."},emailSendId:{type:"string",description:"Email send ID for the sent email detail URL."},domainId:{type:"string",description:"Sending domain ID."},status:{type:"string",description:"Status for campaign/sequence list URLs."},settingsTab:{type:"string",description:"Settings tab slug, e.g. integrations, domain, tracking, api-keys, team."}}}},{name:"create_company",description:"Create a new company/brand. Requires a personal account key (seq_user_...); a company/workspace-scoped key (seq_live_.../ek_...) is bound to its one company and is rejected, because it could never access the company it created. This will parse your website to extract brand information. The tool polls every 20 seconds until the company is fully processed (typically 30-60 seconds).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Company name (optional, will be extracted from domain if not provided)"},domain:{type:"string",description:"The company's website domain (e.g., example.com)"}},required:["domain"]}},{name:"get_company",description:"Get company details, processing status, product info, brand colors, AI writing context, reply-tracking settings, and effective email localization settings",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to check"}},required:["companyId"]}},{name:"update_company",description:"Edit company product info, brand context, the default email theme, reply-tracking settings, and account-wide sending identity defaults. fromEmail must use a verified sending domain; replyTo may be any valid mailbox. Missing sender/reply profiles are created automatically. Send fromName/replyToName on their own to rename the display name of the existing default profile without changing its address, or pair them with senderProfileId/replyProfileId (from list_sender_profiles) to rename a specific profile. Provide at least one editable field. Profile, branding, and AI-context fields need the company_profile:manage scope; the sending identity and reply-tracking fields additionally need companies:manage.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},name:{type:"string",description:"Company display name."},description:{type:"string",description:"Short product or company summary for AI writing context."},logoUrl:{type:"string",description:"Public logo URL."},founderName:{type:"string",description:"Founder or sender name for personal email signatures."},primaryColor:{type:"string",description:"Primary brand color as a 6-digit hex value, e.g. #f97316."},brandColors:{type:"object",description:"Stored brand color object. Prefer primaryColor for the main color.",additionalProperties:!0},valueProps:{type:"array",description:"Value propositions, usually objects with title and description.",items:{type:"object",additionalProperties:!0}},testimonials:{type:"array",description:"Testimonials, usually objects with quote/text and author.",items:{type:"object",additionalProperties:!0}},toneVoice:{type:"string",description:"Tone of voice guidance for AI-written content."},companyContext:{type:"string",description:"Basic product/company knowledge AI should use when writing emails."},emailLengthPreference:{type:"string",description:"Email length preference: concise, balanced, or detailed. New workspaces default to concise."},socialLinks:{type:"object",description:"Social profile URLs keyed by platform.",additionalProperties:{type:"string"}},privacyPolicyUrl:{type:"string",description:"Privacy policy URL."},termsUrl:{type:"string",description:"Terms of service URL."},address:{type:"string",description:"Physical mailing address for email footers."},language:{type:"string",description:"Primary language code, e.g. en, es, de."},pricing:{type:"object",description:"Pricing information used as product context.",additionalProperties:!0},fontFamily:{type:"string",description:"Default email font family stack."},emailTheme:{type:["object","null"],description:"Default email theme applied to campaigns, sequences, and transactional email. Partial update: omitted fields keep their current value (or the preset default). Pass null to reset to the platform default theme. Numeric values are clamped to supported ranges.",properties:{presetId:{type:"string",description:"Theme preset to base the theme on: default, soft, editorial, or bold."},colors:{type:"object",description:"6-digit hex colors.",properties:{primary:{type:"string"},background:{type:"string"},surface:{type:"string"},text:{type:"string"},mutedText:{type:"string"},heading:{type:"string"},border:{type:"string"},link:{type:"string"}},additionalProperties:!1},typography:{type:"object",description:"Numeric type settings.",properties:{baseFontSize:{type:"number"},leadFontSize:{type:"number"},baseLineHeight:{type:"number"},heading1Size:{type:"number"},heading2Size:{type:"number"},heading3Size:{type:"number"},buttonFontSize:{type:"number"}},additionalProperties:!1},layout:{type:"object",description:"Numeric layout settings.",properties:{contentWidth:{type:"number"},containerPaddingX:{type:"number"},containerPaddingY:{type:"number"},blockSpacing:{type:"number"},baseRadius:{type:"number"},buttonRadius:{type:"number"},sectionPadding:{type:"number"},buttonPaddingX:{type:"number"},buttonPaddingY:{type:"number"},borderedBlockPadding:{type:"number"}},additionalProperties:!1}},additionalProperties:!1},emailDirection:{type:"string",description:"Default email text direction: ltr or rtl."},senderProfileId:{type:"string",description:"Make this existing sender profile the account-wide default, and the one fromName renames. Get IDs from list_sender_profiles. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"Set the account-wide default From address. Its domain must already be configured and verified."},fromName:{type:"string",description:"Display name of the default From profile. Sent alone it renames the current default profile; with senderProfileId it renames that profile; with fromEmail it names the profile for that address. If the address already has several display names, pass senderProfileId to say which one to rename."},replyProfileId:{type:"string",description:"Make this existing reply profile the account-wide default, and the one replyToName renames. Get IDs from list_sender_profiles. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Set the account-wide default Reply-To address. Creates a reply profile when needed."},replyToName:{type:"string",description:"Display name of the default Reply-To profile. Sent alone it renames the current default profile; with replyProfileId it renames that profile; with replyTo it names the profile for that address."},replyTrackingEnabled:{type:"boolean",description:"Enable or disable inbound reply capture for this company."},replyTrackingDomainMode:{type:"string",description:"Reply-tracking domain mode: sequenzy for the managed domain or custom for a configured custom domain."},forwardReplies:{type:"boolean",description:"Enable or disable forwarding captured replies to the configured mailbox."}}}},{name:"get_shopify_automation_settings",description:"Get the connected Shopify store's automation settings: browse abandonment (emails shoppers who viewed a product but didn't buy), cart abandonment (fires ecommerce.cart_abandoned with the full cart after the cart sits inactive), and price drop alerts (emails recent viewers when a product's price falls). Returns the effective values with platform defaults applied.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_shopify_automation_settings",description:"Update the connected Shopify store's browse-abandonment, cart-abandonment, and/or price-drop automation settings. Partial update: omitted sections are untouched, omitted fields within a section keep their current value, and passing null for a section resets it to the platform defaults (browse abandonment: on, 2h delay, 24h cooldown; cart abandonment: on, 1h inactivity, 24h cooldown; price drop: on, 5% minimum drop, 30-day viewer lookback, 7-day cooldown).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},browseAbandonment:{type:["object","null"],description:"Browse abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours to wait after a product view before checking for abandonment (default 2)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between browse-abandoned events per subscriber (default 24)."}},additionalProperties:!1},cartAbandonment:{type:["object","null"],description:"Cart abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours of cart inactivity before the cart counts as abandoned (default 1)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between cart-abandoned events per subscriber (default 24)."}},additionalProperties:!1},priceDrop:{type:["object","null"],description:"Price drop settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},minPercent:{type:"number",exclusiveMinimum:0,maximum:95,description:"Minimum price decrease percent to alert on (default 5)."},lookbackDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"How many days back product viewers qualify as the audience (default 30)."},cooldownDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"Minimum days between price-drop events per subscriber and product (default 7)."}},additionalProperties:!1}},additionalProperties:!1}},{name:"get_sync_rules",description:"Get the company's sync rules: the automatic tag changes applied when events fire (e.g. order placed -> add a tag). New companies start with no rules. Returns the effective rules plus isDefault, which is true when the company has explicitly opted into the inherited SaaS/ecommerce platform preset.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_sync_rules",description:"Replace the company's sync rules. Pass the FULL rule set (fetch with get_sync_rules first and edit it - this is not a partial update), [] to disable rules, or null to opt into the inherited SaaS/ecommerce platform preset. Each rule: { triggerEvent, actions: { addTags, removeTags }, conditions? }. Conditions support requiresTags, requiresNotTags, and purchasedProduct ({ tags?, collectionIds?, productTypes?, vendors? }) which matches products on commerce events - e.g. tag buyers of products carrying a given product tag.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncRules:{type:["array","null"],description:"Full replacement rule set. Use [] to disable sync rules, or null to opt into the inherited SaaS/ecommerce platform preset.",items:{type:"object",properties:{triggerEvent:{type:"string",description:"Event name that triggers the rule, e.g. ecommerce.order_placed or saas.purchase."},actions:{type:"object",properties:{addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}}},required:["addTags","removeTags"],additionalProperties:!1},conditions:{type:"object",properties:{requiresTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has ALL of these tags."},requiresNotTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has NONE of these tags."},purchasedProduct:{type:"object",description:"For commerce events with product context: rule only applies when a product on the event matches every specified selector.",properties:{tags:{type:"array",items:{type:"string"}},collectionIds:{type:"array",items:{type:"string"}},productTypes:{type:"array",items:{type:"string"}},vendors:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},required:["triggerEvent","actions"],additionalProperties:!1}}},required:["syncRules"],additionalProperties:!1}},{name:"create_api_key",description:"Create a new API key for a company. Use this when setting up Sequenzy integration in a project. The returned key should be saved to the project's .env file as SEQUENZY_API_KEY. The key can only be retrieved once at creation time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the key for"},name:{type:"string",description:"Optional name for the API key (e.g., 'Production', 'Development')"},preset:{type:"string",description:"Optional permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Defaults to full_access when both preset and scopes are omitted; prefer agent_safe when creating a key for an AI agent."},scopes:{type:"array",description:"Optional explicit API key permission scopes. If provided, this overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId"]}},{name:"request_api_key_handoff",description:"Prepare an owner-confirmed handoff link for creating or rotating an API key. Use this when key management fails because the active key is missing api_keys:manage - that scope fails closed on purpose, and this is the supported way forward instead of asking the user to reason about the dashboard themselves. Returns a URL that opens the dashboard's create-key form with the requested name and permissions already filled in. IMPORTANT: this creates nothing and never returns a key. Give the URL to the workspace owner and stop; they review the form, click Create, and copy the new key from the browser. To rotate, pass replaceApiKeyId (or the literal string 'current' for the key you are authenticated with) and the dashboard offers to revoke the predecessor after the replacement is created. Requires only account:read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Suggested name for the new key (e.g., 'Production sync (rotated)')."},preset:{type:"string",description:"Suggested permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Prefer agent_safe for an AI agent key."},scopes:{type:"array",description:"Suggested explicit permission scopes. Overrides preset. Unsupported scopes are rejected here rather than silently dropped from the owner's form.",items:{type:"string"}},replaceApiKeyId:{type:"string",description:"ID of the key the new one replaces, so the owner can revoke it in the same visit. Pass 'current' for the key this session is authenticated with; its ID is also in get_account under apiKeyPermissions.activeKey.id."}}}},{name:"list_api_keys",description:"List company-scoped API keys as non-secret metadata. Returns IDs, names, prefixes, permissions, usage timestamps, and whether each key is the active credential. It never returns a plain key or stored key hash. Use this before revoke_api_key or delete_api_key to identify the exact unused key.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID whose API keys should be listed"}},required:["companyId"]}},{name:"update_api_key",description:"Rename a company-scoped API key or replace its permissions in place, without issuing a new key. Use this when a call fails with a missing-scope error: the key value stays the same, so no client has to be re-wired, and added permissions apply on the next retry. Removed permissions may remain usable for up to five minutes while API caches expire. preset and scopes REPLACE the current selection rather than merging into it - call list_api_keys first and pass the full set you want. Returns non-secret metadata only.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"},name:{type:"string",description:"New human-readable name for the key"},preset:{type:"string",description:"Replacement permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender."},scopes:{type:"array",description:"Replacement explicit permission scopes. Overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId","apiKeyId"]}},{name:"revoke_api_key",description:"Permanently revoke a company-scoped API key by ID. The response contains non-secret metadata only. Call list_api_keys first and compare the ID, name, prefix, and isCurrent flag because revoking a key cannot be undone and may invalidate the active credential.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"delete_api_key",description:"Compatibility alias for revoke_api_key. Permanently delete a company-scoped API key by ID and return non-secret metadata only. Call list_api_keys first to verify the exact target.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"list_websites",description:"List configured sending domains with separate DNS verification, sending readiness, and SPF, DKIM, and MAIL FROM status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."}}}},{name:"add_sending_domain",description:"Add and configure a sending domain. Publish every cohort-specific DNS record returned, including DMARC when present, before calling verify_sending_domain.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Sending domain to add (for example, mail.example.com)."}},required:["domain"]}},{name:"add_website",description:"Compatibility alias for add_sending_domain. Adds a sending domain and returns the DNS records required for setup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to add (e.g., example.com)"}},required:["domain"]}},{name:"check_website",description:"Read a sending domain's separate DNS verification, sending readiness, and SPF, DKIM, MAIL FROM diagnostics. Use verify_sending_domain to run a fresh DNS check.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to check"}},required:["domain"]}},{name:"verify_sending_domain",description:"Run a fresh DNS check for a configured sending domain and return DNS verification separately from sending readiness. A DNS-verified domain may still be activating; when readyToSend is false, read readiness.reason rather than the DKIM/SPF/MAIL FROM record statuses, which describe DNS only.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Configured sending domain to verify."}},required:["domain"]}},{name:"list_integrations",description:"List connected integrations (Stripe, Shopify, Supabase, Clerk, WooCommerce, ad platforms, and so on) with connection status, sync state, last sync time, and last sync error. Read-only: credentials, access tokens, and webhook secrets are never returned. Use this to audit which external systems feed this account and whether their syncs are healthy.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},includeInactive:{type:"boolean",description:"Include disconnected/inactive integrations. Defaults to false (active only)."}}}},{name:"list_sender_profiles",description:"List sender (From) profiles and reply-to profiles for the company, including which are the account defaults and whether each sender address has verified DNS plus a ready home transport. Use this to audit sending identity before scheduling, or to pick a valid senderProfileId/replyProfileId for create_campaign or update_campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_sender_profile",description:"Rename one sender (From) or reply-to profile in place, without changing which profile is the account default. Use this to standardize a display name across the several identities a mailbox may carry, e.g. renaming 'Viraj from SnapCount' to 'SnapCount'. Get IDs from list_sender_profiles. Only the display name changes: the address, its sending domain, and the account-wide default From/Reply-To selection are untouched, and existing campaigns and sequences pinned to this profile pick up the new name. To change which profile is the default instead, use update_company with senderProfileId/replyProfileId. A company cannot have two sender identities with the same name on one address, so a colliding rename is rejected and reports the ID already using that name. Requires the companies:manage scope.",inputSchema:{type:"object",properties:{profileId:{type:"string",description:"ID of the profile to rename, from list_sender_profiles. Sender profile IDs come from senderProfiles, reply-to IDs from replyProfiles."},name:{type:"string",description:"New display name, e.g. 'SnapCount'. Trimmed; must be non-empty and 255 characters or fewer."},type:{type:"string",enum:["sender","reply"],description:"Which list profileId came from. Defaults to sender. Pass reply to rename a reply-to profile."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["profileId","name"]}},{name:"get_sending_status",description:`Check whether company-level email sending is active, paused, or suspended, and what it takes to restore it. Call this FIRST whenever a send, test send, or sequence step fails for a reason that is not a validation error, and whenever the account reports a bounce or complaint rate problem.
|
|
33
|
+
The response shows 'companies' (all available) and 'selectedCompanyId' (currently active). All subsequent operations will use the selected company unless you pass a companyId override.`,inputSchema:{type:"object",properties:{}}},{name:"select_company",description:"Select which company to operate on (for user-scoped API keys with access to multiple companies). Use get_account to see available companies. After selecting, all subsequent operations will use this company unless you pass a companyId override.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to select (from get_account's companies list)"}},required:["companyId"]}},{name:"get_app_urls",description:"Generate Sequenzy dashboard URLs for known resource IDs. Use this when the user asks where to review or edit a generated sequence, campaign, template, or company settings. If companyId is omitted, the selected/current company is used when available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},campaignId:{type:"string",description:"Campaign ID for the campaign editor URL."},landingPageId:{type:"string",description:"Landing page ID for the landing page editor URL."},sequenceId:{type:"string",description:"Sequence ID for the sequence editor URL."},templateId:{type:"string",description:"Template/email ID for the email editor URL."},emailId:{type:"string",description:"Email ID for the email editor URL."},transactionalId:{type:"string",description:"Transactional email ID."},emailSendId:{type:"string",description:"Email send ID for the sent email detail URL."},domainId:{type:"string",description:"Sending domain ID."},status:{type:"string",description:"Status for campaign/sequence list URLs."},settingsTab:{type:"string",description:"Settings tab slug, e.g. integrations, domain, tracking, api-keys, team."}}}},{name:"create_company",description:"Create a new company/brand. Requires a personal account key (seq_user_...); a company/workspace-scoped key (seq_live_.../ek_...) is bound to its one company and is rejected, because it could never access the company it created. This will parse your website to extract brand information. The tool polls every 20 seconds until the company is fully processed (typically 30-60 seconds).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Company name (optional, will be extracted from domain if not provided)"},domain:{type:"string",description:"The company's website domain (e.g., example.com)"}},required:["domain"]}},{name:"get_company",description:"Get company details, processing status, product info, brand colors, AI writing context, reply-tracking settings, and effective email localization settings",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"The company ID to check"}},required:["companyId"]}},{name:"update_company",description:"Edit company product info, brand context, the default email theme, reply-tracking settings, and account-wide sending identity defaults. fromEmail must use a verified sending domain; replyTo may be any valid mailbox. Missing sender/reply profiles are created automatically. Send fromName/replyToName on their own to rename the display name of the existing default profile without changing its address, or pair them with senderProfileId/replyProfileId (from list_sender_profiles) to rename a specific profile. Provide at least one editable field. Profile, branding, and AI-context fields need the company_profile:manage scope; the sending identity and reply-tracking fields additionally need companies:manage.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If omitted, uses the selected/current company when available."},name:{type:"string",description:"Company display name."},description:{type:"string",description:"Short product or company summary for AI writing context."},logoUrl:{type:"string",description:"Public logo URL."},founderName:{type:"string",description:"Founder or sender name for personal email signatures."},primaryColor:{type:"string",description:"Primary brand color as a 6-digit hex value, e.g. #f97316."},brandColors:{type:"object",description:"Stored brand color object. Prefer primaryColor for the main color.",additionalProperties:!0},valueProps:{type:"array",description:"Value propositions, usually objects with title and description.",items:{type:"object",additionalProperties:!0}},testimonials:{type:"array",description:"Testimonials, usually objects with quote/text and author.",items:{type:"object",additionalProperties:!0}},toneVoice:{type:"string",description:"Tone of voice guidance for AI-written content."},companyContext:{type:"string",description:"Basic product/company knowledge AI should use when writing emails."},emailDesignPrompt:{type:"string",description:"Art direction for AI-designed emails: layout, density, which sections belong in an email, imagery, CTA prominence, reference brands. Steers design; toneVoice steers copy. Overrides the default composition rules. When empty, the next email generation prefills it with the direction derived from the brand, so read the current value from get_company before editing. Pass an empty string to reset - the next generation refills it."},emailLengthPreference:{type:"string",description:"Email length preference: concise, balanced, or detailed. New workspaces default to concise."},socialLinks:{type:"object",description:"Social profile URLs keyed by platform.",additionalProperties:{type:"string"}},privacyPolicyUrl:{type:"string",description:"Privacy policy URL."},termsUrl:{type:"string",description:"Terms of service URL."},address:{type:"string",description:"Physical mailing address for email footers."},language:{type:"string",description:"Primary language code, e.g. en, es, de."},pricing:{type:"object",description:"Pricing information used as product context.",additionalProperties:!0},fontFamily:{type:"string",description:"Default email font family stack."},emailTheme:{type:["object","null"],description:"Default email theme applied to campaigns, sequences, and transactional email. Partial update: omitted fields keep their current value (or the preset default). Pass null to reset to the platform default theme. Numeric values are clamped to supported ranges.",properties:{presetId:{type:"string",description:"Theme preset to base the theme on: default, soft, editorial, or bold."},colors:{type:"object",description:"6-digit hex colors.",properties:{primary:{type:"string"},background:{type:"string"},surface:{type:"string"},text:{type:"string"},mutedText:{type:"string"},heading:{type:"string"},border:{type:"string"},link:{type:"string"},buttonText:{type:"string",description:"Label color for solid buttons. Omit to auto-derive a readable color from the button background."}},additionalProperties:!1},typography:{type:"object",description:"Numeric type settings.",properties:{baseFontSize:{type:"number"},leadFontSize:{type:"number"},baseLineHeight:{type:"number"},heading1Size:{type:"number"},heading2Size:{type:"number"},heading3Size:{type:"number"},buttonFontSize:{type:"number"},buttonFontWeight:{type:"number",description:"CTA label weight, 400-800."},headingFontWeight:{type:"number",description:"Heading weight applied to all heading levels, 300-900. Omit for the per-level defaults."},headingFontFamily:{type:"string",description:"Font stack for headings when it differs from the email body font. Omit so headings inherit the email font."},headingLetterSpacing:{type:"number",description:"Heading letter spacing in pixels (negative = tighter), clamped to -2..4. Omit for natural tracking."}},additionalProperties:!1},buttonStyle:{type:"string",description:'How primary buttons are filled: "solid" (default) or "outline" (transparent fill with a brand-color border).'},layout:{type:"object",description:"Numeric layout settings.",properties:{contentWidth:{type:"number"},containerPaddingX:{type:"number"},containerPaddingY:{type:"number"},blockSpacing:{type:"number"},baseRadius:{type:"number"},buttonRadius:{type:"number"},sectionPadding:{type:"number"},buttonPaddingX:{type:"number"},buttonPaddingY:{type:"number"},borderedBlockPadding:{type:"number"}},additionalProperties:!1}},additionalProperties:!1},emailDirection:{type:"string",description:"Default email text direction: ltr or rtl."},senderProfileId:{type:"string",description:"Make this existing sender profile the account-wide default, and the one fromName renames. Get IDs from list_sender_profiles. Mutually exclusive with fromEmail."},fromEmail:{type:"string",description:"Set the account-wide default From address. Its domain must already be configured and verified."},fromName:{type:"string",description:"Display name of the default From profile. Sent alone it renames the current default profile; with senderProfileId it renames that profile; with fromEmail it names the profile for that address. If the address already has several display names, pass senderProfileId to say which one to rename."},replyProfileId:{type:"string",description:"Make this existing reply profile the account-wide default, and the one replyToName renames. Get IDs from list_sender_profiles. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Set the account-wide default Reply-To address. Creates a reply profile when needed."},replyToName:{type:"string",description:"Display name of the default Reply-To profile. Sent alone it renames the current default profile; with replyProfileId it renames that profile; with replyTo it names the profile for that address."},replyTrackingEnabled:{type:"boolean",description:"Enable or disable inbound reply capture for this company."},replyTrackingDomainMode:{type:"string",description:"Reply-tracking domain mode: sequenzy for the managed domain or custom for a configured custom domain."},forwardReplies:{type:"boolean",description:"Enable or disable forwarding captured replies to the configured mailbox."}}}},{name:"get_shopify_automation_settings",description:"Get the connected Shopify store's automation settings: browse abandonment (emails shoppers who viewed a product but didn't buy), cart abandonment (fires ecommerce.cart_abandoned with the full cart after the cart sits inactive), and price drop alerts (emails recent viewers when a product's price falls). Returns the effective values with platform defaults applied.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_shopify_automation_settings",description:"Update the connected Shopify store's browse-abandonment, cart-abandonment, and/or price-drop automation settings. Partial update: omitted sections are untouched, omitted fields within a section keep their current value, and passing null for a section resets it to the platform defaults (browse abandonment: on, 2h delay, 24h cooldown; cart abandonment: on, 1h inactivity, 24h cooldown; price drop: on, 5% minimum drop, 30-day viewer lookback, 7-day cooldown).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},browseAbandonment:{type:["object","null"],description:"Browse abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours to wait after a product view before checking for abandonment (default 2)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between browse-abandoned events per subscriber (default 24)."}},additionalProperties:!1},cartAbandonment:{type:["object","null"],description:"Cart abandonment settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},delayHours:{type:"number",exclusiveMinimum:0,maximum:168,description:"Hours of cart inactivity before the cart counts as abandoned (default 1)."},cooldownHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Minimum hours between cart-abandoned events per subscriber (default 24)."}},additionalProperties:!1},priceDrop:{type:["object","null"],description:"Price drop settings, or null to reset to defaults.",properties:{enabled:{type:"boolean"},minPercent:{type:"number",exclusiveMinimum:0,maximum:95,description:"Minimum price decrease percent to alert on (default 5)."},lookbackDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"How many days back product viewers qualify as the audience (default 30)."},cooldownDays:{type:"number",exclusiveMinimum:0,maximum:90,description:"Minimum days between price-drop events per subscriber and product (default 7)."}},additionalProperties:!1}},additionalProperties:!1}},{name:"get_sync_rules",description:"Get the company's sync rules: the automatic tag changes applied when events fire (e.g. order placed -> add a tag). New companies start with no rules. Returns the effective rules plus isDefault, which is true when the company has explicitly opted into the inherited SaaS/ecommerce platform preset.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_sync_rules",description:"Replace the company's sync rules. Pass the FULL rule set (fetch with get_sync_rules first and edit it - this is not a partial update), [] to disable rules, or null to opt into the inherited SaaS/ecommerce platform preset. Each rule: { triggerEvent, actions: { addTags, removeTags }, conditions? }. Conditions support requiresTags, requiresNotTags, and purchasedProduct ({ tags?, collectionIds?, productTypes?, vendors? }) which matches products on commerce events - e.g. tag buyers of products carrying a given product tag.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncRules:{type:["array","null"],description:"Full replacement rule set. Use [] to disable sync rules, or null to opt into the inherited SaaS/ecommerce platform preset.",items:{type:"object",properties:{triggerEvent:{type:"string",description:"Event name that triggers the rule, e.g. ecommerce.order_placed or saas.purchase."},actions:{type:"object",properties:{addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}}},required:["addTags","removeTags"],additionalProperties:!1},conditions:{type:"object",properties:{requiresTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has ALL of these tags."},requiresNotTags:{type:"array",items:{type:"string"},description:"Rule only applies if the subscriber has NONE of these tags."},purchasedProduct:{type:"object",description:"For commerce events with product context: rule only applies when a product on the event matches every specified selector.",properties:{tags:{type:"array",items:{type:"string"}},collectionIds:{type:"array",items:{type:"string"}},productTypes:{type:"array",items:{type:"string"}},vendors:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},required:["triggerEvent","actions"],additionalProperties:!1}}},required:["syncRules"],additionalProperties:!1}},{name:"create_api_key",description:"Create a new API key for a company. Use this when setting up Sequenzy integration in a project. The returned key should be saved to the project's .env file as SEQUENZY_API_KEY. The key can only be retrieved once at creation time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the key for"},name:{type:"string",description:"Optional name for the API key (e.g., 'Production', 'Development')"},preset:{type:"string",description:"Optional permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Defaults to full_access when both preset and scopes are omitted; prefer agent_safe when creating a key for an AI agent."},scopes:{type:"array",description:"Optional explicit API key permission scopes. If provided, this overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId"]}},{name:"request_api_key_handoff",description:"Prepare an owner-confirmed handoff link for creating or rotating an API key. Use this when key management fails because the active key is missing api_keys:manage - that scope fails closed on purpose, and this is the supported way forward instead of asking the user to reason about the dashboard themselves. Returns a URL that opens the dashboard's create-key form with the requested name and permissions already filled in. IMPORTANT: this creates nothing and never returns a key. Give the URL to the workspace owner and stop; they review the form, click Create, and copy the new key from the browser. To rotate, pass replaceApiKeyId (or the literal string 'current' for the key you are authenticated with) and the dashboard offers to revoke the predecessor after the replacement is created. Requires only account:read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Suggested name for the new key (e.g., 'Production sync (rotated)')."},preset:{type:"string",description:"Suggested permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender. Prefer agent_safe for an AI agent key."},scopes:{type:"array",description:"Suggested explicit permission scopes. Overrides preset. Unsupported scopes are rejected here rather than silently dropped from the owner's form.",items:{type:"string"}},replaceApiKeyId:{type:"string",description:"ID of the key the new one replaces, so the owner can revoke it in the same visit. Pass 'current' for the key this session is authenticated with; its ID is also in get_account under apiKeyPermissions.activeKey.id."}}}},{name:"list_api_keys",description:"List company-scoped API keys as non-secret metadata. Returns IDs, names, prefixes, permissions, usage timestamps, and whether each key is the active credential. It never returns a plain key or stored key hash. Use this before revoke_api_key or delete_api_key to identify the exact unused key.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID whose API keys should be listed"}},required:["companyId"]}},{name:"update_api_key",description:"Rename a company-scoped API key or replace its permissions in place, without issuing a new key. Use this when a call fails with a missing-scope error: the key value stays the same, so no client has to be re-wired, and added permissions apply on the next retry. Removed permissions may remain usable for up to five minutes while API caches expire. preset and scopes REPLACE the current selection rather than merging into it - call list_api_keys first and pass the full set you want. Returns non-secret metadata only.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"},name:{type:"string",description:"New human-readable name for the key"},preset:{type:"string",description:"Replacement permission preset. Supported values: full_access, read_only, agent_safe, ai_drafting, data_ingest_safe, data_ingest_automations, transactional_sender, marketing_sender."},scopes:{type:"array",description:"Replacement explicit permission scopes. Overrides preset and must include at least one supported scope.",items:{type:"string"}}},required:["companyId","apiKeyId"]}},{name:"revoke_api_key",description:"Permanently revoke a company-scoped API key by ID. The response contains non-secret metadata only. Call list_api_keys first and compare the ID, name, prefix, and isCurrent flag because revoking a key cannot be undone and may invalidate the active credential.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"delete_api_key",description:"Compatibility alias for revoke_api_key. Permanently delete a company-scoped API key by ID and return non-secret metadata only. Call list_api_keys first to verify the exact target.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID that owns the API key"},apiKeyId:{type:"string",description:"Exact API key ID returned by list_api_keys"}},required:["companyId","apiKeyId"]}},{name:"list_websites",description:"List configured sending domains with separate DNS verification, sending readiness, and SPF, DKIM, and MAIL FROM status",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},label:{type:"string",description:"Optional label name filter. Only templates assigned this label are returned."}}}},{name:"add_sending_domain",description:"Add and configure a sending domain. Publish every cohort-specific DNS record returned, including DMARC when present, before calling verify_sending_domain.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Sending domain to add (for example, mail.example.com)."}},required:["domain"]}},{name:"add_website",description:"Compatibility alias for add_sending_domain. Adds a sending domain and returns the DNS records required for setup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to add (e.g., example.com)"}},required:["domain"]}},{name:"check_website",description:"Read a sending domain's separate DNS verification, sending readiness, and SPF, DKIM, MAIL FROM diagnostics. Use verify_sending_domain to run a fresh DNS check.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"The domain to check"}},required:["domain"]}},{name:"verify_sending_domain",description:"Run a fresh DNS check for a configured sending domain and return DNS verification separately from sending readiness. A DNS-verified domain may still be activating; when readyToSend is false, read readiness.reason rather than the DKIM/SPF/MAIL FROM record statuses, which describe DNS only.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Configured sending domain to verify."}},required:["domain"]}},{name:"list_integrations",description:"List connected integrations (Stripe, Shopify, Supabase, Clerk, WooCommerce, ad platforms, and so on) with connection status, sync state, last sync time, and last sync error. Read-only: credentials, access tokens, and webhook secrets are never returned. Use this to audit which external systems feed this account and whether their syncs are healthy.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},includeInactive:{type:"boolean",description:"Include disconnected/inactive integrations. Defaults to false (active only)."}}}},{name:"list_sender_profiles",description:"List sender (From) profiles and reply-to profiles for the company, including which are the account defaults and whether each sender address has verified DNS plus a ready home transport. Use this to audit sending identity before scheduling, or to pick a valid senderProfileId/replyProfileId for create_campaign or update_campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_sender_profile",description:"Rename one sender (From) or reply-to profile in place, without changing which profile is the account default. Use this to standardize a display name across the several identities a mailbox may carry, e.g. renaming 'Viraj from SnapCount' to 'SnapCount'. Get IDs from list_sender_profiles. Only the display name changes: the address, its sending domain, and the account-wide default From/Reply-To selection are untouched, and existing campaigns and sequences pinned to this profile pick up the new name. To change which profile is the default instead, use update_company with senderProfileId/replyProfileId. A company cannot have two sender identities with the same name on one address, so a colliding rename is rejected and reports the ID already using that name. Requires the companies:manage scope.",inputSchema:{type:"object",properties:{profileId:{type:"string",description:"ID of the profile to rename, from list_sender_profiles. Sender profile IDs come from senderProfiles, reply-to IDs from replyProfiles."},name:{type:"string",description:"New display name, e.g. 'SnapCount'. Trimmed; must be non-empty and 255 characters or fewer."},type:{type:"string",enum:["sender","reply"],description:"Which list profileId came from. Defaults to sender. Pass reply to rename a reply-to profile."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["profileId","name"]}},{name:"get_sending_status",description:`Check whether company-level email sending is active, paused, or suspended, and what it takes to restore it. Call this FIRST whenever a send, test send, or sequence step fails for a reason that is not a validation error, and whenever the account reports a bounce or complaint rate problem.
|
|
34
34
|
|
|
35
35
|
Returns the pause reason and reason kind, when it was paused, the automated sender-health review state, whether the one-click resume is currently available (and if not, which gate is blocking it), the enforcement counts and thresholds for permanent bounces, temporary bounces, and complaints, and ordered remediation steps.
|
|
36
36
|
|