@sequenzy/mcp 0.0.149 → 0.0.151
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 +21 -21
- package/dist/server.js +19 -19
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Kz=Object.create;var{getPrototypeOf:Zz,defineProperty:V$,getOwnPropertyNames:Pz}=Object;var Vz=Object.prototype.hasOwnProperty;function jz($){return this[$]}var Mz,qz,RQ=($,W,Q)=>{var X=$!=null&&typeof $==="object";if(X){var G=W?Mz??=new WeakMap:qz??=new WeakMap,J=G.get($);if(J)return J}Q=$!=null?Kz(Zz($)):{};let w=W||!$||!$.__esModule?V$(Q,"default",{value:$,enumerable:!0}):Q;for(let Y of Pz($))if(!Vz.call(w,Y))V$(w,Y,{get:jz.bind($,Y),enumerable:!0});if(X)G.set($,w);return w};var N=($,W)=>()=>(W||$((W={exports:{}}).exports,W),W.exports);var Iz=($)=>$;function Nz($,W){this[$]=Iz.bind(null,W)}var SQ=($,W)=>{for(var Q in W)V$($,Q,{get:W[Q],enumerable:!0,configurable:!0,set:Nz.bind(W,Q)})};var X4=N((Cw)=>{Object.defineProperty(Cw,"__esModule",{value:!0});Cw.regexpCode=Cw.getEsmExportName=Cw.getProperty=Cw.safeStringify=Cw.stringify=Cw.strConcat=Cw.addCodeArg=Cw.str=Cw._=Cw.nil=Cw._Code=Cw.Name=Cw.IDENTIFIER=Cw._CodeOrName=void 0;class A9{}Cw._CodeOrName=A9;Cw.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Y6 extends A9{constructor($){super();if(!Cw.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}Cw.Name=Y6;class d0 extends A9{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((W,Q)=>`${W}${Q}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((W,Q)=>{if(Q instanceof Y6)W[Q.str]=(W[Q.str]||0)+1;return W},{})}}Cw._Code=d0;Cw.nil=new d0("");function Rw($,...W){let Q=[$[0]],X=0;while(X<W.length)S8(Q,W[X]),Q.push($[++X]);return new d0(Q)}Cw._=Rw;var R8=new d0("+");function Sw($,...W){let Q=[Q4($[0])],X=0;while(X<W.length)Q.push(R8),S8(Q,W[X]),Q.push(R8,Q4($[++X]));return tU(Q),new d0(Q)}Cw.str=Sw;function S8($,W){if(W instanceof d0)$.push(...W._items);else if(W instanceof Y6)$.push(W);else $.push(aU(W))}Cw.addCodeArg=S8;function tU($){let W=1;while(W<$.length-1){if($[W]===R8){let Q=rU($[W-1],$[W+1]);if(Q!==void 0){$.splice(W-1,3,Q);continue}$[W++]="+"}W++}}function rU($,W){if(W==='""')return $;if($==='""')return W;if(typeof $=="string"){if(W instanceof Y6||$[$.length-1]!=='"')return;if(typeof W!="string")return`${$.slice(0,-1)}${W}"`;if(W[0]==='"')return $.slice(0,-1)+W.slice(1);return}if(typeof W=="string"&&W[0]==='"'&&!($ instanceof Y6))return`"${$}${W.slice(1)}`;return}function sU($,W){return W.emptyStr()?$:$.emptyStr()?W:Sw`${$}${W}`}Cw.strConcat=sU;function aU($){return typeof $=="number"||typeof $=="boolean"||$===null?$:Q4(Array.isArray($)?$.join(","):$)}function eU($){return new d0(Q4($))}Cw.stringify=eU;function Q4($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Cw.safeStringify=Q4;function $B($){return typeof $=="string"&&Cw.IDENTIFIER.test($)?new d0(`.${$}`):Rw`[${$}]`}Cw.getProperty=$B;function WB($){if(typeof $=="string"&&Cw.IDENTIFIER.test($))return new d0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}Cw.getEsmExportName=WB;function QB($){return new d0($.toString())}Cw.regexpCode=QB});var _8=N((xw)=>{Object.defineProperty(xw,"__esModule",{value:!0});xw.ValueScope=xw.ValueScopeName=xw.Scope=xw.varKinds=xw.UsedValueState=void 0;var N0=X4();class vw extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var K9;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(K9||(xw.UsedValueState=K9={}));xw.varKinds={const:new N0.Name("const"),let:new N0.Name("let"),var:new N0.Name("var")};class k8{constructor({prefixes:$,parent:W}={}){this._names={},this._prefixes=$,this._parent=W}toName($){return $ instanceof N0.Name?$:this.name($)}name($){return new N0.Name(this._newName($))}_newName($){let W=this._names[$]||this._nameGroup($);return`${$}${W.index++}`}_nameGroup($){var W,Q;if(((Q=(W=this._parent)===null||W===void 0?void 0:W._prefixes)===null||Q===void 0?void 0:Q.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}xw.Scope=k8;class v8 extends N0.Name{constructor($,W){super(W);this.prefix=$}setValue($,{property:W,itemIndex:Q}){this.value=$,this.scopePath=N0._`.${new N0.Name(W)}[${Q}]`}}xw.ValueScopeName=v8;var LB=N0._`\n`;class _w extends k8{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?LB:N0.nil}}get(){return this._scope}name($){return new v8($,this._newName($))}value($,W){var Q;if(W.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName($),{prefix:G}=X,J=(Q=W.key)!==null&&Q!==void 0?Q:W.ref,w=this._values[G];if(w){let H=w.get(J);if(H)return H}else w=this._values[G]=new Map;w.set(J,X);let Y=this._scope[G]||(this._scope[G]=[]),b=Y.length;return Y[b]=W.ref,X.setValue(W,{property:G,itemIndex:b}),X}getValue($,W){let Q=this._values[$];if(!Q)return;return Q.get(W)}scopeRefs($,W=this._values){return this._reduceValues(W,(Q)=>{if(Q.scopePath===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return N0._`${$}${Q.scopePath}`})}scopeCode($=this._values,W,Q){return this._reduceValues($,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},W,Q)}_reduceValues($,W,Q={},X){let G=N0.nil;for(let J in $){let w=$[J];if(!w)continue;let Y=Q[J]=Q[J]||new Map;w.forEach((b)=>{if(Y.has(b))return;Y.set(b,K9.Started);let H=W(b);if(H){let z=this.opts.es5?xw.varKinds.var:xw.varKinds.const;G=N0._`${G}${z} ${b} = ${H};${this.opts._n}`}else if(H=X===null||X===void 0?void 0:X(b))G=N0._`${G}${H}${this.opts._n}`;else throw new vw(b);Y.set(b,K9.Completed)})}return G}}xw.ValueScope=_w});var g=N((E0)=>{Object.defineProperty(E0,"__esModule",{value:!0});E0.or=E0.and=E0.not=E0.CodeGen=E0.operators=E0.varKinds=E0.ValueScopeName=E0.ValueScope=E0.Scope=E0.Name=E0.regexpCode=E0.stringify=E0.getProperty=E0.nil=E0.strConcat=E0.str=E0._=void 0;var n=X4(),o0=_8(),S1=X4();Object.defineProperty(E0,"_",{enumerable:!0,get:function(){return S1._}});Object.defineProperty(E0,"str",{enumerable:!0,get:function(){return S1.str}});Object.defineProperty(E0,"strConcat",{enumerable:!0,get:function(){return S1.strConcat}});Object.defineProperty(E0,"nil",{enumerable:!0,get:function(){return S1.nil}});Object.defineProperty(E0,"getProperty",{enumerable:!0,get:function(){return S1.getProperty}});Object.defineProperty(E0,"stringify",{enumerable:!0,get:function(){return S1.stringify}});Object.defineProperty(E0,"regexpCode",{enumerable:!0,get:function(){return S1.regexpCode}});Object.defineProperty(E0,"Name",{enumerable:!0,get:function(){return S1.Name}});var q9=_8();Object.defineProperty(E0,"Scope",{enumerable:!0,get:function(){return q9.Scope}});Object.defineProperty(E0,"ValueScope",{enumerable:!0,get:function(){return q9.ValueScope}});Object.defineProperty(E0,"ValueScopeName",{enumerable:!0,get:function(){return q9.ValueScopeName}});Object.defineProperty(E0,"varKinds",{enumerable:!0,get:function(){return q9.varKinds}});E0.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class C1{optimizeNodes(){return this}optimizeNames($,W){return this}}class yw extends C1{constructor($,W,Q){super();this.varKind=$,this.name=W,this.rhs=Q}render({es5:$,_n:W}){let Q=$?o0.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${Q} ${this.name}${X};`+W}optimizeNames($,W){if(!$[this.name.str])return;if(this.rhs)this.rhs=H6(this.rhs,$,W);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class y8 extends C1{constructor($,W,Q){super();this.lhs=$,this.rhs=W,this.sideEffects=Q}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,W){if(this.lhs instanceof n.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=H6(this.rhs,$,W),this}get names(){let $=this.lhs instanceof n.Name?{}:{...this.lhs.names};return M9($,this.rhs)}}class fw extends y8{constructor($,W,Q,X){super($,Q,X);this.op=W}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class uw extends C1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class cw extends C1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class mw extends C1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class lw extends C1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,W){return this.code=H6(this.code,$,W),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class I9 extends C1{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((W,Q)=>W+Q.render($),"")}optimizeNodes(){let{nodes:$}=this,W=$.length;while(W--){let Q=$[W].optimizeNodes();if(Array.isArray(Q))$.splice(W,1,...Q);else if(Q)$[W]=Q;else $.splice(W,1)}return $.length>0?this:void 0}optimizeNames($,W){let{nodes:Q}=this,X=Q.length;while(X--){let G=Q[X];if(G.optimizeNames($,W))continue;ZB($,G.names),Q.splice(X,1)}return Q.length>0?this:void 0}get names(){return this.nodes.reduce(($,W)=>m1($,W.names),{})}}class k1 extends I9{render($){return"{"+$._n+super.render($)+"}"+$._n}}class gw extends I9{}class G4 extends k1{}G4.kind="else";class D1 extends k1{constructor($,W){super(W);this.condition=$}render($){let W=`if(${this.condition})`+super.render($);if(this.else)W+="else "+this.else.render($);return W}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let W=this.else;if(W){let Q=W.optimizeNodes();W=this.else=Array.isArray(Q)?new G4(Q):Q}if(W){if($===!1)return W instanceof D1?W:W.nodes;if(this.nodes.length)return this;return new D1(ow($),W instanceof D1?[W]:W.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,W){var Q;if(this.else=(Q=this.else)===null||Q===void 0?void 0:Q.optimizeNames($,W),!(super.optimizeNames($,W)||this.else))return;return this.condition=H6(this.condition,$,W),this}get names(){let $=super.names;if(M9($,this.condition),this.else)m1($,this.else.names);return $}}D1.kind="if";class b6 extends k1{}b6.kind="for";class pw extends b6{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,W){if(!super.optimizeNames($,W))return;return this.iteration=H6(this.iteration,$,W),this}get names(){return m1(super.names,this.iteration.names)}}class iw extends b6{constructor($,W,Q,X){super();this.varKind=$,this.name=W,this.from=Q,this.to=X}render($){let W=$.es5?o0.varKinds.var:this.varKind,{name:Q,from:X,to:G}=this;return`for(${W} ${Q}=${X}; ${Q}<${G}; ${Q}++)`+super.render($)}get names(){let $=M9(super.names,this.from);return M9($,this.to)}}class x8 extends b6{constructor($,W,Q,X){super();this.loop=$,this.varKind=W,this.name=Q,this.iterable=X}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,W){if(!super.optimizeNames($,W))return;return this.iterable=H6(this.iterable,$,W),this}get names(){return m1(super.names,this.iterable.names)}}class Z9 extends k1{constructor($,W,Q){super();this.name=$,this.args=W,this.async=Q}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}Z9.kind="func";class P9 extends I9{render($){return"return "+super.render($)}}P9.kind="return";class nw extends k1{render($){let W="try"+super.render($);if(this.catch)W+=this.catch.render($);if(this.finally)W+=this.finally.render($);return W}optimizeNodes(){var $,W;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(W=this.finally)===null||W===void 0||W.optimizeNodes(),this}optimizeNames($,W){var Q,X;return super.optimizeNames($,W),(Q=this.catch)===null||Q===void 0||Q.optimizeNames($,W),(X=this.finally)===null||X===void 0||X.optimizeNames($,W),this}get names(){let $=super.names;if(this.catch)m1($,this.catch.names);if(this.finally)m1($,this.finally.names);return $}}class V9 extends k1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}V9.kind="catch";class j9 extends k1{render($){return"finally"+super.render($)}}j9.kind="finally";class dw{constructor($,W={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...W,_n:W.lines?`
|
|
3
|
-
`:""},this._extScope=$,this._scope=new o0.Scope({parent:$}),this._nodes=[new gw]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,W){let Q=this._extScope.value($,W);return(this._values[Q.prefix]||(this._values[Q.prefix]=new Set)).add(Q),Q}getScopeValue($,W){return this._extScope.getValue($,W)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,W,Q,X){let G=this._scope.toName(W);if(Q!==void 0&&X)this._constants[G.str]=Q;return this._leafNode(new yw($,G,Q)),G}const($,W,Q){return this._def(o0.varKinds.const,$,W,Q)}let($,W,Q){return this._def(o0.varKinds.let,$,W,Q)}var($,W,Q){return this._def(o0.varKinds.var,$,W,Q)}assign($,W,Q){return this._leafNode(new y8($,W,Q))}add($,W){return this._leafNode(new fw($,E0.operators.ADD,W))}code($){if(typeof $=="function")$();else if($!==n.nil)this._leafNode(new lw($));return this}object(...$){let W=["{"];for(let[Q,X]of $){if(W.length>1)W.push(",");if(W.push(Q),Q!==X||this.opts.es5)W.push(":"),(0,n.addCodeArg)(W,X)}return W.push("}"),new n._Code(W)}if($,W,Q){if(this._blockNode(new D1($)),W&&Q)this.code(W).else().code(Q).endIf();else if(W)this.code(W).endIf();else if(Q)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new D1($))}else(){return this._elseNode(new G4)}endIf(){return this._endBlockNode(D1,G4)}_for($,W){if(this._blockNode($),W)this.code(W).endFor();return this}for($,W){return this._for(new pw($),W)}forRange($,W,Q,X,G=this.opts.es5?o0.varKinds.var:o0.varKinds.let){let J=this._scope.toName($);return this._for(new iw(G,J,W,Q),()=>X(J))}forOf($,W,Q,X=o0.varKinds.const){let G=this._scope.toName($);if(this.opts.es5){let J=W instanceof n.Name?W:this.var("_arr",W);return this.forRange("_i",0,n._`${J}.length`,(w)=>{this.var(G,n._`${J}[${w}]`),Q(G)})}return this._for(new x8("of",X,G,W),()=>Q(G))}forIn($,W,Q,X=this.opts.es5?o0.varKinds.var:o0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,n._`Object.keys(${W})`,Q);let G=this._scope.toName($);return this._for(new x8("in",X,G,W),()=>Q(G))}endFor(){return this._endBlockNode(b6)}label($){return this._leafNode(new uw($))}break($){return this._leafNode(new cw($))}return($){let W=new P9;if(this._blockNode(W),this.code($),W.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(P9)}try($,W,Q){if(!W&&!Q)throw Error('CodeGen: "try" without "catch" and "finally"');let X=new nw;if(this._blockNode(X),this.code($),W){let G=this.name("e");this._currNode=X.catch=new V9(G),W(G)}if(Q)this._currNode=X.finally=new j9,this.code(Q);return this._endBlockNode(V9,j9)}throw($){return this._leafNode(new mw($))}block($,W){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(W);return this}endBlock($){let W=this._blockStarts.pop();if(W===void 0)throw Error("CodeGen: not in self-balancing block");let Q=this._nodes.length-W;if(Q<0||$!==void 0&&Q!==$)throw Error(`CodeGen: wrong number of nodes: ${Q} vs ${$} expected`);return this._nodes.length=W,this}func($,W=n.nil,Q,X){if(this._blockNode(new Z9($,W,Q)),X)this.code(X).endFunc();return this}endFunc(){return this._endBlockNode(Z9)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,W){let Q=this._currNode;if(Q instanceof $||W&&Q instanceof W)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${W?`${$.kind}/${W.kind}`:$.kind}"`)}_elseNode($){let W=this._currNode;if(!(W instanceof D1))throw Error('CodeGen: "else" without "if"');return this._currNode=W.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let W=this._nodes;W[W.length-1]=$}}E0.CodeGen=dw;function m1($,W){for(let Q in W)$[Q]=($[Q]||0)+(W[Q]||0);return $}function M9($,W){return W instanceof n._CodeOrName?m1($,W.names):$}function H6($,W,Q){if($ instanceof n.Name)return X($);if(!G($))return $;return new n._Code($._items.reduce((J,w)=>{if(w instanceof n.Name)w=X(w);if(w instanceof n._Code)J.push(...w._items);else J.push(w);return J},[]));function X(J){let w=Q[J.str];if(w===void 0||W[J.str]!==1)return J;return delete W[J.str],w}function G(J){return J instanceof n._Code&&J._items.some((w)=>w instanceof n.Name&&W[w.str]===1&&Q[w.str]!==void 0)}}function ZB($,W){for(let Q in W)$[Q]=($[Q]||0)-(W[Q]||0)}function ow($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:n._`!${h8($)}`}E0.not=ow;var PB=tw(E0.operators.AND);function VB(...$){return $.reduce(PB)}E0.and=VB;var jB=tw(E0.operators.OR);function MB(...$){return $.reduce(jB)}E0.or=MB;function tw($){return(W,Q)=>W===n.nil?Q:Q===n.nil?W:n._`${h8(W)} ${$} ${h8(Q)}`}function h8($){return $ instanceof n.Name?$:n._`(${$})`}});var t=N((GY)=>{Object.defineProperty(GY,"__esModule",{value:!0});GY.checkStrictMode=GY.getErrorPath=GY.Type=GY.useFunc=GY.setEvaluated=GY.evaluatedPropsToName=GY.mergeEvaluated=GY.eachItem=GY.unescapeJsonPointer=GY.escapeJsonPointer=GY.escapeFragment=GY.unescapeFragment=GY.schemaRefOrVal=GY.schemaHasRulesButRef=GY.schemaHasRules=GY.checkUnknownRules=GY.alwaysValidSchema=GY.toHash=void 0;var a=g(),EB=X4();function TB($){let W={};for(let Q of $)W[Q]=!0;return W}GY.toHash=TB;function RB($,W){if(typeof W=="boolean")return W;if(Object.keys(W).length===0)return!0;return ew($,W),!$Y(W,$.self.RULES.all)}GY.alwaysValidSchema=RB;function ew($,W=$.schema){let{opts:Q,self:X}=$;if(!Q.strictSchema)return;if(typeof W==="boolean")return;let G=X.RULES.keywords;for(let J in W)if(!G[J])XY($,`unknown keyword: "${J}"`)}GY.checkUnknownRules=ew;function $Y($,W){if(typeof $=="boolean")return!$;for(let Q in $)if(W[Q])return!0;return!1}GY.schemaHasRules=$Y;function SB($,W){if(typeof $=="boolean")return!$;for(let Q in $)if(Q!=="$ref"&&W.all[Q])return!0;return!1}GY.schemaHasRulesButRef=SB;function CB({topSchemaRef:$,schemaPath:W},Q,X,G){if(!G){if(typeof Q=="number"||typeof Q=="boolean")return Q;if(typeof Q=="string")return a._`${Q}`}return a._`${$}${W}${(0,a.getProperty)(X)}`}GY.schemaRefOrVal=CB;function kB($){return WY(decodeURIComponent($))}GY.unescapeFragment=kB;function vB($){return encodeURIComponent(u8($))}GY.escapeFragment=vB;function u8($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}GY.escapeJsonPointer=u8;function WY($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}GY.unescapeJsonPointer=WY;function _B($,W){if(Array.isArray($))for(let Q of $)W(Q);else W($)}GY.eachItem=_B;function sw({mergeNames:$,mergeToName:W,mergeValues:Q,resultToName:X}){return(G,J,w,Y)=>{let b=w===void 0?J:w instanceof a.Name?(J instanceof a.Name?$(G,J,w):W(G,J,w),w):J instanceof a.Name?(W(G,w,J),J):Q(J,w);return Y===a.Name&&!(b instanceof a.Name)?X(G,b):b}}GY.mergeEvaluated={props:sw({mergeNames:($,W,Q)=>$.if(a._`${Q} !== true && ${W} !== undefined`,()=>{$.if(a._`${W} === true`,()=>$.assign(Q,!0),()=>$.assign(Q,a._`${Q} || {}`).code(a._`Object.assign(${Q}, ${W})`))}),mergeToName:($,W,Q)=>$.if(a._`${Q} !== true`,()=>{if(W===!0)$.assign(Q,!0);else $.assign(Q,a._`${Q} || {}`),c8($,Q,W)}),mergeValues:($,W)=>$===!0?!0:{...$,...W},resultToName:QY}),items:sw({mergeNames:($,W,Q)=>$.if(a._`${Q} !== true && ${W} !== undefined`,()=>$.assign(Q,a._`${W} === true ? true : ${Q} > ${W} ? ${Q} : ${W}`)),mergeToName:($,W,Q)=>$.if(a._`${Q} !== true`,()=>$.assign(Q,W===!0?!0:a._`${Q} > ${W} ? ${Q} : ${W}`)),mergeValues:($,W)=>$===!0?!0:Math.max($,W),resultToName:($,W)=>$.var("items",W)})};function QY($,W){if(W===!0)return $.var("props",!0);let Q=$.var("props",a._`{}`);if(W!==void 0)c8($,Q,W);return Q}GY.evaluatedPropsToName=QY;function c8($,W,Q){Object.keys(Q).forEach((X)=>$.assign(a._`${W}${(0,a.getProperty)(X)}`,!0))}GY.setEvaluated=c8;var aw={};function xB($,W){return $.scopeValue("func",{ref:W,code:aw[W.code]||(aw[W.code]=new EB._Code(W.code))})}GY.useFunc=xB;var f8;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(f8||(GY.Type=f8={}));function hB($,W,Q){if($ instanceof a.Name){let X=W===f8.Num;return Q?X?a._`"[" + ${$} + "]"`:a._`"['" + ${$} + "']"`:X?a._`"/" + ${$}`:a._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Q?(0,a.getProperty)($).toString():"/"+u8($)}GY.getErrorPath=hB;function XY($,W,Q=$.opts.strictSchema){if(!Q)return;if(W=`strict mode: ${W}`,Q===!0)throw Error(W);$.self.logger.warn(W)}GY.checkStrictMode=XY});var F1=N((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});var V0=g(),$L={data:new V0.Name("data"),valCxt:new V0.Name("valCxt"),instancePath:new V0.Name("instancePath"),parentData:new V0.Name("parentData"),parentDataProperty:new V0.Name("parentDataProperty"),rootData:new V0.Name("rootData"),dynamicAnchors:new V0.Name("dynamicAnchors"),vErrors:new V0.Name("vErrors"),errors:new V0.Name("errors"),this:new V0.Name("this"),self:new V0.Name("self"),scope:new V0.Name("scope"),json:new V0.Name("json"),jsonPos:new V0.Name("jsonPos"),jsonLen:new V0.Name("jsonLen"),jsonPart:new V0.Name("jsonPart")};wY.default=$L});var J4=N((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.extendErrors=zY.resetErrorsCount=zY.reportExtraError=zY.reportError=zY.keyword$DataError=zY.keywordError=void 0;var d=g(),E9=t(),M0=F1();zY.keywordError={message:({keyword:$})=>d.str`must pass "${$}" keyword validation`};zY.keyword$DataError={message:({keyword:$,schemaType:W})=>W?d.str`"${$}" keyword must be ${W} ($data)`:d.str`"${$}" keyword is invalid ($data)`};function QL($,W=zY.keywordError,Q,X){let{it:G}=$,{gen:J,compositeRule:w,allErrors:Y}=G,b=HY($,W,Q);if(X!==null&&X!==void 0?X:w||Y)YY(J,b);else bY(G,d._`[${b}]`)}zY.reportError=QL;function XL($,W=zY.keywordError,Q){let{it:X}=$,{gen:G,compositeRule:J,allErrors:w}=X,Y=HY($,W,Q);if(YY(G,Y),!(J||w))bY(X,M0.default.vErrors)}zY.reportExtraError=XL;function GL($,W){$.assign(M0.default.errors,W),$.if(d._`${M0.default.vErrors} !== null`,()=>$.if(W,()=>$.assign(d._`${M0.default.vErrors}.length`,W),()=>$.assign(M0.default.vErrors,null)))}zY.resetErrorsCount=GL;function JL({gen:$,keyword:W,schemaValue:Q,data:X,errsCount:G,it:J}){if(G===void 0)throw Error("ajv implementation error");let w=$.name("err");$.forRange("i",G,M0.default.errors,(Y)=>{if($.const(w,d._`${M0.default.vErrors}[${Y}]`),$.if(d._`${w}.instancePath === undefined`,()=>$.assign(d._`${w}.instancePath`,(0,d.strConcat)(M0.default.instancePath,J.errorPath))),$.assign(d._`${w}.schemaPath`,d.str`${J.errSchemaPath}/${W}`),J.opts.verbose)$.assign(d._`${w}.schema`,Q),$.assign(d._`${w}.data`,X)})}zY.extendErrors=JL;function YY($,W){let Q=$.const("err",W);$.if(d._`${M0.default.vErrors} === null`,()=>$.assign(M0.default.vErrors,d._`[${Q}]`),d._`${M0.default.vErrors}.push(${Q})`),$.code(d._`${M0.default.errors}++`)}function bY($,W){let{gen:Q,validateName:X,schemaEnv:G}=$;if(G.$async)Q.throw(d._`new ${$.ValidationError}(${W})`);else Q.assign(d._`${X}.errors`,W),Q.return(!1)}var l1={keyword:new d.Name("keyword"),schemaPath:new d.Name("schemaPath"),params:new d.Name("params"),propertyName:new d.Name("propertyName"),message:new d.Name("message"),schema:new d.Name("schema"),parentSchema:new d.Name("parentSchema")};function HY($,W,Q){let{createErrors:X}=$.it;if(X===!1)return d._`{}`;return wL($,W,Q)}function wL($,W,Q={}){let{gen:X,it:G}=$,J=[YL(G,Q),bL($,Q)];return HL($,W,J),X.object(...J)}function YL({errorPath:$},{instancePath:W}){let Q=W?d.str`${$}${(0,E9.getErrorPath)(W,E9.Type.Str)}`:$;return[M0.default.instancePath,(0,d.strConcat)(M0.default.instancePath,Q)]}function bL({keyword:$,it:{errSchemaPath:W}},{schemaPath:Q,parentSchema:X}){let G=X?W:d.str`${W}/${$}`;if(Q)G=d.str`${G}${(0,E9.getErrorPath)(Q,E9.Type.Str)}`;return[l1.schemaPath,G]}function HL($,{params:W,message:Q},X){let{keyword:G,data:J,schemaValue:w,it:Y}=$,{opts:b,propertyName:H,topSchemaRef:z,schemaPath:F}=Y;if(X.push([l1.keyword,G],[l1.params,typeof W=="function"?W($):W||d._`{}`]),b.messages)X.push([l1.message,typeof Q=="function"?Q($):Q]);if(b.verbose)X.push([l1.schema,w],[l1.parentSchema,d._`${z}${F}`],[M0.default.data,J]);if(H)X.push([l1.propertyName,H])}});var LY=N((UY)=>{Object.defineProperty(UY,"__esModule",{value:!0});UY.boolOrEmptySchema=UY.topBoolOrEmptySchema=void 0;var BL=J4(),LL=g(),AL=F1(),OL={message:"boolean schema is false"};function KL($){let{gen:W,schema:Q,validateName:X}=$;if(Q===!1)FY($,!1);else if(typeof Q=="object"&&Q.$async===!0)W.return(AL.default.data);else W.assign(LL._`${X}.errors`,null),W.return(!0)}UY.topBoolOrEmptySchema=KL;function ZL($,W){let{gen:Q,schema:X}=$;if(X===!1)Q.var(W,!1),FY($);else Q.var(W,!0)}UY.boolOrEmptySchema=ZL;function FY($,W){let{gen:Q,data:X}=$,G={gen:Q,keyword:"false schema",data:X,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,BL.reportError)(G,OL,void 0,W)}});var l8=N((AY)=>{Object.defineProperty(AY,"__esModule",{value:!0});AY.getRules=AY.isJSONType=void 0;var VL=["string","number","integer","boolean","null","object","array"],jL=new Set(VL);function ML($){return typeof $=="string"&&jL.has($)}AY.isJSONType=ML;function qL(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}AY.getRules=qL});var g8=N((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.shouldUseRule=PY.shouldUseGroup=PY.schemaHasRulesForType=void 0;function NL({schema:$,self:W},Q){let X=W.RULES.types[Q];return X&&X!==!0&&KY($,X)}PY.schemaHasRulesForType=NL;function KY($,W){return W.rules.some((Q)=>ZY($,Q))}PY.shouldUseGroup=KY;function ZY($,W){var Q;return $[W.keyword]!==void 0||((Q=W.definition.implements)===null||Q===void 0?void 0:Q.some((X)=>$[X]!==void 0))}PY.shouldUseRule=ZY});var w4=N((IY)=>{Object.defineProperty(IY,"__esModule",{value:!0});IY.reportTypeError=IY.checkDataTypes=IY.checkDataType=IY.coerceAndCheckDataType=IY.getJSONTypes=IY.getSchemaTypes=IY.DataType=void 0;var RL=l8(),SL=g8(),CL=J4(),m=g(),jY=t(),z6;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(z6||(IY.DataType=z6={}));function kL($){let W=MY($.type);if(W.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!W.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)W.push("null")}return W}IY.getSchemaTypes=kL;function MY($){let W=Array.isArray($)?$:$?[$]:[];if(W.every(RL.isJSONType))return W;throw Error("type must be JSONType or JSONType[]: "+W.join(","))}IY.getJSONTypes=MY;function vL($,W){let{gen:Q,data:X,opts:G}=$,J=_L(W,G.coerceTypes),w=W.length>0&&!(J.length===0&&W.length===1&&(0,SL.schemaHasRulesForType)($,W[0]));if(w){let Y=i8(W,X,G.strictNumbers,z6.Wrong);Q.if(Y,()=>{if(J.length)xL($,W,J);else n8($)})}return w}IY.coerceAndCheckDataType=vL;var qY=new Set(["string","number","integer","boolean","null"]);function _L($,W){return W?$.filter((Q)=>qY.has(Q)||W==="array"&&Q==="array"):[]}function xL($,W,Q){let{gen:X,data:G,opts:J}=$,w=X.let("dataType",m._`typeof ${G}`),Y=X.let("coerced",m._`undefined`);if(J.coerceTypes==="array")X.if(m._`${w} == 'object' && Array.isArray(${G}) && ${G}.length == 1`,()=>X.assign(G,m._`${G}[0]`).assign(w,m._`typeof ${G}`).if(i8(W,G,J.strictNumbers),()=>X.assign(Y,G)));X.if(m._`${Y} !== undefined`);for(let H of Q)if(qY.has(H)||H==="array"&&J.coerceTypes==="array")b(H);X.else(),n8($),X.endIf(),X.if(m._`${Y} !== undefined`,()=>{X.assign(G,Y),hL($,Y)});function b(H){switch(H){case"string":X.elseIf(m._`${w} == "number" || ${w} == "boolean"`).assign(Y,m._`"" + ${G}`).elseIf(m._`${G} === null`).assign(Y,m._`""`);return;case"number":X.elseIf(m._`${w} == "boolean" || ${G} === null
|
|
4
|
-
|| (${w} == "string" && ${
|
|
5
|
-
|| (${w} === "string" && ${
|
|
6
|
-
|| ${w} === "boolean" || ${G} === null`).assign(Y,m._`[${G}]`)}}}function hL({gen:$,parentData:W,parentDataProperty:Q},X){$.if(m._`${W} !== undefined`,()=>$.assign(m._`${W}[${Q}]`,X))}function p8($,W,Q,X=z6.Correct){let G=X===z6.Correct?m.operators.EQ:m.operators.NEQ,J;switch($){case"null":return m._`${W} ${G} null`;case"array":J=m._`Array.isArray(${W})`;break;case"object":J=m._`${W} && typeof ${W} == "object" && !Array.isArray(${W})`;break;case"integer":J=w(m._`!(${W} % 1) && !isNaN(${W})`);break;case"number":J=w();break;default:return m._`typeof ${W} ${G} ${$}`}return X===z6.Correct?J:(0,m.not)(J);function w(Y=m.nil){return(0,m.and)(m._`typeof ${W} == "number"`,Y,Q?m._`isFinite(${W})`:m.nil)}}IY.checkDataType=p8;function i8($,W,Q,X){if($.length===1)return p8($[0],W,Q,X);let G,J=(0,jY.toHash)($);if(J.array&&J.object){let w=m._`typeof ${W} != "object"`;G=J.null?w:m._`!${W} || ${w}`,delete J.null,delete J.array,delete J.object}else G=m.nil;if(J.number)delete J.integer;for(let w in J)G=(0,m.and)(G,p8(w,W,Q,X));return G}IY.checkDataTypes=i8;var yL={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:W})=>typeof $=="string"?m._`{type: ${$}}`:m._`{type: ${W}}`};function n8($){let W=fL($);(0,CL.reportError)(W,yL)}IY.reportTypeError=n8;function fL($){let{gen:W,data:Q,schema:X}=$,G=(0,jY.schemaRefOrVal)($,X,"type");return{gen:W,keyword:"type",data:Q,schema:X.type,schemaCode:G,schemaValue:G,parentSchema:X,params:{},it:$}}});var SY=N((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});TY.assignDefaults=void 0;var D6=g(),iL=t();function nL($,W){let{properties:Q,items:X}=$.schema;if(W==="object"&&Q)for(let G in Q)EY($,G,Q[G].default);else if(W==="array"&&Array.isArray(X))X.forEach((G,J)=>EY($,J,G.default))}TY.assignDefaults=nL;function EY($,W,Q){let{gen:X,compositeRule:G,data:J,opts:w}=$;if(Q===void 0)return;let Y=D6._`${J}${(0,D6.getProperty)(W)}`;if(G){(0,iL.checkStrictMode)($,`default is ignored for: ${Y}`);return}let b=D6._`${Y} === undefined`;if(w.useDefaults==="empty")b=D6._`${b} || ${Y} === null || ${Y} === ""`;X.if(b,D6._`${Y} = ${(0,D6.stringify)(Q)}`)}});var m0=N((vY)=>{Object.defineProperty(vY,"__esModule",{value:!0});vY.validateUnion=vY.validateArray=vY.usePattern=vY.callValidateCode=vY.schemaProperties=vY.allSchemaProperties=vY.noPropertyInData=vY.propertyInData=vY.isOwnProperty=vY.hasPropFunc=vY.reportMissingProp=vY.checkMissingProp=vY.checkReportMissingProp=void 0;var Q0=g(),d8=t(),v1=F1(),dL=t();function oL($,W){let{gen:Q,data:X,it:G}=$;Q.if(t8(Q,X,W,G.opts.ownProperties),()=>{$.setParams({missingProperty:Q0._`${W}`},!0),$.error()})}vY.checkReportMissingProp=oL;function tL({gen:$,data:W,it:{opts:Q}},X,G){return(0,Q0.or)(...X.map((J)=>(0,Q0.and)(t8($,W,J,Q.ownProperties),Q0._`${G} = ${J}`)))}vY.checkMissingProp=tL;function rL($,W){$.setParams({missingProperty:W},!0),$.error()}vY.reportMissingProp=rL;function CY($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Q0._`Object.prototype.hasOwnProperty`})}vY.hasPropFunc=CY;function o8($,W,Q){return Q0._`${CY($)}.call(${W}, ${Q})`}vY.isOwnProperty=o8;function sL($,W,Q,X){let G=Q0._`${W}${(0,Q0.getProperty)(Q)} !== undefined`;return X?Q0._`${G} && ${o8($,W,Q)}`:G}vY.propertyInData=sL;function t8($,W,Q,X){let G=Q0._`${W}${(0,Q0.getProperty)(Q)} === undefined`;return X?(0,Q0.or)(G,(0,Q0.not)(o8($,W,Q))):G}vY.noPropertyInData=t8;function kY($){return $?Object.keys($).filter((W)=>W!=="__proto__"):[]}vY.allSchemaProperties=kY;function aL($,W){return kY(W).filter((Q)=>!(0,d8.alwaysValidSchema)($,W[Q]))}vY.schemaProperties=aL;function eL({schemaCode:$,data:W,it:{gen:Q,topSchemaRef:X,schemaPath:G,errorPath:J},it:w},Y,b,H){let z=H?Q0._`${$}, ${W}, ${X}${G}`:W,F=[[v1.default.instancePath,(0,Q0.strConcat)(v1.default.instancePath,J)],[v1.default.parentData,w.parentData],[v1.default.parentDataProperty,w.parentDataProperty],[v1.default.rootData,v1.default.rootData]];if(w.opts.dynamicRef)F.push([v1.default.dynamicAnchors,v1.default.dynamicAnchors]);let U=Q0._`${z}, ${Q.object(...F)}`;return b!==Q0.nil?Q0._`${Y}.call(${b}, ${U})`:Q0._`${Y}(${U})`}vY.callValidateCode=eL;var $A=Q0._`new RegExp`;function WA({gen:$,it:{opts:W}},Q){let X=W.unicodeRegExp?"u":"",{regExp:G}=W.code,J=G(Q,X);return $.scopeValue("pattern",{key:J.toString(),ref:J,code:Q0._`${G.code==="new RegExp"?$A:(0,dL.useFunc)($,G)}(${Q}, ${X})`})}vY.usePattern=WA;function QA($){let{gen:W,data:Q,keyword:X,it:G}=$,J=W.name("valid");if(G.allErrors){let Y=W.let("valid",!0);return w(()=>W.assign(Y,!1)),Y}return W.var(J,!0),w(()=>W.break()),J;function w(Y){let b=W.const("len",Q0._`${Q}.length`);W.forRange("i",0,b,(H)=>{$.subschema({keyword:X,dataProp:H,dataPropType:d8.Type.Num},J),W.if((0,Q0.not)(J),Y)})}}vY.validateArray=QA;function XA($){let{gen:W,schema:Q,keyword:X,it:G}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(Q.some((b)=>(0,d8.alwaysValidSchema)(G,b))&&!G.opts.unevaluated)return;let w=W.let("valid",!1),Y=W.name("_valid");W.block(()=>Q.forEach((b,H)=>{let z=$.subschema({keyword:X,schemaProp:H,compositeRule:!0},Y);if(W.assign(w,Q0._`${w} || ${Y}`),!$.mergeValidEvaluated(z,Y))W.if((0,Q0.not)(w))})),$.result(w,()=>$.reset(),()=>$.error(!0))}vY.validateUnion=XA});var uY=N((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});yY.validateKeywordUsage=yY.validSchemaType=yY.funcKeywordCode=yY.macroKeywordCode=void 0;var q0=g(),g1=F1(),AA=m0(),OA=J4();function KA($,W){let{gen:Q,keyword:X,schema:G,parentSchema:J,it:w}=$,Y=W.macro.call(w.self,G,J,w),b=hY(Q,X,Y);if(w.opts.validateSchema!==!1)w.self.validateSchema(Y,!0);let H=Q.name("valid");$.subschema({schema:Y,schemaPath:q0.nil,errSchemaPath:`${w.errSchemaPath}/${X}`,topSchemaRef:b,compositeRule:!0},H),$.pass(H,()=>$.error(!0))}yY.macroKeywordCode=KA;function ZA($,W){var Q;let{gen:X,keyword:G,schema:J,parentSchema:w,$data:Y,it:b}=$;VA(b,W);let H=!Y&&W.compile?W.compile.call(b.self,J,w,b):W.validate,z=hY(X,G,H),F=X.let("valid");$.block$data(F,U),$.ok((Q=W.valid)!==null&&Q!==void 0?Q:F);function U(){if(W.errors===!1){if(P(),W.modifying)xY($);q(()=>$.error())}else{let M=W.async?B():K();if(W.modifying)xY($);q(()=>PA($,M))}}function B(){let M=X.let("ruleErrs",null);return X.try(()=>P(q0._`await `),(S)=>X.assign(F,!1).if(q0._`${S} instanceof ${b.ValidationError}`,()=>X.assign(M,q0._`${S}.errors`),()=>X.throw(S))),M}function K(){let M=q0._`${z}.errors`;return X.assign(M,null),P(q0.nil),M}function P(M=W.async?q0._`await `:q0.nil){let S=b.opts.passContext?g1.default.this:g1.default.self,C=!(("compile"in W)&&!Y||W.schema===!1);X.assign(F,q0._`${M}${(0,AA.callValidateCode)($,z,S,C)}`,W.modifying)}function q(M){var S;X.if((0,q0.not)((S=W.valid)!==null&&S!==void 0?S:F),M)}}yY.funcKeywordCode=ZA;function xY($){let{gen:W,data:Q,it:X}=$;W.if(X.parentData,()=>W.assign(Q,q0._`${X.parentData}[${X.parentDataProperty}]`))}function PA($,W){let{gen:Q}=$;Q.if(q0._`Array.isArray(${W})`,()=>{Q.assign(g1.default.vErrors,q0._`${g1.default.vErrors} === null ? ${W} : ${g1.default.vErrors}.concat(${W})`).assign(g1.default.errors,q0._`${g1.default.vErrors}.length`),(0,OA.extendErrors)($)},()=>$.error())}function VA({schemaEnv:$},W){if(W.async&&!$.$async)throw Error("async keyword in sync schema")}function hY($,W,Q){if(Q===void 0)throw Error(`keyword "${W}" failed to compile`);return $.scopeValue("keyword",typeof Q=="function"?{ref:Q}:{ref:Q,code:(0,q0.stringify)(Q)})}function jA($,W,Q=!1){return!W.length||W.some((X)=>X==="array"?Array.isArray($):X==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==X||Q&&typeof $>"u")}yY.validSchemaType=jA;function MA({schema:$,opts:W,self:Q,errSchemaPath:X},G,J){if(Array.isArray(G.keyword)?!G.keyword.includes(J):G.keyword!==J)throw Error("ajv implementation error");let w=G.dependencies;if(w===null||w===void 0?void 0:w.some((Y)=>!Object.prototype.hasOwnProperty.call($,Y)))throw Error(`parent schema must have dependencies of ${J}: ${w.join(",")}`);if(G.validateSchema){if(!G.validateSchema($[J])){let b=`keyword "${J}" value is invalid at path "${X}": `+Q.errorsText(G.validateSchema.errors);if(W.validateSchema==="log")Q.logger.error(b);else throw Error(b)}}}yY.validateKeywordUsage=MA});var gY=N((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});mY.extendSubschemaMode=mY.extendSubschemaData=mY.getSubschema=void 0;var Q1=g(),cY=t();function EA($,{keyword:W,schemaProp:Q,schema:X,schemaPath:G,errSchemaPath:J,topSchemaRef:w}){if(W!==void 0&&X!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(W!==void 0){let Y=$.schema[W];return Q===void 0?{schema:Y,schemaPath:Q1._`${$.schemaPath}${(0,Q1.getProperty)(W)}`,errSchemaPath:`${$.errSchemaPath}/${W}`}:{schema:Y[Q],schemaPath:Q1._`${$.schemaPath}${(0,Q1.getProperty)(W)}${(0,Q1.getProperty)(Q)}`,errSchemaPath:`${$.errSchemaPath}/${W}/${(0,cY.escapeFragment)(Q)}`}}if(X!==void 0){if(G===void 0||J===void 0||w===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:X,schemaPath:G,topSchemaRef:w,errSchemaPath:J}}throw Error('either "keyword" or "schema" must be passed')}mY.getSubschema=EA;function TA($,W,{dataProp:Q,dataPropType:X,data:G,dataTypes:J,propertyName:w}){if(G!==void 0&&Q!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=W;if(Q!==void 0){let{errorPath:H,dataPathArr:z,opts:F}=W,U=Y.let("data",Q1._`${W.data}${(0,Q1.getProperty)(Q)}`,!0);b(U),$.errorPath=Q1.str`${H}${(0,cY.getErrorPath)(Q,X,F.jsPropertySyntax)}`,$.parentDataProperty=Q1._`${Q}`,$.dataPathArr=[...z,$.parentDataProperty]}if(G!==void 0){let H=G instanceof Q1.Name?G:Y.let("data",G,!0);if(b(H),w!==void 0)$.propertyName=w}if(J)$.dataTypes=J;function b(H){$.data=H,$.dataLevel=W.dataLevel+1,$.dataTypes=[],W.definedProperties=new Set,$.parentData=W.data,$.dataNames=[...W.dataNames,H]}}mY.extendSubschemaData=TA;function RA($,{jtdDiscriminator:W,jtdMetadata:Q,compositeRule:X,createErrors:G,allErrors:J}){if(X!==void 0)$.compositeRule=X;if(G!==void 0)$.createErrors=G;if(J!==void 0)$.allErrors=J;$.jtdDiscriminator=W,$.jtdMetadata=Q}mY.extendSubschemaMode=RA});var r8=N((yR,pY)=>{pY.exports=function $(W,Q){if(W===Q)return!0;if(W&&Q&&typeof W=="object"&&typeof Q=="object"){if(W.constructor!==Q.constructor)return!1;var X,G,J;if(Array.isArray(W)){if(X=W.length,X!=Q.length)return!1;for(G=X;G--!==0;)if(!$(W[G],Q[G]))return!1;return!0}if(W.constructor===RegExp)return W.source===Q.source&&W.flags===Q.flags;if(W.valueOf!==Object.prototype.valueOf)return W.valueOf()===Q.valueOf();if(W.toString!==Object.prototype.toString)return W.toString()===Q.toString();if(J=Object.keys(W),X=J.length,X!==Object.keys(Q).length)return!1;for(G=X;G--!==0;)if(!Object.prototype.hasOwnProperty.call(Q,J[G]))return!1;for(G=X;G--!==0;){var w=J[G];if(!$(W[w],Q[w]))return!1}return!0}return W!==W&&Q!==Q}});var nY=N((fR,iY)=>{var _1=iY.exports=function($,W,Q){if(typeof W=="function")Q=W,W={};Q=W.cb||Q;var X=typeof Q=="function"?Q:Q.pre||function(){},G=Q.post||function(){};T9(W,X,G,$,"",$)};_1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};_1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};_1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};_1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function T9($,W,Q,X,G,J,w,Y,b,H){if(X&&typeof X=="object"&&!Array.isArray(X)){W(X,G,J,w,Y,b,H);for(var z in X){var F=X[z];if(Array.isArray(F)){if(z in _1.arrayKeywords)for(var U=0;U<F.length;U++)T9($,W,Q,F[U],G+"/"+z+"/"+U,J,G,z,X,U)}else if(z in _1.propsKeywords){if(F&&typeof F=="object")for(var B in F)T9($,W,Q,F[B],G+"/"+z+"/"+kA(B),J,G,z,X,B)}else if(z in _1.keywords||$.allKeys&&!(z in _1.skipKeywords))T9($,W,Q,F,G+"/"+z,J,G,z,X)}Q(X,G,J,w,Y,b,H)}}function kA($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var Y4=N((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});rY.getSchemaRefs=rY.resolveUrl=rY.normalizeId=rY._getFullPath=rY.getFullPath=rY.inlineRef=void 0;var vA=t(),_A=r8(),xA=nY(),hA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function yA($,W=!0){if(typeof $=="boolean")return!0;if(W===!0)return!s8($);if(!W)return!1;return dY($)<=W}rY.inlineRef=yA;var fA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s8($){for(let W in $){if(fA.has(W))return!0;let Q=$[W];if(Array.isArray(Q)&&Q.some(s8))return!0;if(typeof Q=="object"&&s8(Q))return!0}return!1}function dY($){let W=0;for(let Q in $){if(Q==="$ref")return 1/0;if(W++,hA.has(Q))continue;if(typeof $[Q]=="object")(0,vA.eachItem)($[Q],(X)=>W+=dY(X));if(W===1/0)return 1/0}return W}function oY($,W="",Q){if(Q!==!1)W=F6(W);let X=$.parse(W);return tY($,X)}rY.getFullPath=oY;function tY($,W){return $.serialize(W).split("#")[0]+"#"}rY._getFullPath=tY;var uA=/#\/?$/;function F6($){return $?$.replace(uA,""):""}rY.normalizeId=F6;function cA($,W,Q){return Q=F6(Q),$.resolve(W,Q)}rY.resolveUrl=cA;var mA=/^[a-z_][-a-z0-9._]*$/i;function lA($,W){if(typeof $=="boolean")return{};let{schemaId:Q,uriResolver:X}=this.opts,G=F6($[Q]||W),J={"":G},w=oY(X,G,!1),Y={},b=new Set;return xA($,{allKeys:!0},(F,U,B,K)=>{if(K===void 0)return;let P=w+U,q=J[K];if(typeof F[Q]=="string")q=M.call(this,F[Q]);S.call(this,F.$anchor),S.call(this,F.$dynamicAnchor),J[U]=q;function M(C){let v=this.opts.uriResolver.resolve;if(C=F6(q?v(q,C):C),b.has(C))throw z(C);b.add(C);let k=this.refs[C];if(typeof k=="string")k=this.refs[k];if(typeof k=="object")H(F,k.schema,C);else if(C!==F6(P))if(C[0]==="#")H(F,Y[C],C),Y[C]=F;else this.refs[C]=P;return C}function S(C){if(typeof C=="string"){if(!mA.test(C))throw Error(`invalid anchor "${C}"`);M.call(this,`#${C}`)}}}),Y;function H(F,U,B){if(U!==void 0&&!_A(F,U))throw z(B)}function z(F){return Error(`reference "${F}" resolves to more than one schema`)}}rY.getSchemaRefs=lA});var z4=N((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.getData=F7.KeywordCxt=F7.validateFunctionCode=void 0;var Q7=LY(),aY=w4(),e8=g8(),R9=w4(),oA=SY(),H4=uY(),a8=gY(),R=g(),f=F1(),tA=Y4(),U1=t(),b4=J4();function rA($){if(J7($)){if(w7($),G7($)){eA($);return}}X7($,()=>(0,Q7.topBoolOrEmptySchema)($))}F7.validateFunctionCode=rA;function X7({gen:$,validateName:W,schema:Q,schemaEnv:X,opts:G},J){if(G.code.es5)$.func(W,R._`${f.default.data}, ${f.default.valCxt}`,X.$async,()=>{$.code(R._`"use strict"; ${eY(Q,G)}`),aA($,G),$.code(J)});else $.func(W,R._`${f.default.data}, ${sA(G)}`,X.$async,()=>$.code(eY(Q,G)).code(J))}function sA($){return R._`{${f.default.instancePath}="", ${f.default.parentData}, ${f.default.parentDataProperty}, ${f.default.rootData}=${f.default.data}${$.dynamicRef?R._`, ${f.default.dynamicAnchors}={}`:R.nil}}={}`}function aA($,W){$.if(f.default.valCxt,()=>{if($.var(f.default.instancePath,R._`${f.default.valCxt}.${f.default.instancePath}`),$.var(f.default.parentData,R._`${f.default.valCxt}.${f.default.parentData}`),$.var(f.default.parentDataProperty,R._`${f.default.valCxt}.${f.default.parentDataProperty}`),$.var(f.default.rootData,R._`${f.default.valCxt}.${f.default.rootData}`),W.dynamicRef)$.var(f.default.dynamicAnchors,R._`${f.default.valCxt}.${f.default.dynamicAnchors}`)},()=>{if($.var(f.default.instancePath,R._`""`),$.var(f.default.parentData,R._`undefined`),$.var(f.default.parentDataProperty,R._`undefined`),$.var(f.default.rootData,f.default.data),W.dynamicRef)$.var(f.default.dynamicAnchors,R._`{}`)})}function eA($){let{schema:W,opts:Q,gen:X}=$;X7($,()=>{if(Q.$comment&&W.$comment)b7($);if(GO($),X.let(f.default.vErrors,null),X.let(f.default.errors,0),Q.unevaluated)$O($);Y7($),YO($)});return}function $O($){let{gen:W,validateName:Q}=$;$.evaluated=W.const("evaluated",R._`${Q}.evaluated`),W.if(R._`${$.evaluated}.dynamicProps`,()=>W.assign(R._`${$.evaluated}.props`,R._`undefined`)),W.if(R._`${$.evaluated}.dynamicItems`,()=>W.assign(R._`${$.evaluated}.items`,R._`undefined`))}function eY($,W){let Q=typeof $=="object"&&$[W.schemaId];return Q&&(W.code.source||W.code.process)?R._`/*# sourceURL=${Q} */`:R.nil}function WO($,W){if(J7($)){if(w7($),G7($)){QO($,W);return}}(0,Q7.boolOrEmptySchema)($,W)}function G7({schema:$,self:W}){if(typeof $=="boolean")return!$;for(let Q in $)if(W.RULES.all[Q])return!0;return!1}function J7($){return typeof $.schema!="boolean"}function QO($,W){let{schema:Q,gen:X,opts:G}=$;if(G.$comment&&Q.$comment)b7($);JO($),wO($);let J=X.const("_errs",f.default.errors);Y7($,J),X.var(W,R._`${J} === ${f.default.errors}`)}function w7($){(0,U1.checkUnknownRules)($),XO($)}function Y7($,W){if($.opts.jtd)return $7($,[],!1,W);let Q=(0,aY.getSchemaTypes)($.schema),X=(0,aY.coerceAndCheckDataType)($,Q);$7($,Q,!X,W)}function XO($){let{schema:W,errSchemaPath:Q,opts:X,self:G}=$;if(W.$ref&&X.ignoreKeywordsWithRef&&(0,U1.schemaHasRulesButRef)(W,G.RULES))G.logger.warn(`$ref: keywords ignored in schema at path "${Q}"`)}function GO($){let{schema:W,opts:Q}=$;if(W.default!==void 0&&Q.useDefaults&&Q.strictSchema)(0,U1.checkStrictMode)($,"default is ignored in the schema root")}function JO($){let W=$.schema[$.opts.schemaId];if(W)$.baseId=(0,tA.resolveUrl)($.opts.uriResolver,$.baseId,W)}function wO($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function b7({gen:$,schemaEnv:W,schema:Q,errSchemaPath:X,opts:G}){let J=Q.$comment;if(G.$comment===!0)$.code(R._`${f.default.self}.logger.log(${J})`);else if(typeof G.$comment=="function"){let w=R.str`${X}/$comment`,Y=$.scopeValue("root",{ref:W.root});$.code(R._`${f.default.self}.opts.$comment(${J}, ${w}, ${Y}.schema)`)}}function YO($){let{gen:W,schemaEnv:Q,validateName:X,ValidationError:G,opts:J}=$;if(Q.$async)W.if(R._`${f.default.errors} === 0`,()=>W.return(f.default.data),()=>W.throw(R._`new ${G}(${f.default.vErrors})`));else{if(W.assign(R._`${X}.errors`,f.default.vErrors),J.unevaluated)bO($);W.return(R._`${f.default.errors} === 0`)}}function bO({gen:$,evaluated:W,props:Q,items:X}){if(Q instanceof R.Name)$.assign(R._`${W}.props`,Q);if(X instanceof R.Name)$.assign(R._`${W}.items`,X)}function $7($,W,Q,X){let{gen:G,schema:J,data:w,allErrors:Y,opts:b,self:H}=$,{RULES:z}=H;if(J.$ref&&(b.ignoreKeywordsWithRef||!(0,U1.schemaHasRulesButRef)(J,z))){G.block(()=>z7($,"$ref",z.all.$ref.definition));return}if(!b.jtd)HO($,W);G.block(()=>{for(let U of z.rules)F(U);F(z.post)});function F(U){if(!(0,e8.shouldUseGroup)(J,U))return;if(U.type){if(G.if((0,R9.checkDataType)(U.type,w,b.strictNumbers)),W7($,U),W.length===1&&W[0]===U.type&&Q)G.else(),(0,R9.reportTypeError)($);G.endIf()}else W7($,U);if(!Y)G.if(R._`${f.default.errors} === ${X||0}`)}}function W7($,W){let{gen:Q,schema:X,opts:{useDefaults:G}}=$;if(G)(0,oA.assignDefaults)($,W.type);Q.block(()=>{for(let J of W.rules)if((0,e8.shouldUseRule)(X,J))z7($,J.keyword,J.definition,W.type)})}function HO($,W){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(zO($,W),!$.opts.allowUnionTypes)DO($,W);FO($,$.dataTypes)}function zO($,W){if(!W.length)return;if(!$.dataTypes.length){$.dataTypes=W;return}W.forEach((Q)=>{if(!H7($.dataTypes,Q))$W($,`type "${Q}" not allowed by context "${$.dataTypes.join(",")}"`)}),BO($,W)}function DO($,W){if(W.length>1&&!(W.length===2&&W.includes("null")))$W($,"use allowUnionTypes to allow union type keyword")}function FO($,W){let Q=$.self.RULES.all;for(let X in Q){let G=Q[X];if(typeof G=="object"&&(0,e8.shouldUseRule)($.schema,G)){let{type:J}=G.definition;if(J.length&&!J.some((w)=>UO(W,w)))$W($,`missing type "${J.join(",")}" for keyword "${X}"`)}}}function UO($,W){return $.includes(W)||W==="number"&&$.includes("integer")}function H7($,W){return $.includes(W)||W==="integer"&&$.includes("number")}function BO($,W){let Q=[];for(let X of $.dataTypes)if(H7(W,X))Q.push(X);else if(W.includes("integer")&&X==="number")Q.push("integer");$.dataTypes=Q}function $W($,W){let Q=$.schemaEnv.baseId+$.errSchemaPath;W+=` at "${Q}" (strictTypes)`,(0,U1.checkStrictMode)($,W,$.opts.strictTypes)}class WW{constructor($,W,Q){if((0,H4.validateKeywordUsage)($,W,Q),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=Q,this.data=$.data,this.schema=$.schema[Q],this.$data=W.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,U1.schemaRefOrVal)($,this.schema,Q,this.$data),this.schemaType=W.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=W,this.$data)this.schemaCode=$.gen.const("vSchema",D7(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,H4.validSchemaType)(this.schema,W.schemaType,W.allowUndefined))throw Error(`${Q} value must be ${JSON.stringify(W.schemaType)}`);if("code"in W?W.trackErrors:W.errors!==!1)this.errsCount=$.gen.const("_errs",f.default.errors)}result($,W,Q){this.failResult((0,R.not)($),W,Q)}failResult($,W,Q){if(this.gen.if($),Q)Q();else this.error();if(W){if(this.gen.else(),W(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,W){this.failResult((0,R.not)($),void 0,W)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:W}=this;this.fail(R._`${W} !== undefined && (${(0,R.or)(this.invalid$data(),$)})`)}error($,W,Q){if(W){this.setParams(W),this._error($,Q),this.setParams({});return}this._error($,Q)}_error($,W){($?b4.reportExtraError:b4.reportError)(this,this.def.error,W)}$dataError(){(0,b4.reportError)(this,this.def.$dataError||b4.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,b4.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,W){if(W)Object.assign(this.params,$);else this.params=$}block$data($,W,Q=R.nil){this.gen.block(()=>{this.check$data($,Q),W()})}check$data($=R.nil,W=R.nil){if(!this.$data)return;let{gen:Q,schemaCode:X,schemaType:G,def:J}=this;if(Q.if((0,R.or)(R._`${X} === undefined`,W)),$!==R.nil)Q.assign($,!0);if(G.length||J.validateSchema){if(Q.elseIf(this.invalid$data()),this.$dataError(),$!==R.nil)Q.assign($,!1)}Q.else()}invalid$data(){let{gen:$,schemaCode:W,schemaType:Q,def:X,it:G}=this;return(0,R.or)(J(),w());function J(){if(Q.length){if(!(W instanceof R.Name))throw Error("ajv implementation error");let Y=Array.isArray(Q)?Q:[Q];return R._`${(0,R9.checkDataTypes)(Y,W,G.opts.strictNumbers,R9.DataType.Wrong)}`}return R.nil}function w(){if(X.validateSchema){let Y=$.scopeValue("validate$data",{ref:X.validateSchema});return R._`!${Y}(${W})`}return R.nil}}subschema($,W){let Q=(0,a8.getSubschema)(this.it,$);(0,a8.extendSubschemaData)(Q,this.it,$),(0,a8.extendSubschemaMode)(Q,$);let X={...this.it,...Q,items:void 0,props:void 0};return WO(X,W),X}mergeEvaluated($,W){let{it:Q,gen:X}=this;if(!Q.opts.unevaluated)return;if(Q.props!==!0&&$.props!==void 0)Q.props=U1.mergeEvaluated.props(X,$.props,Q.props,W);if(Q.items!==!0&&$.items!==void 0)Q.items=U1.mergeEvaluated.items(X,$.items,Q.items,W)}mergeValidEvaluated($,W){let{it:Q,gen:X}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return X.if(W,()=>this.mergeEvaluated($,R.Name)),!0}}F7.KeywordCxt=WW;function z7($,W,Q,X){let G=new WW($,Q,W);if("code"in Q)Q.code(G,X);else if(G.$data&&Q.validate)(0,H4.funcKeywordCode)(G,Q);else if("macro"in Q)(0,H4.macroKeywordCode)(G,Q);else if(Q.compile||Q.validate)(0,H4.funcKeywordCode)(G,Q)}var LO=/^\/(?:[^~]|~0|~1)*$/,AO=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function D7($,{dataLevel:W,dataNames:Q,dataPathArr:X}){let G,J;if($==="")return f.default.rootData;if($[0]==="/"){if(!LO.test($))throw Error(`Invalid JSON-pointer: ${$}`);G=$,J=f.default.rootData}else{let H=AO.exec($);if(!H)throw Error(`Invalid JSON-pointer: ${$}`);let z=+H[1];if(G=H[2],G==="#"){if(z>=W)throw Error(b("property/index",z));return X[W-z]}if(z>W)throw Error(b("data",z));if(J=Q[W-z],!G)return J}let w=J,Y=G.split("/");for(let H of Y)if(H)J=R._`${J}${(0,R.getProperty)((0,U1.unescapeJsonPointer)(H))}`,w=R._`${w} && ${J}`;return w;function b(H,z){return`Cannot access ${H} ${z} levels up, current level is ${W}`}}F7.getData=D7});var S9=N((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});class B7 extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}L7.default=B7});var D4=N((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});var QW=Y4();class A7 extends Error{constructor($,W,Q,X){super(X||`can't resolve reference ${Q} from id ${W}`);this.missingRef=(0,QW.resolveUrl)($,W,Q),this.missingSchema=(0,QW.normalizeId)((0,QW.getFullPath)($,this.missingRef))}}O7.default=A7});var k9=N((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.resolveSchema=P7.getCompilingSchema=P7.resolveRef=P7.compileSchema=P7.SchemaEnv=void 0;var t0=g(),VO=S9(),p1=F1(),r0=Y4(),K7=t(),jO=z4();class F4{constructor($){var W;this.refs={},this.dynamicAnchors={};let Q;if(typeof $.schema=="object")Q=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(W=$.baseId)!==null&&W!==void 0?W:(0,r0.normalizeId)(Q===null||Q===void 0?void 0:Q[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=Q===null||Q===void 0?void 0:Q.$async,this.refs={}}}P7.SchemaEnv=F4;function GW($){let W=Z7.call(this,$);if(W)return W;let Q=(0,r0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:X,lines:G}=this.opts.code,{ownProperties:J}=this.opts,w=new t0.CodeGen(this.scope,{es5:X,lines:G,ownProperties:J}),Y;if($.$async)Y=w.scopeValue("Error",{ref:VO.default,code:t0._`require("ajv/dist/runtime/validation_error").default`});let b=w.scopeName("validate");$.validateName=b;let H={gen:w,allErrors:this.opts.allErrors,data:p1.default.data,parentData:p1.default.parentData,parentDataProperty:p1.default.parentDataProperty,dataNames:[p1.default.data],dataPathArr:[t0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:w.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,t0.stringify)($.schema)}:{ref:$.schema}),validateName:b,ValidationError:Y,schema:$.schema,schemaEnv:$,rootId:Q,baseId:$.baseId||Q,schemaPath:t0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:t0._`""`,opts:this.opts,self:this},z;try{this._compilations.add($),(0,jO.validateFunctionCode)(H),w.optimize(this.opts.code.optimize);let F=w.toString();if(z=`${w.scopeRefs(p1.default.scope)}return ${F}`,this.opts.code.process)z=this.opts.code.process(z,$);let B=Function(`${p1.default.self}`,`${p1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(b,{ref:B}),B.errors=null,B.schema=$.schema,B.schemaEnv=$,$.$async)B.$async=!0;if(this.opts.code.source===!0)B.source={validateName:b,validateCode:F,scopeValues:w._values};if(this.opts.unevaluated){let{props:K,items:P}=H;if(B.evaluated={props:K instanceof t0.Name?void 0:K,items:P instanceof t0.Name?void 0:P,dynamicProps:K instanceof t0.Name,dynamicItems:P instanceof t0.Name},B.source)B.source.evaluated=(0,t0.stringify)(B.evaluated)}return $.validate=B,$}catch(F){if(delete $.validate,delete $.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw F}finally{this._compilations.delete($)}}P7.compileSchema=GW;function MO($,W,Q){var X;Q=(0,r0.resolveUrl)(this.opts.uriResolver,W,Q);let G=$.refs[Q];if(G)return G;let J=NO.call(this,$,Q);if(J===void 0){let w=(X=$.localRefs)===null||X===void 0?void 0:X[Q],{schemaId:Y}=this.opts;if(w)J=new F4({schema:w,schemaId:Y,root:$,baseId:W})}if(J===void 0)return;return $.refs[Q]=qO.call(this,J)}P7.resolveRef=MO;function qO($){if((0,r0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:GW.call(this,$)}function Z7($){for(let W of this._compilations)if(IO(W,$))return W}P7.getCompilingSchema=Z7;function IO($,W){return $.schema===W.schema&&$.root===W.root&&$.baseId===W.baseId}function NO($,W){let Q;while(typeof(Q=this.refs[W])=="string")W=Q;return Q||this.schemas[W]||C9.call(this,$,W)}function C9($,W){let Q=this.opts.uriResolver.parse(W),X=(0,r0._getFullPath)(this.opts.uriResolver,Q),G=(0,r0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&X===G)return XW.call(this,Q,$);let J=(0,r0.normalizeId)(X),w=this.refs[J]||this.schemas[J];if(typeof w=="string"){let Y=C9.call(this,$,w);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return XW.call(this,Q,Y)}if(typeof(w===null||w===void 0?void 0:w.schema)!=="object")return;if(!w.validate)GW.call(this,w);if(J===(0,r0.normalizeId)(W)){let{schema:Y}=w,{schemaId:b}=this.opts,H=Y[b];if(H)G=(0,r0.resolveUrl)(this.opts.uriResolver,G,H);return new F4({schema:Y,schemaId:b,root:$,baseId:G})}return XW.call(this,Q,w)}P7.resolveSchema=C9;var EO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function XW($,{baseId:W,schema:Q,root:X}){var G;if(((G=$.fragment)===null||G===void 0?void 0:G[0])!=="/")return;for(let Y of $.fragment.slice(1).split("/")){if(typeof Q==="boolean")return;let b=Q[(0,K7.unescapeFragment)(Y)];if(b===void 0)return;Q=b;let H=typeof Q==="object"&&Q[this.opts.schemaId];if(!EO.has(Y)&&H)W=(0,r0.resolveUrl)(this.opts.uriResolver,W,H)}let J;if(typeof Q!="boolean"&&Q.$ref&&!(0,K7.schemaHasRulesButRef)(Q,this.RULES)){let Y=(0,r0.resolveUrl)(this.opts.uriResolver,W,Q.$ref);J=C9.call(this,X,Y)}let{schemaId:w}=this.opts;if(J=J||new F4({schema:Q,schemaId:w,root:X,baseId:W}),J.schema!==J.root.schema)return J;return}});var j7=N((pR,kO)=>{kO.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var wW=N((iR,N7)=>{var vO=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),q7=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function JW($){let W="",Q=0,X=0;for(X=0;X<$.length;X++){if(Q=$[X].charCodeAt(0),Q===48)continue;if(!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";W+=$[X];break}for(X+=1;X<$.length;X++){if(Q=$[X].charCodeAt(0),!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";W+=$[X]}return W}var _O=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function M7($){return $.length=0,!0}function xO($,W,Q){if($.length){let X=JW($);if(X!=="")W.push(X);else return Q.error=!0,!1;$.length=0}return!0}function hO($){let W=0,Q={error:!1,address:"",zone:""},X=[],G=[],J=!1,w=!1,Y=xO;for(let b=0;b<$.length;b++){let H=$[b];if(H==="["||H==="]")continue;if(H===":"){if(J===!0)w=!0;if(!Y(G,X,Q))break;if(++W>7){Q.error=!0;break}if(b>0&&$[b-1]===":")J=!0;X.push(":");continue}else if(H==="%"){if(!Y(G,X,Q))break;Y=M7}else{G.push(H);continue}}if(G.length)if(Y===M7)Q.zone=G.join("");else if(w)X.push(G.join(""));else X.push(JW(G));return Q.address=X.join(""),Q}function I7($){if(yO($,":")<2)return{host:$,isIPV6:!1};let W=hO($);if(!W.error){let{address:Q,address:X}=W;if(W.zone)Q+="%"+W.zone,X+="%25"+W.zone;return{host:Q,isIPV6:!0,escapedHost:X}}else return{host:$,isIPV6:!1}}function yO($,W){let Q=0;for(let X=0;X<$.length;X++)if($[X]===W)Q++;return Q}function fO($){let W=$,Q=[],X=-1,G=0;while(G=W.length){if(G===1)if(W===".")break;else if(W==="/"){Q.push("/");break}else{Q.push(W);break}else if(G===2){if(W[0]==="."){if(W[1]===".")break;else if(W[1]==="/"){W=W.slice(2);continue}}else if(W[0]==="/"){if(W[1]==="."||W[1]==="/"){Q.push("/");break}}}else if(G===3){if(W==="/.."){if(Q.length!==0)Q.pop();Q.push("/");break}}if(W[0]==="."){if(W[1]==="."){if(W[2]==="/"){W=W.slice(3);continue}}else if(W[1]==="/"){W=W.slice(2);continue}}else if(W[0]==="/"){if(W[1]==="."){if(W[2]==="/"){W=W.slice(2);continue}else if(W[2]==="."){if(W[3]==="/"){if(W=W.slice(3),Q.length!==0)Q.pop();continue}}}}if((X=W.indexOf("/",1))===-1){Q.push(W);break}else Q.push(W.slice(0,X)),W=W.slice(X)}return Q.join("")}function uO($,W){let Q=W!==!0?escape:unescape;if($.scheme!==void 0)$.scheme=Q($.scheme);if($.userinfo!==void 0)$.userinfo=Q($.userinfo);if($.host!==void 0)$.host=Q($.host);if($.path!==void 0)$.path=Q($.path);if($.query!==void 0)$.query=Q($.query);if($.fragment!==void 0)$.fragment=Q($.fragment);return $}function cO($){let W=[];if($.userinfo!==void 0)W.push($.userinfo),W.push("@");if($.host!==void 0){let Q=unescape($.host);if(!q7(Q)){let X=I7(Q);if(X.isIPV6===!0)Q=`[${X.escapedHost}]`;else Q=$.host}W.push(Q)}if(typeof $.port==="number"||typeof $.port==="string")W.push(":"),W.push(String($.port));return W.length?W.join(""):void 0}N7.exports={nonSimpleDomain:_O,recomposeAuthority:cO,normalizeComponentEncoding:uO,removeDotSegments:fO,isIPv4:q7,isUUID:vO,normalizeIPv6:I7,stringArrayToHexStripped:JW}});var C7=N((nR,S7)=>{var{isUUID:mO}=wW(),lO=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,gO=["http","https","ws","wss","urn","urn:uuid"];function pO($){return gO.indexOf($)!==-1}function YW($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function E7($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function T7($){let W=String($.scheme).toLowerCase()==="https";if($.port===(W?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function iO($){return $.secure=YW($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function nO($){if($.port===(YW($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[W,Q]=$.resourceName.split("?");$.path=W&&W!=="/"?W:void 0,$.query=Q,$.resourceName=void 0}return $.fragment=void 0,$}function dO($,W){if(!$.path)return $.error="URN can not be parsed",$;let Q=$.path.match(lO);if(Q){let X=W.scheme||$.scheme||"urn";$.nid=Q[1].toLowerCase(),$.nss=Q[2];let G=`${X}:${W.nid||$.nid}`,J=bW(G);if($.path=void 0,J)$=J.parse($,W)}else $.error=$.error||"URN can not be parsed.";return $}function oO($,W){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let Q=W.scheme||$.scheme||"urn",X=$.nid.toLowerCase(),G=`${Q}:${W.nid||X}`,J=bW(G);if(J)$=J.serialize($,W);let w=$,Y=$.nss;return w.path=`${X||W.nid}:${Y}`,W.skipEscape=!0,w}function tO($,W){let Q=$;if(Q.uuid=Q.nss,Q.nss=void 0,!W.tolerant&&(!Q.uuid||!mO(Q.uuid)))Q.error=Q.error||"UUID is not valid.";return Q}function rO($){let W=$;return W.nss=($.uuid||"").toLowerCase(),W}var R7={scheme:"http",domainHost:!0,parse:E7,serialize:T7},sO={scheme:"https",domainHost:R7.domainHost,parse:E7,serialize:T7},v9={scheme:"ws",domainHost:!0,parse:iO,serialize:nO},aO={scheme:"wss",domainHost:v9.domainHost,parse:v9.parse,serialize:v9.serialize},eO={scheme:"urn",parse:dO,serialize:oO,skipNormalize:!0},$K={scheme:"urn:uuid",parse:tO,serialize:rO,skipNormalize:!0},_9={http:R7,https:sO,ws:v9,wss:aO,urn:eO,"urn:uuid":$K};Object.setPrototypeOf(_9,null);function bW($){return $&&(_9[$]||_9[$.toLowerCase()])||void 0}S7.exports={wsIsSecure:YW,SCHEMES:_9,isValidSchemeName:pO,getSchemeHandler:bW}});var _7=N((dR,h9)=>{var{normalizeIPv6:WK,removeDotSegments:U4,recomposeAuthority:QK,normalizeComponentEncoding:x9,isIPv4:XK,nonSimpleDomain:GK}=wW(),{SCHEMES:JK,getSchemeHandler:k7}=C7();function wK($,W){if(typeof $==="string")$=X1(B1($,W),W);else if(typeof $==="object")$=B1(X1($,W),W);return $}function YK($,W,Q){let X=Q?Object.assign({scheme:"null"},Q):{scheme:"null"},G=v7(B1($,X),B1(W,X),X,!0);return X.skipEscape=!0,X1(G,X)}function v7($,W,Q,X){let G={};if(!X)$=B1(X1($,Q),Q),W=B1(X1(W,Q),Q);if(Q=Q||{},!Q.tolerant&&W.scheme)G.scheme=W.scheme,G.userinfo=W.userinfo,G.host=W.host,G.port=W.port,G.path=U4(W.path||""),G.query=W.query;else{if(W.userinfo!==void 0||W.host!==void 0||W.port!==void 0)G.userinfo=W.userinfo,G.host=W.host,G.port=W.port,G.path=U4(W.path||""),G.query=W.query;else{if(!W.path)if(G.path=$.path,W.query!==void 0)G.query=W.query;else G.query=$.query;else{if(W.path[0]==="/")G.path=U4(W.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)G.path="/"+W.path;else if(!$.path)G.path=W.path;else G.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+W.path;G.path=U4(G.path)}G.query=W.query}G.userinfo=$.userinfo,G.host=$.host,G.port=$.port}G.scheme=$.scheme}return G.fragment=W.fragment,G}function bK($,W,Q){if(typeof $==="string")$=unescape($),$=X1(x9(B1($,Q),!0),{...Q,skipEscape:!0});else if(typeof $==="object")$=X1(x9($,!0),{...Q,skipEscape:!0});if(typeof W==="string")W=unescape(W),W=X1(x9(B1(W,Q),!0),{...Q,skipEscape:!0});else if(typeof W==="object")W=X1(x9(W,!0),{...Q,skipEscape:!0});return $.toLowerCase()===W.toLowerCase()}function X1($,W){let Q={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},X=Object.assign({},W),G=[],J=k7(X.scheme||Q.scheme);if(J&&J.serialize)J.serialize(Q,X);if(Q.path!==void 0)if(!X.skipEscape){if(Q.path=escape(Q.path),Q.scheme!==void 0)Q.path=Q.path.split("%3A").join(":")}else Q.path=unescape(Q.path);if(X.reference!=="suffix"&&Q.scheme)G.push(Q.scheme,":");let w=QK(Q);if(w!==void 0){if(X.reference!=="suffix")G.push("//");if(G.push(w),Q.path&&Q.path[0]!=="/")G.push("/")}if(Q.path!==void 0){let Y=Q.path;if(!X.absolutePath&&(!J||!J.absolutePath))Y=U4(Y);if(w===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);G.push(Y)}if(Q.query!==void 0)G.push("?",Q.query);if(Q.fragment!==void 0)G.push("#",Q.fragment);return G.join("")}var HK=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function B1($,W){let Q=Object.assign({},W),X={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},G=!1;if(Q.reference==="suffix")if(Q.scheme)$=Q.scheme+":"+$;else $="//"+$;let J=$.match(HK);if(J){if(X.scheme=J[1],X.userinfo=J[3],X.host=J[4],X.port=parseInt(J[5],10),X.path=J[6]||"",X.query=J[7],X.fragment=J[8],isNaN(X.port))X.port=J[5];if(X.host)if(XK(X.host)===!1){let b=WK(X.host);X.host=b.host.toLowerCase(),G=b.isIPV6}else G=!0;if(X.scheme===void 0&&X.userinfo===void 0&&X.host===void 0&&X.port===void 0&&X.query===void 0&&!X.path)X.reference="same-document";else if(X.scheme===void 0)X.reference="relative";else if(X.fragment===void 0)X.reference="absolute";else X.reference="uri";if(Q.reference&&Q.reference!=="suffix"&&Q.reference!==X.reference)X.error=X.error||"URI is not a "+Q.reference+" reference.";let w=k7(Q.scheme||X.scheme);if(!Q.unicodeSupport&&(!w||!w.unicodeSupport)){if(X.host&&(Q.domainHost||w&&w.domainHost)&&G===!1&&GK(X.host))try{X.host=URL.domainToASCII(X.host.toLowerCase())}catch(Y){X.error=X.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!w||w&&!w.skipNormalize){if($.indexOf("%")!==-1){if(X.scheme!==void 0)X.scheme=unescape(X.scheme);if(X.host!==void 0)X.host=unescape(X.host)}if(X.path)X.path=escape(unescape(X.path));if(X.fragment)X.fragment=encodeURI(decodeURIComponent(X.fragment))}if(w&&w.parse)w.parse(X,Q)}else X.error=X.error||"URI can not be parsed.";return X}var HW={SCHEMES:JK,normalize:wK,resolve:YK,resolveComponent:v7,equal:bK,serialize:X1,parse:B1};h9.exports=HW;h9.exports.default=HW;h9.exports.fastUri=HW});var y7=N((h7)=>{Object.defineProperty(h7,"__esModule",{value:!0});var x7=_7();x7.code='require("ajv/dist/runtime/uri").default';h7.default=x7});var i7=N((L1)=>{Object.defineProperty(L1,"__esModule",{value:!0});L1.CodeGen=L1.Name=L1.nil=L1.stringify=L1.str=L1._=L1.KeywordCxt=void 0;var DK=z4();Object.defineProperty(L1,"KeywordCxt",{enumerable:!0,get:function(){return DK.KeywordCxt}});var U6=g();Object.defineProperty(L1,"_",{enumerable:!0,get:function(){return U6._}});Object.defineProperty(L1,"str",{enumerable:!0,get:function(){return U6.str}});Object.defineProperty(L1,"stringify",{enumerable:!0,get:function(){return U6.stringify}});Object.defineProperty(L1,"nil",{enumerable:!0,get:function(){return U6.nil}});Object.defineProperty(L1,"Name",{enumerable:!0,get:function(){return U6.Name}});Object.defineProperty(L1,"CodeGen",{enumerable:!0,get:function(){return U6.CodeGen}});var FK=S9(),l7=D4(),UK=l8(),B4=k9(),BK=g(),L4=Y4(),y9=w4(),DW=t(),f7=j7(),LK=y7(),g7=($,W)=>new RegExp($,W);g7.code="new RegExp";var AK=["removeAdditional","useDefaults","coerceTypes"],OK=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),KK={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},ZK={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},u7=200;function PK($){var W,Q,X,G,J,w,Y,b,H,z,F,U,B,K,P,q,M,S,C,v,k,S0,g0,C0,a1;let p0=$.strict,R6=(W=$.code)===null||W===void 0?void 0:W.optimize,P1=R6===!0||R6===void 0?1:R6||0,TQ=(X=(Q=$.code)===null||Q===void 0?void 0:Q.regExp)!==null&&X!==void 0?X:g7,Oz=(G=$.uriResolver)!==null&&G!==void 0?G:LK.default;return{strictSchema:(w=(J=$.strictSchema)!==null&&J!==void 0?J:p0)!==null&&w!==void 0?w:!0,strictNumbers:(b=(Y=$.strictNumbers)!==null&&Y!==void 0?Y:p0)!==null&&b!==void 0?b:!0,strictTypes:(z=(H=$.strictTypes)!==null&&H!==void 0?H:p0)!==null&&z!==void 0?z:"log",strictTuples:(U=(F=$.strictTuples)!==null&&F!==void 0?F:p0)!==null&&U!==void 0?U:"log",strictRequired:(K=(B=$.strictRequired)!==null&&B!==void 0?B:p0)!==null&&K!==void 0?K:!1,code:$.code?{...$.code,optimize:P1,regExp:TQ}:{optimize:P1,regExp:TQ},loopRequired:(P=$.loopRequired)!==null&&P!==void 0?P:u7,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:u7,meta:(M=$.meta)!==null&&M!==void 0?M:!0,messages:(S=$.messages)!==null&&S!==void 0?S:!0,inlineRefs:(C=$.inlineRefs)!==null&&C!==void 0?C:!0,schemaId:(v=$.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(k=$.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(S0=$.validateSchema)!==null&&S0!==void 0?S0:!0,validateFormats:(g0=$.validateFormats)!==null&&g0!==void 0?g0:!0,unicodeRegExp:(C0=$.unicodeRegExp)!==null&&C0!==void 0?C0:!0,int32range:(a1=$.int32range)!==null&&a1!==void 0?a1:!0,uriResolver:Oz}}class f9{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...PK($)};let{es5:W,lines:Q}=this.opts.code;this.scope=new BK.ValueScope({scope:{},prefixes:OK,es5:W,lines:Q}),this.logger=NK($.logger);let X=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,UK.getRules)(),c7.call(this,KK,$,"NOT SUPPORTED"),c7.call(this,ZK,$,"DEPRECATED","warn"),this._metaOpts=qK.call(this),$.formats)jK.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)MK.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);VK.call(this),$.validateFormats=X}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:W,schemaId:Q}=this.opts,X=f7;if(Q==="id")X={...f7},X.id=X.$id,delete X.$id;if(W&&$)this.addMetaSchema(X,X[Q],!1)}defaultMeta(){let{meta:$,schemaId:W}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[W]||$:void 0}validate($,W){let Q;if(typeof $=="string"){if(Q=this.getSchema($),!Q)throw Error(`no schema with key or ref "${$}"`)}else Q=this.compile($);let X=Q(W);if(!("$async"in Q))this.errors=Q.errors;return X}compile($,W){let Q=this._addSchema($,W);return Q.validate||this._compileSchemaEnv(Q)}compileAsync($,W){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:Q}=this.opts;return X.call(this,$,W);async function X(H,z){await G.call(this,H.$schema);let F=this._addSchema(H,z);return F.validate||J.call(this,F)}async function G(H){if(H&&!this.getSchema(H))await X.call(this,{$ref:H},!0)}async function J(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof l7.default))throw z;return w.call(this,z),await Y.call(this,z.missingSchema),J.call(this,H)}}function w({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function Y(H){let z=await b.call(this,H);if(!this.refs[H])await G.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,W)}async function b(H){let z=this._loading[H];if(z)return z;try{return await(this._loading[H]=Q(H))}finally{delete this._loading[H]}}}addSchema($,W,Q,X=this.opts.validateSchema){if(Array.isArray($)){for(let J of $)this.addSchema(J,void 0,Q,X);return this}let G;if(typeof $==="object"){let{schemaId:J}=this.opts;if(G=$[J],G!==void 0&&typeof G!="string")throw Error(`schema ${J} must be string`)}return W=(0,L4.normalizeId)(W||G),this._checkUnique(W),this.schemas[W]=this._addSchema($,Q,W,X,!0),this}addMetaSchema($,W,Q=this.opts.validateSchema){return this.addSchema($,W,!0,Q),this}validateSchema($,W){if(typeof $=="boolean")return!0;let Q;if(Q=$.$schema,Q!==void 0&&typeof Q!="string")throw Error("$schema must be a string");if(Q=Q||this.opts.defaultMeta||this.defaultMeta(),!Q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let X=this.validate(Q,$);if(!X&&W){let G="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(G);else throw Error(G)}return X}getSchema($){let W;while(typeof(W=m7.call(this,$))=="string")$=W;if(W===void 0){let{schemaId:Q}=this.opts,X=new B4.SchemaEnv({schema:{},schemaId:Q});if(W=B4.resolveSchema.call(this,X,$),!W)return;this.refs[$]=W}return W.validate||this._compileSchemaEnv(W)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let W=m7.call(this,$);if(typeof W=="object")this._cache.delete(W.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let W=$;this._cache.delete(W);let Q=$[this.opts.schemaId];if(Q)Q=(0,L4.normalizeId)(Q),delete this.schemas[Q],delete this.refs[Q];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let W of $)this.addKeyword(W);return this}addKeyword($,W){let Q;if(typeof $=="string"){if(Q=$,typeof W=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),W.keyword=Q}else if(typeof $=="object"&&W===void 0){if(W=$,Q=W.keyword,Array.isArray(Q)&&!Q.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(TK.call(this,Q,W),!W)return(0,DW.eachItem)(Q,(G)=>zW.call(this,G)),this;SK.call(this,W);let X={...W,type:(0,y9.getJSONTypes)(W.type),schemaType:(0,y9.getJSONTypes)(W.schemaType)};return(0,DW.eachItem)(Q,X.type.length===0?(G)=>zW.call(this,G,X):(G)=>X.type.forEach((J)=>zW.call(this,G,X,J))),this}getKeyword($){let W=this.RULES.all[$];return typeof W=="object"?W.definition:!!W}removeKeyword($){let{RULES:W}=this;delete W.keywords[$],delete W.all[$];for(let Q of W.rules){let X=Q.rules.findIndex((G)=>G.keyword===$);if(X>=0)Q.rules.splice(X,1)}return this}addFormat($,W){if(typeof W=="string")W=new RegExp(W);return this.formats[$]=W,this}errorsText($=this.errors,{separator:W=", ",dataVar:Q="data"}={}){if(!$||$.length===0)return"No errors";return $.map((X)=>`${Q}${X.instancePath} ${X.message}`).reduce((X,G)=>X+W+G)}$dataMetaSchema($,W){let Q=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let X of W){let G=X.split("/").slice(1),J=$;for(let w of G)J=J[w];for(let w in Q){let Y=Q[w];if(typeof Y!="object")continue;let{$data:b}=Y.definition,H=J[w];if(b&&H)J[w]=p7(H)}}return $}_removeAllSchemas($,W){for(let Q in $){let X=$[Q];if(!W||W.test(Q)){if(typeof X=="string")delete $[Q];else if(X&&!X.meta)this._cache.delete(X.schema),delete $[Q]}}}_addSchema($,W,Q,X=this.opts.validateSchema,G=this.opts.addUsedSchema){let J,{schemaId:w}=this.opts;if(typeof $=="object")J=$[w];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let Y=this._cache.get($);if(Y!==void 0)return Y;Q=(0,L4.normalizeId)(J||Q);let b=L4.getSchemaRefs.call(this,$,Q);if(Y=new B4.SchemaEnv({schema:$,schemaId:w,meta:W,baseId:Q,localRefs:b}),this._cache.set(Y.schema,Y),G&&!Q.startsWith("#")){if(Q)this._checkUnique(Q);this.refs[Q]=Y}if(X)this.validateSchema($,!0);return Y}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else B4.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let W=this.opts;this.opts=this._metaOpts;try{B4.compileSchema.call(this,$)}finally{this.opts=W}}}f9.ValidationError=FK.default;f9.MissingRefError=l7.default;L1.default=f9;function c7($,W,Q,X="error"){for(let G in $){let J=G;if(J in W)this.logger[X](`${Q}: option ${G}. ${$[J]}`)}}function m7($){return $=(0,L4.normalizeId)($),this.schemas[$]||this.refs[$]}function VK(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let W in $)this.addSchema($[W],W)}function jK(){for(let $ in this.opts.formats){let W=this.opts.formats[$];if(W)this.addFormat($,W)}}function MK($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let W in $){let Q=$[W];if(!Q.keyword)Q.keyword=W;this.addKeyword(Q)}}function qK(){let $={...this.opts};for(let W of AK)delete $[W];return $}var IK={log(){},warn(){},error(){}};function NK($){if($===!1)return IK;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var EK=/^[a-z_$][a-z0-9_$:-]*$/i;function TK($,W){let{RULES:Q}=this;if((0,DW.eachItem)($,(X)=>{if(Q.keywords[X])throw Error(`Keyword ${X} is already defined`);if(!EK.test(X))throw Error(`Keyword ${X} has invalid name`)}),!W)return;if(W.$data&&!(("code"in W)||("validate"in W)))throw Error('$data keyword must have "code" or "validate" function')}function zW($,W,Q){var X;let G=W===null||W===void 0?void 0:W.post;if(Q&&G)throw Error('keyword with "post" flag cannot have "type"');let{RULES:J}=this,w=G?J.post:J.rules.find(({type:b})=>b===Q);if(!w)w={type:Q,rules:[]},J.rules.push(w);if(J.keywords[$]=!0,!W)return;let Y={keyword:$,definition:{...W,type:(0,y9.getJSONTypes)(W.type),schemaType:(0,y9.getJSONTypes)(W.schemaType)}};if(W.before)RK.call(this,w,Y,W.before);else w.rules.push(Y);J.all[$]=Y,(X=W.implements)===null||X===void 0||X.forEach((b)=>this.addKeyword(b))}function RK($,W,Q){let X=$.rules.findIndex((G)=>G.keyword===Q);if(X>=0)$.rules.splice(X,0,W);else $.rules.push(W),this.logger.warn(`rule ${Q} is not defined`)}function SK($){let{metaSchema:W}=$;if(W===void 0)return;if($.$data&&this.opts.$data)W=p7(W);$.validateSchema=this.compile(W,!0)}var CK={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function p7($){return{anyOf:[$,CK]}}});var d7=N((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var _K={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};n7.default=_K});var e7=N((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});s7.callRef=s7.getValidate=void 0;var hK=D4(),o7=m0(),T0=g(),B6=F1(),t7=k9(),u9=t(),yK={keyword:"$ref",schemaType:"string",code($){let{gen:W,schema:Q,it:X}=$,{baseId:G,schemaEnv:J,validateName:w,opts:Y,self:b}=X,{root:H}=J;if((Q==="#"||Q==="#/")&&G===H.baseId)return F();let z=t7.resolveRef.call(b,H,G,Q);if(z===void 0)throw new hK.default(X.opts.uriResolver,G,Q);if(z instanceof t7.SchemaEnv)return U(z);return B(z);function F(){if(J===H)return c9($,w,J,J.$async);let K=W.scopeValue("root",{ref:H});return c9($,T0._`${K}.validate`,H,H.$async)}function U(K){let P=r7($,K);c9($,P,K,K.$async)}function B(K){let P=W.scopeValue("schema",Y.code.source===!0?{ref:K,code:(0,T0.stringify)(K)}:{ref:K}),q=W.name("valid"),M=$.subschema({schema:K,dataTypes:[],schemaPath:T0.nil,topSchemaRef:P,errSchemaPath:Q},q);$.mergeEvaluated(M),$.ok(q)}}};function r7($,W){let{gen:Q}=$;return W.validate?Q.scopeValue("validate",{ref:W.validate}):T0._`${Q.scopeValue("wrapper",{ref:W})}.validate`}s7.getValidate=r7;function c9($,W,Q,X){let{gen:G,it:J}=$,{allErrors:w,schemaEnv:Y,opts:b}=J,H=b.passContext?B6.default.this:T0.nil;if(X)z();else F();function z(){if(!Y.$async)throw Error("async schema referenced by sync schema");let K=G.let("valid");G.try(()=>{if(G.code(T0._`await ${(0,o7.callValidateCode)($,W,H)}`),B(W),!w)G.assign(K,!0)},(P)=>{if(G.if(T0._`!(${P} instanceof ${J.ValidationError})`,()=>G.throw(P)),U(P),!w)G.assign(K,!1)}),$.ok(K)}function F(){$.result((0,o7.callValidateCode)($,W,H),()=>B(W),()=>U(W))}function U(K){let P=T0._`${K}.errors`;G.assign(B6.default.vErrors,T0._`${B6.default.vErrors} === null ? ${P} : ${B6.default.vErrors}.concat(${P})`),G.assign(B6.default.errors,T0._`${B6.default.vErrors}.length`)}function B(K){var P;if(!J.opts.unevaluated)return;let q=(P=Q===null||Q===void 0?void 0:Q.validate)===null||P===void 0?void 0:P.evaluated;if(J.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)J.props=u9.mergeEvaluated.props(G,q.props,J.props)}else{let M=G.var("props",T0._`${K}.evaluated.props`);J.props=u9.mergeEvaluated.props(G,M,J.props,T0.Name)}if(J.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)J.items=u9.mergeEvaluated.items(G,q.items,J.items)}else{let M=G.var("items",T0._`${K}.evaluated.items`);J.items=u9.mergeEvaluated.items(G,M,J.items,T0.Name)}}}s7.callRef=c9;s7.default=yK});var W5=N(($5)=>{Object.defineProperty($5,"__esModule",{value:!0});var cK=d7(),mK=e7(),lK=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cK.default,mK.default];$5.default=lK});var X5=N((Q5)=>{Object.defineProperty(Q5,"__esModule",{value:!0});var m9=g(),x1=m9.operators,l9={maximum:{okStr:"<=",ok:x1.LTE,fail:x1.GT},minimum:{okStr:">=",ok:x1.GTE,fail:x1.LT},exclusiveMaximum:{okStr:"<",ok:x1.LT,fail:x1.GTE},exclusiveMinimum:{okStr:">",ok:x1.GT,fail:x1.LTE}},pK={message:({keyword:$,schemaCode:W})=>m9.str`must be ${l9[$].okStr} ${W}`,params:({keyword:$,schemaCode:W})=>m9._`{comparison: ${l9[$].okStr}, limit: ${W}}`},iK={keyword:Object.keys(l9),type:"number",schemaType:"number",$data:!0,error:pK,code($){let{keyword:W,data:Q,schemaCode:X}=$;$.fail$data(m9._`${Q} ${l9[W].fail} ${X} || isNaN(${Q})`)}};Q5.default=iK});var J5=N((G5)=>{Object.defineProperty(G5,"__esModule",{value:!0});var A4=g(),dK={message:({schemaCode:$})=>A4.str`must be multiple of ${$}`,params:({schemaCode:$})=>A4._`{multipleOf: ${$}}`},oK={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:dK,code($){let{gen:W,data:Q,schemaCode:X,it:G}=$,J=G.opts.multipleOfPrecision,w=W.let("res"),Y=J?A4._`Math.abs(Math.round(${w}) - ${w}) > 1e-${J}`:A4._`${w} !== parseInt(${w})`;$.fail$data(A4._`(${X} === 0 || (${w} = ${Q}/${X}, ${Y}))`)}};G5.default=oK});var b5=N((Y5)=>{Object.defineProperty(Y5,"__esModule",{value:!0});function w5($){let W=$.length,Q=0,X=0,G;while(X<W)if(Q++,G=$.charCodeAt(X++),G>=55296&&G<=56319&&X<W){if(G=$.charCodeAt(X),(G&64512)===56320)X++}return Q}Y5.default=w5;w5.code='require("ajv/dist/runtime/ucs2length").default'});var z5=N((H5)=>{Object.defineProperty(H5,"__esModule",{value:!0});var i1=g(),sK=t(),aK=b5(),eK={message({keyword:$,schemaCode:W}){let Q=$==="maxLength"?"more":"fewer";return i1.str`must NOT have ${Q} than ${W} characters`},params:({schemaCode:$})=>i1._`{limit: ${$}}`},$Z={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eK,code($){let{keyword:W,data:Q,schemaCode:X,it:G}=$,J=W==="maxLength"?i1.operators.GT:i1.operators.LT,w=G.opts.unicode===!1?i1._`${Q}.length`:i1._`${(0,sK.useFunc)($.gen,aK.default)}(${Q})`;$.fail$data(i1._`${w} ${J} ${X}`)}};H5.default=$Z});var F5=N((D5)=>{Object.defineProperty(D5,"__esModule",{value:!0});var QZ=m0(),g9=g(),XZ={message:({schemaCode:$})=>g9.str`must match pattern "${$}"`,params:({schemaCode:$})=>g9._`{pattern: ${$}}`},GZ={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XZ,code($){let{data:W,$data:Q,schema:X,schemaCode:G,it:J}=$,w=J.opts.unicodeRegExp?"u":"",Y=Q?g9._`(new RegExp(${G}, ${w}))`:(0,QZ.usePattern)($,X);$.fail$data(g9._`!${Y}.test(${W})`)}};D5.default=GZ});var B5=N((U5)=>{Object.defineProperty(U5,"__esModule",{value:!0});var O4=g(),wZ={message({keyword:$,schemaCode:W}){let Q=$==="maxProperties"?"more":"fewer";return O4.str`must NOT have ${Q} than ${W} properties`},params:({schemaCode:$})=>O4._`{limit: ${$}}`},YZ={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:wZ,code($){let{keyword:W,data:Q,schemaCode:X}=$,G=W==="maxProperties"?O4.operators.GT:O4.operators.LT;$.fail$data(O4._`Object.keys(${Q}).length ${G} ${X}`)}};U5.default=YZ});var A5=N((L5)=>{Object.defineProperty(L5,"__esModule",{value:!0});var K4=m0(),Z4=g(),HZ=t(),zZ={message:({params:{missingProperty:$}})=>Z4.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>Z4._`{missingProperty: ${$}}`},DZ={keyword:"required",type:"object",schemaType:"array",$data:!0,error:zZ,code($){let{gen:W,schema:Q,schemaCode:X,data:G,$data:J,it:w}=$,{opts:Y}=w;if(!J&&Q.length===0)return;let b=Q.length>=Y.loopRequired;if(w.allErrors)H();else z();if(Y.strictRequired){let B=$.parentSchema.properties,{definedProperties:K}=$.it;for(let P of Q)if((B===null||B===void 0?void 0:B[P])===void 0&&!K.has(P)){let q=w.schemaEnv.baseId+w.errSchemaPath,M=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,HZ.checkStrictMode)(w,M,w.opts.strictRequired)}}function H(){if(b||J)$.block$data(Z4.nil,F);else for(let B of Q)(0,K4.checkReportMissingProp)($,B)}function z(){let B=W.let("missing");if(b||J){let K=W.let("valid",!0);$.block$data(K,()=>U(B,K)),$.ok(K)}else W.if((0,K4.checkMissingProp)($,Q,B)),(0,K4.reportMissingProp)($,B),W.else()}function F(){W.forOf("prop",X,(B)=>{$.setParams({missingProperty:B}),W.if((0,K4.noPropertyInData)(W,G,B,Y.ownProperties),()=>$.error())})}function U(B,K){$.setParams({missingProperty:B}),W.forOf(B,X,()=>{W.assign(K,(0,K4.propertyInData)(W,G,B,Y.ownProperties)),W.if((0,Z4.not)(K),()=>{$.error(),W.break()})},Z4.nil)}}};L5.default=DZ});var K5=N((O5)=>{Object.defineProperty(O5,"__esModule",{value:!0});var P4=g(),UZ={message({keyword:$,schemaCode:W}){let Q=$==="maxItems"?"more":"fewer";return P4.str`must NOT have ${Q} than ${W} items`},params:({schemaCode:$})=>P4._`{limit: ${$}}`},BZ={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UZ,code($){let{keyword:W,data:Q,schemaCode:X}=$,G=W==="maxItems"?P4.operators.GT:P4.operators.LT;$.fail$data(P4._`${Q}.length ${G} ${X}`)}};O5.default=BZ});var p9=N((P5)=>{Object.defineProperty(P5,"__esModule",{value:!0});var Z5=r8();Z5.code='require("ajv/dist/runtime/equal").default';P5.default=Z5});var j5=N((V5)=>{Object.defineProperty(V5,"__esModule",{value:!0});var FW=w4(),P0=g(),OZ=t(),KZ=p9(),ZZ={message:({params:{i:$,j:W}})=>P0.str`must NOT have duplicate items (items ## ${W} and ${$} are identical)`,params:({params:{i:$,j:W}})=>P0._`{i: ${$}, j: ${W}}`},PZ={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ZZ,code($){let{gen:W,data:Q,$data:X,schema:G,parentSchema:J,schemaCode:w,it:Y}=$;if(!X&&!G)return;let b=W.let("valid"),H=J.items?(0,FW.getSchemaTypes)(J.items):[];$.block$data(b,z,P0._`${w} === false`),$.ok(b);function z(){let K=W.let("i",P0._`${Q}.length`),P=W.let("j");$.setParams({i:K,j:P}),W.assign(b,!0),W.if(P0._`${K} > 1`,()=>(F()?U:B)(K,P))}function F(){return H.length>0&&!H.some((K)=>K==="object"||K==="array")}function U(K,P){let q=W.name("item"),M=(0,FW.checkDataTypes)(H,q,Y.opts.strictNumbers,FW.DataType.Wrong),S=W.const("indices",P0._`{}`);W.for(P0._`;${K}--;`,()=>{if(W.let(q,P0._`${Q}[${K}]`),W.if(M,P0._`continue`),H.length>1)W.if(P0._`typeof ${q} == "string"`,P0._`${q} += "_"`);W.if(P0._`typeof ${S}[${q}] == "number"`,()=>{W.assign(P,P0._`${S}[${q}]`),$.error(),W.assign(b,!1).break()}).code(P0._`${S}[${q}] = ${K}`)})}function B(K,P){let q=(0,OZ.useFunc)(W,KZ.default),M=W.name("outer");W.label(M).for(P0._`;${K}--;`,()=>W.for(P0._`${P} = ${K}; ${P}--;`,()=>W.if(P0._`${q}(${Q}[${K}], ${Q}[${P}])`,()=>{$.error(),W.assign(b,!1).break(M)})))}}};V5.default=PZ});var q5=N((M5)=>{Object.defineProperty(M5,"__esModule",{value:!0});var UW=g(),jZ=t(),MZ=p9(),qZ={message:"must be equal to constant",params:({schemaCode:$})=>UW._`{allowedValue: ${$}}`},IZ={keyword:"const",$data:!0,error:qZ,code($){let{gen:W,data:Q,$data:X,schemaCode:G,schema:J}=$;if(X||J&&typeof J=="object")$.fail$data(UW._`!${(0,jZ.useFunc)(W,MZ.default)}(${Q}, ${G})`);else $.fail(UW._`${J} !== ${Q}`)}};M5.default=IZ});var N5=N((I5)=>{Object.defineProperty(I5,"__esModule",{value:!0});var V4=g(),EZ=t(),TZ=p9(),RZ={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>V4._`{allowedValues: ${$}}`},SZ={keyword:"enum",schemaType:"array",$data:!0,error:RZ,code($){let{gen:W,data:Q,$data:X,schema:G,schemaCode:J,it:w}=$;if(!X&&G.length===0)throw Error("enum must have non-empty array");let Y=G.length>=w.opts.loopEnum,b,H=()=>b!==null&&b!==void 0?b:b=(0,EZ.useFunc)(W,TZ.default),z;if(Y||X)z=W.let("valid"),$.block$data(z,F);else{if(!Array.isArray(G))throw Error("ajv implementation error");let B=W.const("vSchema",J);z=(0,V4.or)(...G.map((K,P)=>U(B,P)))}$.pass(z);function F(){W.assign(z,!1),W.forOf("v",J,(B)=>W.if(V4._`${H()}(${Q}, ${B})`,()=>W.assign(z,!0).break()))}function U(B,K){let P=G[K];return typeof P==="object"&&P!==null?V4._`${H()}(${Q}, ${B}[${K}])`:V4._`${Q} === ${P}`}}};I5.default=SZ});var T5=N((E5)=>{Object.defineProperty(E5,"__esModule",{value:!0});var kZ=X5(),vZ=J5(),_Z=z5(),xZ=F5(),hZ=B5(),yZ=A5(),fZ=K5(),uZ=j5(),cZ=q5(),mZ=N5(),lZ=[kZ.default,vZ.default,_Z.default,xZ.default,hZ.default,yZ.default,fZ.default,uZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},cZ.default,mZ.default];E5.default=lZ});var LW=N((S5)=>{Object.defineProperty(S5,"__esModule",{value:!0});S5.validateAdditionalItems=void 0;var n1=g(),BW=t(),pZ={message:({params:{len:$}})=>n1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>n1._`{limit: ${$}}`},iZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:pZ,code($){let{parentSchema:W,it:Q}=$,{items:X}=W;if(!Array.isArray(X)){(0,BW.checkStrictMode)(Q,'"additionalItems" is ignored when "items" is not an array of schemas');return}R5($,X)}};function R5($,W){let{gen:Q,schema:X,data:G,keyword:J,it:w}=$;w.items=!0;let Y=Q.const("len",n1._`${G}.length`);if(X===!1)$.setParams({len:W.length}),$.pass(n1._`${Y} <= ${W.length}`);else if(typeof X=="object"&&!(0,BW.alwaysValidSchema)(w,X)){let H=Q.var("valid",n1._`${Y} <= ${W.length}`);Q.if((0,n1.not)(H),()=>b(H)),$.ok(H)}function b(H){Q.forRange("i",W.length,Y,(z)=>{if($.subschema({keyword:J,dataProp:z,dataPropType:BW.Type.Num},H),!w.allErrors)Q.if((0,n1.not)(H),()=>Q.break())})}}S5.validateAdditionalItems=R5;S5.default=iZ});var AW=N((_5)=>{Object.defineProperty(_5,"__esModule",{value:!0});_5.validateTuple=void 0;var k5=g(),i9=t(),dZ=m0(),oZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:W,it:Q}=$;if(Array.isArray(W))return v5($,"additionalItems",W);if(Q.items=!0,(0,i9.alwaysValidSchema)(Q,W))return;$.ok((0,dZ.validateArray)($))}};function v5($,W,Q=$.schema){let{gen:X,parentSchema:G,data:J,keyword:w,it:Y}=$;if(z(G),Y.opts.unevaluated&&Q.length&&Y.items!==!0)Y.items=i9.mergeEvaluated.items(X,Q.length,Y.items);let b=X.name("valid"),H=X.const("len",k5._`${J}.length`);Q.forEach((F,U)=>{if((0,i9.alwaysValidSchema)(Y,F))return;X.if(k5._`${H} > ${U}`,()=>$.subschema({keyword:w,schemaProp:U,dataProp:U},b)),$.ok(b)});function z(F){let{opts:U,errSchemaPath:B}=Y,K=Q.length,P=K===F.minItems&&(K===F.maxItems||F[W]===!1);if(U.strictTuples&&!P){let q=`"${w}" is ${K}-tuple, but minItems or maxItems/${W} are not specified or different at path "${B}"`;(0,i9.checkStrictMode)(Y,q,U.strictTuples)}}}_5.validateTuple=v5;_5.default=oZ});var y5=N((h5)=>{Object.defineProperty(h5,"__esModule",{value:!0});var rZ=AW(),sZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,rZ.validateTuple)($,"items")};h5.default=sZ});var c5=N((u5)=>{Object.defineProperty(u5,"__esModule",{value:!0});var f5=g(),eZ=t(),$P=m0(),WP=LW(),QP={message:({params:{len:$}})=>f5.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>f5._`{limit: ${$}}`},XP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:QP,code($){let{schema:W,parentSchema:Q,it:X}=$,{prefixItems:G}=Q;if(X.items=!0,(0,eZ.alwaysValidSchema)(X,W))return;if(G)(0,WP.validateAdditionalItems)($,G);else $.ok((0,$P.validateArray)($))}};u5.default=XP});var l5=N((m5)=>{Object.defineProperty(m5,"__esModule",{value:!0});var l0=g(),n9=t(),JP={message:({params:{min:$,max:W}})=>W===void 0?l0.str`must contain at least ${$} valid item(s)`:l0.str`must contain at least ${$} and no more than ${W} valid item(s)`,params:({params:{min:$,max:W}})=>W===void 0?l0._`{minContains: ${$}}`:l0._`{minContains: ${$}, maxContains: ${W}}`},wP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:JP,code($){let{gen:W,schema:Q,parentSchema:X,data:G,it:J}=$,w,Y,{minContains:b,maxContains:H}=X;if(J.opts.next)w=b===void 0?1:b,Y=H;else w=1;let z=W.const("len",l0._`${G}.length`);if($.setParams({min:w,max:Y}),Y===void 0&&w===0){(0,n9.checkStrictMode)(J,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&w>Y){(0,n9.checkStrictMode)(J,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,n9.alwaysValidSchema)(J,Q)){let P=l0._`${z} >= ${w}`;if(Y!==void 0)P=l0._`${P} && ${z} <= ${Y}`;$.pass(P);return}J.items=!0;let F=W.name("valid");if(Y===void 0&&w===1)B(F,()=>W.if(F,()=>W.break()));else if(w===0){if(W.let(F,!0),Y!==void 0)W.if(l0._`${G}.length > 0`,U)}else W.let(F,!1),U();$.result(F,()=>$.reset());function U(){let P=W.name("_valid"),q=W.let("count",0);B(P,()=>W.if(P,()=>K(q)))}function B(P,q){W.forRange("i",0,z,(M)=>{$.subschema({keyword:"contains",dataProp:M,dataPropType:n9.Type.Num,compositeRule:!0},P),q()})}function K(P){if(W.code(l0._`${P}++`),Y===void 0)W.if(l0._`${P} >= ${w}`,()=>W.assign(F,!0).break());else if(W.if(l0._`${P} > ${Y}`,()=>W.assign(F,!1).break()),w===1)W.assign(F,!0);else W.if(l0._`${P} >= ${w}`,()=>W.assign(F,!0))}}};m5.default=wP});var o5=N((i5)=>{Object.defineProperty(i5,"__esModule",{value:!0});i5.validateSchemaDeps=i5.validatePropertyDeps=i5.error=void 0;var OW=g(),bP=t(),j4=m0();i5.error={message:({params:{property:$,depsCount:W,deps:Q}})=>{let X=W===1?"property":"properties";return OW.str`must have ${X} ${Q} when property ${$} is present`},params:({params:{property:$,depsCount:W,deps:Q,missingProperty:X}})=>OW._`{property: ${$},
|
|
7
|
-
missingProperty: ${
|
|
8
|
-
depsCount: ${
|
|
9
|
-
deps: ${Q}}`};var HP={keyword:"dependencies",type:"object",schemaType:"object",error:i5.error,code($){let[W,Q]=zP($);g5($,W),p5($,Q)}};function zP({schema:$}){let W={},Q={};for(let X in $){if(X==="__proto__")continue;let G=Array.isArray($[X])?W:Q;G[X]=$[X]}return[W,Q]}function g5($,W=$.schema){let{gen:Q,data:X,it:G}=$;if(Object.keys(W).length===0)return;let J=Q.let("missing");for(let w in W){let Y=W[w];if(Y.length===0)continue;let b=(0,j4.propertyInData)(Q,X,w,G.opts.ownProperties);if($.setParams({property:w,depsCount:Y.length,deps:Y.join(", ")}),G.allErrors)Q.if(b,()=>{for(let H of Y)(0,j4.checkReportMissingProp)($,H)});else Q.if(OW._`${b} && (${(0,j4.checkMissingProp)($,Y,J)})`),(0,j4.reportMissingProp)($,J),Q.else()}}i5.validatePropertyDeps=g5;function p5($,W=$.schema){let{gen:Q,data:X,keyword:G,it:J}=$,w=Q.name("valid");for(let Y in W){if((0,bP.alwaysValidSchema)(J,W[Y]))continue;Q.if((0,j4.propertyInData)(Q,X,Y,J.opts.ownProperties),()=>{let b=$.subschema({keyword:G,schemaProp:Y},w);$.mergeValidEvaluated(b,w)},()=>Q.var(w,!0)),$.ok(w)}}i5.validateSchemaDeps=p5;i5.default=HP});var s5=N((r5)=>{Object.defineProperty(r5,"__esModule",{value:!0});var t5=g(),UP=t(),BP={message:"property name must be valid",params:({params:$})=>t5._`{propertyName: ${$.propertyName}}`},LP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:BP,code($){let{gen:W,schema:Q,data:X,it:G}=$;if((0,UP.alwaysValidSchema)(G,Q))return;let J=W.name("valid");W.forIn("key",X,(w)=>{$.setParams({propertyName:w}),$.subschema({keyword:"propertyNames",data:w,dataTypes:["string"],propertyName:w,compositeRule:!0},J),W.if((0,t5.not)(J),()=>{if($.error(!0),!G.allErrors)W.break()})}),$.ok(J)}};r5.default=LP});var KW=N((a5)=>{Object.defineProperty(a5,"__esModule",{value:!0});var d9=m0(),s0=g(),OP=F1(),o9=t(),KP={message:"must NOT have additional properties",params:({params:$})=>s0._`{additionalProperty: ${$.additionalProperty}}`},ZP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:KP,code($){let{gen:W,schema:Q,parentSchema:X,data:G,errsCount:J,it:w}=$;if(!J)throw Error("ajv implementation error");let{allErrors:Y,opts:b}=w;if(w.props=!0,b.removeAdditional!=="all"&&(0,o9.alwaysValidSchema)(w,Q))return;let H=(0,d9.allSchemaProperties)(X.properties),z=(0,d9.allSchemaProperties)(X.patternProperties);F(),$.ok(s0._`${J} === ${OP.default.errors}`);function F(){W.forIn("key",G,(q)=>{if(!H.length&&!z.length)K(q);else W.if(U(q),()=>K(q))})}function U(q){let M;if(H.length>8){let S=(0,o9.schemaRefOrVal)(w,X.properties,"properties");M=(0,d9.isOwnProperty)(W,S,q)}else if(H.length)M=(0,s0.or)(...H.map((S)=>s0._`${q} === ${S}`));else M=s0.nil;if(z.length)M=(0,s0.or)(M,...z.map((S)=>s0._`${(0,d9.usePattern)($,S)}.test(${q})`));return(0,s0.not)(M)}function B(q){W.code(s0._`delete ${G}[${q}]`)}function K(q){if(b.removeAdditional==="all"||b.removeAdditional&&Q===!1){B(q);return}if(Q===!1){if($.setParams({additionalProperty:q}),$.error(),!Y)W.break();return}if(typeof Q=="object"&&!(0,o9.alwaysValidSchema)(w,Q)){let M=W.name("valid");if(b.removeAdditional==="failing")P(q,M,!1),W.if((0,s0.not)(M),()=>{$.reset(),B(q)});else if(P(q,M),!Y)W.if((0,s0.not)(M),()=>W.break())}}function P(q,M,S){let C={keyword:"additionalProperties",dataProp:q,dataPropType:o9.Type.Str};if(S===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(C,M)}}};a5.default=ZP});var Qb=N((Wb)=>{Object.defineProperty(Wb,"__esModule",{value:!0});var VP=z4(),e5=m0(),ZW=t(),$b=KW(),jP={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:W,schema:Q,parentSchema:X,data:G,it:J}=$;if(J.opts.removeAdditional==="all"&&X.additionalProperties===void 0)$b.default.code(new VP.KeywordCxt(J,$b.default,"additionalProperties"));let w=(0,e5.allSchemaProperties)(Q);for(let F of w)J.definedProperties.add(F);if(J.opts.unevaluated&&w.length&&J.props!==!0)J.props=ZW.mergeEvaluated.props(W,(0,ZW.toHash)(w),J.props);let Y=w.filter((F)=>!(0,ZW.alwaysValidSchema)(J,Q[F]));if(Y.length===0)return;let b=W.name("valid");for(let F of Y){if(H(F))z(F);else{if(W.if((0,e5.propertyInData)(W,G,F,J.opts.ownProperties)),z(F),!J.allErrors)W.else().var(b,!0);W.endIf()}$.it.definedProperties.add(F),$.ok(b)}function H(F){return J.opts.useDefaults&&!J.compositeRule&&Q[F].default!==void 0}function z(F){$.subschema({keyword:"properties",schemaProp:F,dataProp:F},b)}}};Wb.default=jP});var Yb=N((wb)=>{Object.defineProperty(wb,"__esModule",{value:!0});var Xb=m0(),t9=g(),Gb=t(),Jb=t(),qP={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:W,schema:Q,data:X,parentSchema:G,it:J}=$,{opts:w}=J,Y=(0,Xb.allSchemaProperties)(Q),b=Y.filter((P)=>(0,Gb.alwaysValidSchema)(J,Q[P]));if(Y.length===0||b.length===Y.length&&(!J.opts.unevaluated||J.props===!0))return;let H=w.strictSchema&&!w.allowMatchingProperties&&G.properties,z=W.name("valid");if(J.props!==!0&&!(J.props instanceof t9.Name))J.props=(0,Jb.evaluatedPropsToName)(W,J.props);let{props:F}=J;U();function U(){for(let P of Y){if(H)B(P);if(J.allErrors)K(P);else W.var(z,!0),K(P),W.if(z)}}function B(P){for(let q in H)if(new RegExp(P).test(q))(0,Gb.checkStrictMode)(J,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function K(P){W.forIn("key",X,(q)=>{W.if(t9._`${(0,Xb.usePattern)($,P)}.test(${q})`,()=>{let M=b.includes(P);if(!M)$.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:Jb.Type.Str},z);if(J.opts.unevaluated&&F!==!0)W.assign(t9._`${F}[${q}]`,!0);else if(!M&&!J.allErrors)W.if((0,t9.not)(z),()=>W.break())})})}}};wb.default=qP});var Hb=N((bb)=>{Object.defineProperty(bb,"__esModule",{value:!0});var NP=t(),EP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:W,schema:Q,it:X}=$;if((0,NP.alwaysValidSchema)(X,Q)){$.fail();return}let G=W.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},G),$.failResult(G,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};bb.default=EP});var Db=N((zb)=>{Object.defineProperty(zb,"__esModule",{value:!0});var RP=m0(),SP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:RP.validateUnion,error:{message:"must match a schema in anyOf"}};zb.default=SP});var Ub=N((Fb)=>{Object.defineProperty(Fb,"__esModule",{value:!0});var r9=g(),kP=t(),vP={message:"must match exactly one schema in oneOf",params:({params:$})=>r9._`{passingSchemas: ${$.passing}}`},_P={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:vP,code($){let{gen:W,schema:Q,parentSchema:X,it:G}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(G.opts.discriminator&&X.discriminator)return;let J=Q,w=W.let("valid",!1),Y=W.let("passing",null),b=W.name("_valid");$.setParams({passing:Y}),W.block(H),$.result(w,()=>$.reset(),()=>$.error(!0));function H(){J.forEach((z,F)=>{let U;if((0,kP.alwaysValidSchema)(G,z))W.var(b,!0);else U=$.subschema({keyword:"oneOf",schemaProp:F,compositeRule:!0},b);if(F>0)W.if(r9._`${b} && ${w}`).assign(w,!1).assign(Y,r9._`[${Y}, ${F}]`).else();W.if(b,()=>{if(W.assign(w,!0),W.assign(Y,F),U)$.mergeEvaluated(U,r9.Name)})})}}};Fb.default=_P});var Lb=N((Bb)=>{Object.defineProperty(Bb,"__esModule",{value:!0});var hP=t(),yP={keyword:"allOf",schemaType:"array",code($){let{gen:W,schema:Q,it:X}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");let G=W.name("valid");Q.forEach((J,w)=>{if((0,hP.alwaysValidSchema)(X,J))return;let Y=$.subschema({keyword:"allOf",schemaProp:w},G);$.ok(G),$.mergeEvaluated(Y)})}};Bb.default=yP});var Zb=N((Kb)=>{Object.defineProperty(Kb,"__esModule",{value:!0});var s9=g(),Ob=t(),uP={message:({params:$})=>s9.str`must match "${$.ifClause}" schema`,params:({params:$})=>s9._`{failingKeyword: ${$.ifClause}}`},cP={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uP,code($){let{gen:W,parentSchema:Q,it:X}=$;if(Q.then===void 0&&Q.else===void 0)(0,Ob.checkStrictMode)(X,'"if" without "then" and "else" is ignored');let G=Ab(X,"then"),J=Ab(X,"else");if(!G&&!J)return;let w=W.let("valid",!0),Y=W.name("_valid");if(b(),$.reset(),G&&J){let z=W.let("ifClause");$.setParams({ifClause:z}),W.if(Y,H("then",z),H("else",z))}else if(G)W.if(Y,H("then"));else W.if((0,s9.not)(Y),H("else"));$.pass(w,()=>$.error(!0));function b(){let z=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);$.mergeEvaluated(z)}function H(z,F){return()=>{let U=$.subschema({keyword:z},Y);if(W.assign(w,Y),$.mergeValidEvaluated(U,w),F)W.assign(F,s9._`${z}`);else $.setParams({ifClause:z})}}}};function Ab($,W){let Q=$.schema[W];return Q!==void 0&&!(0,Ob.alwaysValidSchema)($,Q)}Kb.default=cP});var Vb=N((Pb)=>{Object.defineProperty(Pb,"__esModule",{value:!0});var lP=t(),gP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:W,it:Q}){if(W.if===void 0)(0,lP.checkStrictMode)(Q,`"${$}" without "if" is ignored`)}};Pb.default=gP});var Mb=N((jb)=>{Object.defineProperty(jb,"__esModule",{value:!0});var iP=LW(),nP=y5(),dP=AW(),oP=c5(),tP=l5(),rP=o5(),sP=s5(),aP=KW(),eP=Qb(),$V=Yb(),WV=Hb(),QV=Db(),XV=Ub(),GV=Lb(),JV=Zb(),wV=Vb();function YV($=!1){let W=[WV.default,QV.default,XV.default,GV.default,JV.default,wV.default,sP.default,aP.default,rP.default,eP.default,$V.default];if($)W.push(nP.default,oP.default);else W.push(iP.default,dP.default);return W.push(tP.default),W}jb.default=YV});var Ib=N((qb)=>{Object.defineProperty(qb,"__esModule",{value:!0});var z0=g(),HV={message:({schemaCode:$})=>z0.str`must match format "${$}"`,params:({schemaCode:$})=>z0._`{format: ${$}}`},zV={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:HV,code($,W){let{gen:Q,data:X,$data:G,schema:J,schemaCode:w,it:Y}=$,{opts:b,errSchemaPath:H,schemaEnv:z,self:F}=Y;if(!b.validateFormats)return;if(G)U();else B();function U(){let K=Q.scopeValue("formats",{ref:F.formats,code:b.code.formats}),P=Q.const("fDef",z0._`${K}[${w}]`),q=Q.let("fType"),M=Q.let("format");Q.if(z0._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>Q.assign(q,z0._`${P}.type || "string"`).assign(M,z0._`${P}.validate`),()=>Q.assign(q,z0._`"string"`).assign(M,P)),$.fail$data((0,z0.or)(S(),C()));function S(){if(b.strictSchema===!1)return z0.nil;return z0._`${w} && !${M}`}function C(){let v=z.$async?z0._`(${P}.async ? await ${M}(${X}) : ${M}(${X}))`:z0._`${M}(${X})`,k=z0._`(typeof ${M} == "function" ? ${v} : ${M}.test(${X}))`;return z0._`${M} && ${M} !== true && ${q} === ${W} && !${k}`}}function B(){let K=F.formats[J];if(!K){S();return}if(K===!0)return;let[P,q,M]=C(K);if(P===W)$.pass(v());function S(){if(b.strictSchema===!1){F.logger.warn(k());return}throw Error(k());function k(){return`unknown format "${J}" ignored in schema at path "${H}"`}}function C(k){let S0=k instanceof RegExp?(0,z0.regexpCode)(k):b.code.formats?z0._`${b.code.formats}${(0,z0.getProperty)(J)}`:void 0,g0=Q.scopeValue("formats",{key:J,ref:k,code:S0});if(typeof k=="object"&&!(k instanceof RegExp))return[k.type||"string",k.validate,z0._`${g0}.validate`];return["string",k,g0]}function v(){if(typeof K=="object"&&!(K instanceof RegExp)&&K.async){if(!z.$async)throw Error("async format in sync schema");return z0._`await ${M}(${X})`}return typeof q=="function"?z0._`${M}(${X})`:z0._`${M}.test(${X})`}}}};qb.default=zV});var Eb=N((Nb)=>{Object.defineProperty(Nb,"__esModule",{value:!0});var FV=Ib(),UV=[FV.default];Nb.default=UV});var Sb=N((Tb)=>{Object.defineProperty(Tb,"__esModule",{value:!0});Tb.contentVocabulary=Tb.metadataVocabulary=void 0;Tb.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Tb.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var vb=N((kb)=>{Object.defineProperty(kb,"__esModule",{value:!0});var AV=W5(),OV=T5(),KV=Mb(),ZV=Eb(),Cb=Sb(),PV=[AV.default,OV.default,(0,KV.default)(),ZV.default,Cb.metadataVocabulary,Cb.contentVocabulary];kb.default=PV});var yb=N((xb)=>{Object.defineProperty(xb,"__esModule",{value:!0});xb.DiscrError=void 0;var _b;(function($){$.Tag="tag",$.Mapping="mapping"})(_b||(xb.DiscrError=_b={}))});var cb=N((ub)=>{Object.defineProperty(ub,"__esModule",{value:!0});var L6=g(),PW=yb(),fb=k9(),jV=D4(),MV=t(),qV={message:({params:{discrError:$,tagName:W}})=>$===PW.DiscrError.Tag?`tag "${W}" must be string`:`value of tag "${W}" must be in oneOf`,params:({params:{discrError:$,tag:W,tagName:Q}})=>L6._`{error: ${$}, tag: ${Q}, tagValue: ${W}}`},IV={keyword:"discriminator",type:"object",schemaType:"object",error:qV,code($){let{gen:W,data:Q,schema:X,parentSchema:G,it:J}=$,{oneOf:w}=G;if(!J.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=X.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(X.mapping)throw Error("discriminator: mapping is not supported");if(!w)throw Error("discriminator: requires oneOf keyword");let b=W.let("valid",!1),H=W.const("tag",L6._`${Q}${(0,L6.getProperty)(Y)}`);W.if(L6._`typeof ${H} == "string"`,()=>z(),()=>$.error(!1,{discrError:PW.DiscrError.Tag,tag:H,tagName:Y})),$.ok(b);function z(){let B=U();W.if(!1);for(let K in B)W.elseIf(L6._`${H} === ${K}`),W.assign(b,F(B[K]));W.else(),$.error(!1,{discrError:PW.DiscrError.Mapping,tag:H,tagName:Y}),W.endIf()}function F(B){let K=W.name("valid"),P=$.subschema({keyword:"oneOf",schemaProp:B},K);return $.mergeEvaluated(P,L6.Name),K}function U(){var B;let K={},P=M(G),q=!0;for(let v=0;v<w.length;v++){let k=w[v];if((k===null||k===void 0?void 0:k.$ref)&&!(0,MV.schemaHasRulesButRef)(k,J.self.RULES)){let g0=k.$ref;if(k=fb.resolveRef.call(J.self,J.schemaEnv.root,J.baseId,g0),k instanceof fb.SchemaEnv)k=k.schema;if(k===void 0)throw new jV.default(J.opts.uriResolver,J.baseId,g0)}let S0=(B=k===null||k===void 0?void 0:k.properties)===null||B===void 0?void 0:B[Y];if(typeof S0!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);q=q&&(P||M(k)),S(S0,v)}if(!q)throw Error(`discriminator: "${Y}" must be required`);return K;function M({required:v}){return Array.isArray(v)&&v.includes(Y)}function S(v,k){if(v.const)C(v.const,k);else if(v.enum)for(let S0 of v.enum)C(S0,k);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function C(v,k){if(typeof v!="string"||v in K)throw Error(`discriminator: "${Y}" values must be unique strings`);K[v]=k}}}};ub.default=IV});var mb=N((mS,EV)=>{EV.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var jW=N((R0,VW)=>{Object.defineProperty(R0,"__esModule",{value:!0});R0.MissingRefError=R0.ValidationError=R0.CodeGen=R0.Name=R0.nil=R0.stringify=R0.str=R0._=R0.KeywordCxt=R0.Ajv=void 0;var TV=i7(),RV=vb(),SV=cb(),lb=mb(),CV=["/properties"],a9="http://json-schema.org/draft-07/schema";class M4 extends TV.default{_addVocabularies(){if(super._addVocabularies(),RV.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(SV.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(lb,CV):lb;this.addMetaSchema($,a9,!1),this.refs["http://json-schema.org/schema"]=a9}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a9)?a9:void 0)}}R0.Ajv=M4;VW.exports=R0=M4;VW.exports.Ajv=M4;Object.defineProperty(R0,"__esModule",{value:!0});R0.default=M4;var kV=z4();Object.defineProperty(R0,"KeywordCxt",{enumerable:!0,get:function(){return kV.KeywordCxt}});var A6=g();Object.defineProperty(R0,"_",{enumerable:!0,get:function(){return A6._}});Object.defineProperty(R0,"str",{enumerable:!0,get:function(){return A6.str}});Object.defineProperty(R0,"stringify",{enumerable:!0,get:function(){return A6.stringify}});Object.defineProperty(R0,"nil",{enumerable:!0,get:function(){return A6.nil}});Object.defineProperty(R0,"Name",{enumerable:!0,get:function(){return A6.Name}});Object.defineProperty(R0,"CodeGen",{enumerable:!0,get:function(){return A6.CodeGen}});var vV=S9();Object.defineProperty(R0,"ValidationError",{enumerable:!0,get:function(){return vV.default}});var _V=D4();Object.defineProperty(R0,"MissingRefError",{enumerable:!0,get:function(){return _V.default}})});var ab=N((rb)=>{Object.defineProperty(rb,"__esModule",{value:!0});rb.formatNames=rb.fastFormats=rb.fullFormats=void 0;function G1($,W){return{validate:$,compare:W}}rb.fullFormats={date:G1(nb,NW),time:G1(qW(!0),EW),"date-time":G1(gb(!0),ob),"iso-time":G1(qW(),db),"iso-date-time":G1(gb(),tb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lV,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:tV,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:gV,int32:{type:"number",validate:nV},int64:{type:"number",validate:dV},float:{type:"number",validate:ib},double:{type:"number",validate:ib},password:!0,binary:!0};rb.fastFormats={...rb.fullFormats,date:G1(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,NW),time:G1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,EW),"date-time":G1(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ob),"iso-time":G1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,db),"iso-date-time":G1(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,tb),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};rb.formatNames=Object.keys(rb.fullFormats);function yV($){return $%4===0&&($%100!==0||$%400===0)}var fV=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uV=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nb($){let W=fV.exec($);if(!W)return!1;let Q=+W[1],X=+W[2],G=+W[3];return X>=1&&X<=12&&G>=1&&G<=(X===2&&yV(Q)?29:uV[X])}function NW($,W){if(!($&&W))return;if($>W)return 1;if($<W)return-1;return 0}var MW=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function qW($){return function(Q){let X=MW.exec(Q);if(!X)return!1;let G=+X[1],J=+X[2],w=+X[3],Y=X[4],b=X[5]==="-"?-1:1,H=+(X[6]||0),z=+(X[7]||0);if(H>23||z>59||$&&!Y)return!1;if(G<=23&&J<=59&&w<60)return!0;let F=J-z*b,U=G-H*b-(F<0?1:0);return(U===23||U===-1)&&(F===59||F===-1)&&w<61}}function EW($,W){if(!($&&W))return;let Q=new Date("2020-01-01T"+$).valueOf(),X=new Date("2020-01-01T"+W).valueOf();if(!(Q&&X))return;return Q-X}function db($,W){if(!($&&W))return;let Q=MW.exec($),X=MW.exec(W);if(!(Q&&X))return;if($=Q[1]+Q[2]+Q[3],W=X[1]+X[2]+X[3],$>W)return 1;if($<W)return-1;return 0}var IW=/t|\s/i;function gb($){let W=qW($);return function(X){let G=X.split(IW);return G.length===2&&nb(G[0])&&W(G[1])}}function ob($,W){if(!($&&W))return;let Q=new Date($).valueOf(),X=new Date(W).valueOf();if(!(Q&&X))return;return Q-X}function tb($,W){if(!($&&W))return;let[Q,X]=$.split(IW),[G,J]=W.split(IW),w=NW(Q,G);if(w===void 0)return;return w||EW(X,J)}var cV=/\/|:/,mV=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function lV($){return cV.test($)&&mV.test($)}var pb=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function gV($){return pb.lastIndex=0,pb.test($)}var pV=-2147483648,iV=2147483647;function nV($){return Number.isInteger($)&&$<=iV&&$>=pV}function dV($){return Number.isInteger($)}function ib(){return!0}var oV=/[^\\]\\Z/;function tV($){if(oV.test($))return!1;try{return new RegExp($),!0}catch(W){return!1}}});var $H=N((eb)=>{Object.defineProperty(eb,"__esModule",{value:!0});eb.formatLimitDefinition=void 0;var sV=jW(),a0=g(),h1=a0.operators,e9={formatMaximum:{okStr:"<=",ok:h1.LTE,fail:h1.GT},formatMinimum:{okStr:">=",ok:h1.GTE,fail:h1.LT},formatExclusiveMaximum:{okStr:"<",ok:h1.LT,fail:h1.GTE},formatExclusiveMinimum:{okStr:">",ok:h1.GT,fail:h1.LTE}},aV={message:({keyword:$,schemaCode:W})=>a0.str`should be ${e9[$].okStr} ${W}`,params:({keyword:$,schemaCode:W})=>a0._`{comparison: ${e9[$].okStr}, limit: ${W}}`};eb.formatLimitDefinition={keyword:Object.keys(e9),type:"string",schemaType:"string",$data:!0,error:aV,code($){let{gen:W,data:Q,schemaCode:X,keyword:G,it:J}=$,{opts:w,self:Y}=J;if(!w.validateFormats)return;let b=new sV.KeywordCxt(J,Y.RULES.all.format.definition,"format");if(b.$data)H();else z();function H(){let U=W.scopeValue("formats",{ref:Y.formats,code:w.code.formats}),B=W.const("fmt",a0._`${U}[${b.schemaCode}]`);$.fail$data((0,a0.or)(a0._`typeof ${B} != "object"`,a0._`${B} instanceof RegExp`,a0._`typeof ${B}.compare != "function"`,F(B)))}function z(){let U=b.schema,B=Y.formats[U];if(!B||B===!0)return;if(typeof B!="object"||B instanceof RegExp||typeof B.compare!="function")throw Error(`"${G}": format "${U}" does not define "compare" function`);let K=W.scopeValue("formats",{key:U,ref:B,code:w.code.formats?a0._`${w.code.formats}${(0,a0.getProperty)(U)}`:void 0});$.fail$data(F(K))}function F(U){return a0._`${U}.compare(${Q}, ${X}) ${e9[G].fail} 0`}},dependencies:["format"]};var eV=($)=>{return $.addKeyword(eb.formatLimitDefinition),$};eb.default=eV});var GH=N((q4,XH)=>{Object.defineProperty(q4,"__esModule",{value:!0});var O6=ab(),Wj=$H(),SW=g(),WH=new SW.Name("fullFormats"),Qj=new SW.Name("fastFormats"),CW=($,W={keywords:!0})=>{if(Array.isArray(W))return QH($,W,O6.fullFormats,WH),$;let[Q,X]=W.mode==="fast"?[O6.fastFormats,Qj]:[O6.fullFormats,WH],G=W.formats||O6.formatNames;if(QH($,G,Q,X),W.keywords)(0,Wj.default)($);return $};CW.get=($,W="full")=>{let X=(W==="fast"?O6.fastFormats:O6.fullFormats)[$];if(!X)throw Error(`Unknown format "${$}"`);return X};function QH($,W,Q,X){var G,J;(G=(J=$.opts.code).formats)!==null&&G!==void 0||(J.formats=SW._`require("ajv-formats/dist/formats").${X}`);for(let w of W)$.addFormat(w,Q[w])}XH.exports=q4=CW;Object.defineProperty(q4,"__esModule",{value:!0});q4.default=CW});import{AsyncLocalStorage as Sz}from"node:async_hooks";class W1 extends Error{statusCode;rawDetails;code;context;constructor($,W,Q,X,G){super($);this.statusCode=W;this.rawDetails=Q;this.code=X;this.context=G;this.name="McpApiError"}}function Ez($){if($ instanceof W1)return{message:$.message,statusCode:$.statusCode,code:$.code,rawDetails:$.rawDetails,context:$.context};if($ instanceof Error)return{message:$.message};return{message:String($)}}function Tz($){let W=$.match(/api key is missing required scopes?:\s*(.+)$/i);if(!W?.[1])return[];return[...new Set(W[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function Rz($){let W=Ez($),Q=W.message.trim()||"Unknown error",X=Q.toLowerCase(),G=W.rawDetails?.trim()||Q;if(W.context?.title||W.context?.description||W.context?.howToFix||W.context?.docsUrl)return{title:W.context.title??(W.statusCode===409?"Request conflict":"API request failed"),description:W.context.description??Q,howToFix:W.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:W.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.code==="MCP_AUTH_REQUIRED"||X.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.statusCode===401||W.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};if(W.code==="COMPANY_CREATE_REQUIRES_PERSONAL_KEY")return{title:"Personal account key required",description:"Company creation is account-level and cannot be performed with a company/workspace-scoped API key.",howToFix:"Create or use a personal account key beginning with `seq_user_` from Account → API Keys, replace `SEQUENZY_API_KEY`, reconnect the MCP client, and retry `create_company`; alternatively, create the company in the Sequenzy dashboard. Widening the current company key or selecting another company will not fix this restriction.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};let J=Tz(Q);if(J.length>0){let w=J.map((H)=>`\`${H}\``).join(", "),Y=J.every((H)=>H.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions",b=J.includes("api_keys:manage")?' This operation manages API keys, so the missing scope cannot be granted through the API by the key that is missing it. If the active key has `account:read`, call `request_api_key_handoff` to get a dashboard link that opens the create-key form prefilled with the name and permissions you need, pass `replaceApiKeyId: "current"` when rotating, and hand the URL to the workspace owner. It creates nothing and never returns a key. If the handoff tool is also denied because `account:read` is missing, open https://sequenzy.com/dashboard directly and choose the matching API Keys page.':"";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${J.length===1?"scope":"scopes"}: ${w}.`,howToFix:`Permissions can be widened on the key you are already using - no replacement key and no client restart. Call \`get_account\` to read \`apiKeyPermissions\`, then have the key owner open \`apiKeyPermissions.manageUrl\`, edit the key identified by \`apiKeyPermissions.activeKey\`, and enable ${w}. The URL opens Account → API Keys for a \`personal\` key and workspace Settings → API Keys for a \`company\` key. If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and choose the matching API Keys page. When \`apiKeyPermissions.activeKey.type\` is \`company\` and the key holds \`api_keys:manage\`, the agent can instead call \`update_api_key\` with \`apiKeyId\` from \`apiKeyPermissions.activeKey.id\`. Personal keys cannot be changed through \`update_api_key\`. \`scopes\` and \`preset\` REPLACE the whole selection, so pass every scope in \`apiKeyPermissions.scopes\` plus ${w}, or a preset covering all of them (${Y}). Then retry the same tool call - the API reloads the key's permissions on a denied request, so the retry succeeds without reconnecting. Issuing a replacement key and swapping \`SEQUENZY_API_KEY\`, or reauthorizing a hosted OAuth connection with wider permissions, also works but is not required.${b}`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G}}if(W.statusCode===403||X.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:G};if(X.includes("no company available")||X.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.statusCode===404||X.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.statusCode===409)return{title:"Request conflict",description:"Sequenzy rejected this request because the resource changed or an operation is already in progress.",howToFix:"Refresh the resource state, choose the lifecycle action allowed by its current status, and retry at most once.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.statusCode===429||X.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.code==="NETWORK_ERROR"||X.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.includes("unknown tool")||X.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(X.includes("is required")||X.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};if(W.statusCode&&W.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:G}}function V1($){let W=Rz($);return[`Sequenzy MCP error: ${W.title}`,`Description: ${W.description}`,`How to fix: ${W.howToFix}`,`Docs: ${W.docsUrl}`,`Details: ${W.details}`].join(`
|
|
10
|
-
`)}var Cz="https://api.sequenzy.com",kz=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),S6=new Sz,CQ=!1;function kQ(){CQ=!0}function k4(){return CQ}var vQ=null;function j1(){let $=S6.getStore();if($)return $.selectedCompanyId??null;return vQ}function v4($){let W=S6.getStore();if(W){W.selectedCompanyId=$;return}vQ=$}function j$($,W){return S6.run($,W)}function _Q(){return S6.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??Cz}function xQ(){return S6.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function hQ($,W){let Q=xQ();if(!Q)throw new W1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let X={"Content-Type":$,Authorization:`Bearer ${Q}`},G=W??j1();if(G)X["x-company-id"]=G;return X}function yQ(){if(xQ())return;console.error(V1(new W1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function k0($,W){let Q=$[W];return typeof Q==="string"&&Q.trim()!==""?Q.trim():void 0}function vz($){if($===void 0)return;if(typeof $==="string")return $.trim()||void 0;return JSON.stringify($)}function fQ($){if(!$.trim())return{message:"Request failed"};try{let W=JSON.parse($);if(typeof W==="string")return{message:W};let Q=typeof W.error==="object"&&W.error!==null?W.error:void 0,X=k0(W,"code")??(Q?k0(Q,"code"):void 0),G=(typeof W.error==="string"?W.error:void 0)??(Q?k0(Q,"message"):void 0)??k0(W,"message")??k0(W,"error")??$,J=k0(W,"howToFix")??k0(W,"resolution"),w={...k0(W,"title")?{title:k0(W,"title")}:{},...k0(W,"description")?{description:k0(W,"description")}:{},...J?{howToFix:J}:{},...k0(W,"docsUrl")?{docsUrl:k0(W,"docsUrl")}:{}},Y=vz(W.details);if(Object.keys(w).length>0||Y)return{message:G,...X?{code:X}:{},...Y?{details:Y}:{},...Object.keys(w).length>0?{context:w}:{}};if(typeof W.error==="string")return{message:W.error,...X?{code:X}:{}};if(Q)return{message:G,...X?{code:X}:{}};return{message:G,...X?{code:X}:{}}}catch{return{message:$}}}async function D($,W,Q,X){let G=hQ("application/json",X),J;try{J=await fetch(`${_Q()}${W}`,{method:$,headers:G,body:Q?JSON.stringify(Q):void 0})}catch(w){throw new W1(w instanceof Error?w.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!J.ok){let w=await J.text(),Y=fQ(w);throw new W1(Y.message,J.status,Y.details??w,Y.code,Y.context)}return J.json()}async function uQ($,W,Q,X){let G=new URL(_Q()).origin,J=new URL($,`${G}/`);if(J.origin!==G){if(!kz.has(J.pathname))throw new W1("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");J=new URL(`${J.pathname}${J.search}`,`${G}/`)}let w;try{w=await fetch(J,{method:"PUT",headers:hQ(Q,X),body:W})}catch(Y){throw new W1(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!w.ok){let Y=await w.text(),b=fQ(Y);throw new W1(b.message,w.status,b.details??Y,b.code,b.context)}}var TM=Object.freeze({status:"aborted"});function V($,W,Q){function X(Y,b){var H;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(H=Y._zod).traits??(H.traits=new Set),Y._zod.traits.add($),W(Y,b);for(let z in w.prototype)if(!(z in Y))Object.defineProperty(Y,z,{value:w.prototype[z].bind(Y)});Y._zod.constr=w,Y._zod.def=b}let G=Q?.Parent??Object;class J extends G{}Object.defineProperty(J,"name",{value:$});function w(Y){var b;let H=Q?.Parent?new J:this;X(H,Y),(b=H._zod).deferred??(b.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(w,"init",{value:X}),Object.defineProperty(w,Symbol.hasInstance,{value:(Y)=>{if(Q?.Parent&&Y instanceof Q.Parent)return!0;return Y?._zod?.traits?.has($)}}),Object.defineProperty(w,"name",{value:$}),w}var RM=Symbol("zod_brand");class Y1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class C6 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}var _4={};function f0($){if($)Object.assign(_4,$);return _4}var o={};SQ(o,{unwrapMessage:()=>k6,uint8ArrayToHex:()=>GD,uint8ArrayToBase64url:()=>QD,uint8ArrayToBase64:()=>nQ,stringifyPrimitive:()=>f4,shallowClone:()=>mQ,safeExtend:()=>rz,required:()=>ez,randomString:()=>gz,propertyKeyTypes:()=>E$,promiseAllObject:()=>lz,primitiveTypes:()=>lQ,prefixIssues:()=>H1,pick:()=>dz,partial:()=>az,optionalKeys:()=>T$,omit:()=>oz,objectClone:()=>uz,numKeys:()=>pz,nullish:()=>v6,normalizeParams:()=>x,mergeDefs:()=>q1,merge:()=>sz,jsonStringifyReplacer:()=>e1,joinValues:()=>x4,issue:()=>W6,isPlainObject:()=>I1,isObject:()=>u1,hexToUint8Array:()=>XD,getSizableOrigin:()=>pQ,getParsedType:()=>iz,getLengthableOrigin:()=>x6,getEnumValues:()=>q$,getElementAtPath:()=>mz,floatSafeRemainder:()=>I$,finalizeIssue:()=>n0,extend:()=>tz,escapeRegex:()=>b1,esc:()=>h4,defineLazy:()=>s,createTransparentProxy:()=>nz,cloneDef:()=>cz,clone:()=>i0,cleanRegex:()=>_6,cleanEnum:()=>$D,captureStackTrace:()=>y4,cached:()=>$6,base64urlToUint8Array:()=>WD,base64ToUint8Array:()=>iQ,assignProp:()=>M1,assertNotEqual:()=>xz,assertNever:()=>yz,assertIs:()=>hz,assertEqual:()=>_z,assert:()=>fz,allowsEval:()=>N$,aborted:()=>N1,NUMBER_FORMAT_RANGES:()=>R$,Class:()=>dQ,BIGINT_FORMAT_RANGES:()=>gQ});function _z($){return $}function xz($){return $}function hz($){}function yz($){throw Error()}function fz($){}function q$($){let W=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,G])=>W.indexOf(+X)===-1).map(([X,G])=>G)}function x4($,W="|"){return $.map((Q)=>f4(Q)).join(W)}function e1($,W){if(typeof W==="bigint")return W.toString();return W}function $6($){return{get value(){{let Q=$();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function v6($){return $===null||$===void 0}function _6($){let W=$.startsWith("^")?1:0,Q=$.endsWith("$")?$.length-1:$.length;return $.slice(W,Q)}function I$($,W){let Q=($.toString().split(".")[1]||"").length,X=W.toString(),G=(X.split(".")[1]||"").length;if(G===0&&/\d?e-\d?/.test(X)){let b=X.match(/\d?e-(\d?)/);if(b?.[1])G=Number.parseInt(b[1])}let J=Q>G?Q:G,w=Number.parseInt($.toFixed(J).replace(".","")),Y=Number.parseInt(W.toFixed(J).replace(".",""));return w%Y/10**J}var cQ=Symbol("evaluating");function s($,W,Q){let X=void 0;Object.defineProperty($,W,{get(){if(X===cQ)return;if(X===void 0)X=cQ,X=Q();return X},set(G){Object.defineProperty($,W,{value:G})},configurable:!0})}function uz($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function M1($,W,Q){Object.defineProperty($,W,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function q1(...$){let W={};for(let Q of $){let X=Object.getOwnPropertyDescriptors(Q);Object.assign(W,X)}return Object.defineProperties({},W)}function cz($){return q1($._zod.def)}function mz($,W){if(!W)return $;return W.reduce((Q,X)=>Q?.[X],$)}function lz($){let W=Object.keys($),Q=W.map((X)=>$[X]);return Promise.all(Q).then((X)=>{let G={};for(let J=0;J<W.length;J++)G[W[J]]=X[J];return G})}function gz($=10){let Q="";for(let X=0;X<$;X++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function h4($){return JSON.stringify($)}var y4="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function u1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var N$=$6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function I1($){if(u1($)===!1)return!1;let W=$.constructor;if(W===void 0)return!0;let Q=W.prototype;if(u1(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function mQ($){if(I1($))return{...$};if(Array.isArray($))return[...$];return $}function pz($){let W=0;for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))W++;return W}var iz=($)=>{let W=typeof $;switch(W){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${W}`)}},E$=new Set(["string","number","symbol"]),lQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function b1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i0($,W,Q){let X=new $._zod.constr(W??$._zod.def);if(!W||Q?.parent)X._zod.parent=$;return X}function x($){let W=$;if(!W)return{};if(typeof W==="string")return{error:()=>W};if(W?.message!==void 0){if(W?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");W.error=W.message}if(delete W.message,typeof W.error==="string")return{...W,error:()=>W.error};return W}function nz($){let W;return new Proxy({},{get(Q,X,G){return W??(W=$()),Reflect.get(W,X,G)},set(Q,X,G,J){return W??(W=$()),Reflect.set(W,X,G,J)},has(Q,X){return W??(W=$()),Reflect.has(W,X)},deleteProperty(Q,X){return W??(W=$()),Reflect.deleteProperty(W,X)},ownKeys(Q){return W??(W=$()),Reflect.ownKeys(W)},getOwnPropertyDescriptor(Q,X){return W??(W=$()),Reflect.getOwnPropertyDescriptor(W,X)},defineProperty(Q,X,G){return W??(W=$()),Reflect.defineProperty(W,X,G)}})}function f4($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function T$($){return Object.keys($).filter((W)=>{return $[W]._zod.optin==="optional"&&$[W]._zod.optout==="optional"})}var R$={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},gQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function dz($,W){let Q=$._zod.def,X=q1($._zod.def,{get shape(){let G={};for(let J in W){if(!(J in Q.shape))throw Error(`Unrecognized key: "${J}"`);if(!W[J])continue;G[J]=Q.shape[J]}return M1(this,"shape",G),G},checks:[]});return i0($,X)}function oz($,W){let Q=$._zod.def,X=q1($._zod.def,{get shape(){let G={...$._zod.def.shape};for(let J in W){if(!(J in Q.shape))throw Error(`Unrecognized key: "${J}"`);if(!W[J])continue;delete G[J]}return M1(this,"shape",G),G},checks:[]});return i0($,X)}function tz($,W){if(!I1(W))throw Error("Invalid input to extend: expected a plain object");let Q=$._zod.def.checks;if(Q&&Q.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let G=q1($._zod.def,{get shape(){let J={...$._zod.def.shape,...W};return M1(this,"shape",J),J},checks:[]});return i0($,G)}function rz($,W){if(!I1(W))throw Error("Invalid input to safeExtend: expected a plain object");let Q={...$._zod.def,get shape(){let X={...$._zod.def.shape,...W};return M1(this,"shape",X),X},checks:$._zod.def.checks};return i0($,Q)}function sz($,W){let Q=q1($._zod.def,{get shape(){let X={...$._zod.def.shape,...W._zod.def.shape};return M1(this,"shape",X),X},get catchall(){return W._zod.def.catchall},checks:[]});return i0($,Q)}function az($,W,Q){let X=q1(W._zod.def,{get shape(){let G=W._zod.def.shape,J={...G};if(Q)for(let w in Q){if(!(w in G))throw Error(`Unrecognized key: "${w}"`);if(!Q[w])continue;J[w]=$?new $({type:"optional",innerType:G[w]}):G[w]}else for(let w in G)J[w]=$?new $({type:"optional",innerType:G[w]}):G[w];return M1(this,"shape",J),J},checks:[]});return i0(W,X)}function ez($,W,Q){let X=q1(W._zod.def,{get shape(){let G=W._zod.def.shape,J={...G};if(Q)for(let w in Q){if(!(w in J))throw Error(`Unrecognized key: "${w}"`);if(!Q[w])continue;J[w]=new $({type:"nonoptional",innerType:G[w]})}else for(let w in G)J[w]=new $({type:"nonoptional",innerType:G[w]});return M1(this,"shape",J),J},checks:[]});return i0(W,X)}function N1($,W=0){if($.aborted===!0)return!0;for(let Q=W;Q<$.issues.length;Q++)if($.issues[Q]?.continue!==!0)return!0;return!1}function H1($,W){return W.map((Q)=>{var X;return(X=Q).path??(X.path=[]),Q.path.unshift($),Q})}function k6($){return typeof $==="string"?$:$?.message}function n0($,W,Q){let X={...$,path:$.path??[]};if(!$.message){let G=k6($.inst?._zod.def?.error?.($))??k6(W?.error?.($))??k6(Q.customError?.($))??k6(Q.localeError?.($))??"Invalid input";X.message=G}if(delete X.inst,delete X.continue,!W?.reportInput)delete X.input;return X}function pQ($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function x6($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function W6(...$){let[W,Q,X]=$;if(typeof W==="string")return{message:W,code:"custom",input:Q,inst:X};return{...W}}function $D($){return Object.entries($).filter(([W,Q])=>{return Number.isNaN(Number.parseInt(W,10))}).map((W)=>W[1])}function iQ($){let W=atob($),Q=new Uint8Array(W.length);for(let X=0;X<W.length;X++)Q[X]=W.charCodeAt(X);return Q}function nQ($){let W="";for(let Q=0;Q<$.length;Q++)W+=String.fromCharCode($[Q]);return btoa(W)}function WD($){let W=$.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-W.length%4)%4);return iQ(W+Q)}function QD($){return nQ($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function XD($){let W=$.replace(/^0x/,"");if(W.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(W.length/2);for(let X=0;X<W.length;X+=2)Q[X/2]=Number.parseInt(W.slice(X,X+2),16);return Q}function GD($){return Array.from($).map((W)=>W.toString(16).padStart(2,"0")).join("")}class dQ{constructor(...$){}}var oQ=($,W)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:W,enumerable:!1}),$.message=JSON.stringify(W,e1,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},u4=V("$ZodError",oQ),S$=V("$ZodError",oQ,{Parent:Error});function tQ($,W=(Q)=>Q.message){let Q={},X=[];for(let G of $.issues)if(G.path.length>0)Q[G.path[0]]=Q[G.path[0]]||[],Q[G.path[0]].push(W(G));else X.push(W(G));return{formErrors:X,fieldErrors:Q}}function rQ($,W=(Q)=>Q.message){let Q={_errors:[]},X=(G)=>{for(let J of G.issues)if(J.code==="invalid_union"&&J.errors.length)J.errors.map((w)=>X({issues:w}));else if(J.code==="invalid_key")X({issues:J.issues});else if(J.code==="invalid_element")X({issues:J.issues});else if(J.path.length===0)Q._errors.push(W(J));else{let w=Q,Y=0;while(Y<J.path.length){let b=J.path[Y];if(Y!==J.path.length-1)w[b]=w[b]||{_errors:[]};else w[b]=w[b]||{_errors:[]},w[b]._errors.push(W(J));w=w[b],Y++}}};return X($),Q}var c4=($)=>(W,Q,X,G)=>{let J=X?Object.assign(X,{async:!1}):{async:!1},w=W._zod.run({value:Q,issues:[]},J);if(w instanceof Promise)throw new Y1;if(w.issues.length){let Y=new(G?.Err??$)(w.issues.map((b)=>n0(b,J,f0())));throw y4(Y,G?.callee),Y}return w.value};var m4=($)=>async(W,Q,X,G)=>{let J=X?Object.assign(X,{async:!0}):{async:!0},w=W._zod.run({value:Q,issues:[]},J);if(w instanceof Promise)w=await w;if(w.issues.length){let Y=new(G?.Err??$)(w.issues.map((b)=>n0(b,J,f0())));throw y4(Y,G?.callee),Y}return w.value};var h6=($)=>(W,Q,X)=>{let G=X?{...X,async:!1}:{async:!1},J=W._zod.run({value:Q,issues:[]},G);if(J instanceof Promise)throw new Y1;return J.issues.length?{success:!1,error:new($??u4)(J.issues.map((w)=>n0(w,G,f0())))}:{success:!0,data:J.value}},y6=h6(S$),f6=($)=>async(W,Q,X)=>{let G=X?Object.assign(X,{async:!0}):{async:!0},J=W._zod.run({value:Q,issues:[]},G);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((w)=>n0(w,G,f0())))}:{success:!0,data:J.value}},l4=f6(S$),sQ=($)=>(W,Q,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return c4($)(W,Q,G)};var aQ=($)=>(W,Q,X)=>{return c4($)(W,Q,X)};var eQ=($)=>async(W,Q,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return m4($)(W,Q,G)};var $X=($)=>async(W,Q,X)=>{return m4($)(W,Q,X)};var WX=($)=>(W,Q,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return h6($)(W,Q,G)};var QX=($)=>(W,Q,X)=>{return h6($)(W,Q,X)};var XX=($)=>async(W,Q,X)=>{let G=X?Object.assign(X,{direction:"backward"}):{direction:"backward"};return f6($)(W,Q,G)};var GX=($)=>async(W,Q,X)=>{return f6($)(W,Q,X)};var JX=/^[cC][^\s-]{8,}$/,wX=/^[0-9a-z]+$/,YX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bX=/^[0-9a-vA-V]{20}$/,HX=/^[A-Za-z0-9]{27}$/,zX=/^[a-zA-Z0-9_-]{21}$/,DX=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var FX=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,C$=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var UX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function BX(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var LX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,AX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,OX=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,KX=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ZX=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,k$=/^[A-Za-z0-9_-]*$/,PX=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var VX=/^\+(?:[0-9]){6,14}[0-9]$/,jX="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",MX=new RegExp(`^${jX}$`);function qX($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IX($){return new RegExp(`^${qX($)}$`)}function NX($){let W=qX({precision:$.precision}),Q=["Z"];if($.local)Q.push("");if($.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let X=`${W}(?:${Q.join("|")})`;return new RegExp(`^${jX}T(?:${X})$`)}var EX=($)=>{let W=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${W}$`)};var TX=/^-?\d+$/,RX=/^-?\d+(?:\.\d+)?/,SX=/^(?:true|false)$/i,CX=/^null$/i;var kX=/^[^A-Z]*$/,vX=/^[^a-z]*$/;var L0=V("$ZodCheck",($,W)=>{var Q;$._zod??($._zod={}),$._zod.def=W,(Q=$._zod).onattach??(Q.onattach=[])}),_X={number:"number",bigint:"bigint",object:"date"},v$=V("$ZodCheckLessThan",($,W)=>{L0.init($,W);let Q=_X[typeof W.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(W.inclusive?G.maximum:G.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(W.value<J)if(W.inclusive)G.maximum=W.value;else G.exclusiveMaximum=W.value}),$._zod.check=(X)=>{if(W.inclusive?X.value<=W.value:X.value<W.value)return;X.issues.push({origin:Q,code:"too_big",maximum:W.value,input:X.value,inclusive:W.inclusive,inst:$,continue:!W.abort})}}),_$=V("$ZodCheckGreaterThan",($,W)=>{L0.init($,W);let Q=_X[typeof W.value];$._zod.onattach.push((X)=>{let G=X._zod.bag,J=(W.inclusive?G.minimum:G.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(W.value>J)if(W.inclusive)G.minimum=W.value;else G.exclusiveMinimum=W.value}),$._zod.check=(X)=>{if(W.inclusive?X.value>=W.value:X.value>W.value)return;X.issues.push({origin:Q,code:"too_small",minimum:W.value,input:X.value,inclusive:W.inclusive,inst:$,continue:!W.abort})}}),xX=V("$ZodCheckMultipleOf",($,W)=>{L0.init($,W),$._zod.onattach.push((Q)=>{var X;(X=Q._zod.bag).multipleOf??(X.multipleOf=W.value)}),$._zod.check=(Q)=>{if(typeof Q.value!==typeof W.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%W.value===BigInt(0):I$(Q.value,W.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:W.value,input:Q.value,inst:$,continue:!W.abort})}}),hX=V("$ZodCheckNumberFormat",($,W)=>{L0.init($,W),W.format=W.format||"float64";let Q=W.format?.includes("int"),X=Q?"int":"number",[G,J]=R$[W.format];$._zod.onattach.push((w)=>{let Y=w._zod.bag;if(Y.format=W.format,Y.minimum=G,Y.maximum=J,Q)Y.pattern=TX}),$._zod.check=(w)=>{let Y=w.value;if(Q){if(!Number.isInteger(Y)){w.issues.push({expected:X,format:W.format,code:"invalid_type",continue:!1,input:Y,inst:$});return}if(!Number.isSafeInteger(Y)){if(Y>0)w.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!W.abort});else w.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,continue:!W.abort});return}}if(Y<G)w.issues.push({origin:"number",input:Y,code:"too_small",minimum:G,inclusive:!0,inst:$,continue:!W.abort});if(Y>J)w.issues.push({origin:"number",input:Y,code:"too_big",maximum:J,inst:$})}});var yX=V("$ZodCheckMaxLength",($,W)=>{var Q;L0.init($,W),(Q=$._zod.def).when??(Q.when=(X)=>{let G=X.value;return!v6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(W.maximum<G)X._zod.bag.maximum=W.maximum}),$._zod.check=(X)=>{let G=X.value;if(G.length<=W.maximum)return;let w=x6(G);X.issues.push({origin:w,code:"too_big",maximum:W.maximum,inclusive:!0,input:G,inst:$,continue:!W.abort})}}),fX=V("$ZodCheckMinLength",($,W)=>{var Q;L0.init($,W),(Q=$._zod.def).when??(Q.when=(X)=>{let G=X.value;return!v6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(W.minimum>G)X._zod.bag.minimum=W.minimum}),$._zod.check=(X)=>{let G=X.value;if(G.length>=W.minimum)return;let w=x6(G);X.issues.push({origin:w,code:"too_small",minimum:W.minimum,inclusive:!0,input:G,inst:$,continue:!W.abort})}}),uX=V("$ZodCheckLengthEquals",($,W)=>{var Q;L0.init($,W),(Q=$._zod.def).when??(Q.when=(X)=>{let G=X.value;return!v6(G)&&G.length!==void 0}),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.minimum=W.length,G.maximum=W.length,G.length=W.length}),$._zod.check=(X)=>{let G=X.value,J=G.length;if(J===W.length)return;let w=x6(G),Y=J>W.length;X.issues.push({origin:w,...Y?{code:"too_big",maximum:W.length}:{code:"too_small",minimum:W.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!W.abort})}}),u6=V("$ZodCheckStringFormat",($,W)=>{var Q,X;if(L0.init($,W),$._zod.onattach.push((G)=>{let J=G._zod.bag;if(J.format=W.format,W.pattern)J.patterns??(J.patterns=new Set),J.patterns.add(W.pattern)}),W.pattern)(Q=$._zod).check??(Q.check=(G)=>{if(W.pattern.lastIndex=0,W.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:W.format,input:G.value,...W.pattern?{pattern:W.pattern.toString()}:{},inst:$,continue:!W.abort})});else(X=$._zod).check??(X.check=()=>{})}),cX=V("$ZodCheckRegex",($,W)=>{u6.init($,W),$._zod.check=(Q)=>{if(W.pattern.lastIndex=0,W.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:W.pattern.toString(),inst:$,continue:!W.abort})}}),mX=V("$ZodCheckLowerCase",($,W)=>{W.pattern??(W.pattern=kX),u6.init($,W)}),lX=V("$ZodCheckUpperCase",($,W)=>{W.pattern??(W.pattern=vX),u6.init($,W)}),gX=V("$ZodCheckIncludes",($,W)=>{L0.init($,W);let Q=b1(W.includes),X=new RegExp(typeof W.position==="number"?`^.{${W.position}}${Q}`:Q);W.pattern=X,$._zod.onattach.push((G)=>{let J=G._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(X)}),$._zod.check=(G)=>{if(G.value.includes(W.includes,W.position))return;G.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:W.includes,input:G.value,inst:$,continue:!W.abort})}}),pX=V("$ZodCheckStartsWith",($,W)=>{L0.init($,W);let Q=new RegExp(`^${b1(W.prefix)}.*`);W.pattern??(W.pattern=Q),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),$._zod.check=(X)=>{if(X.value.startsWith(W.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:W.prefix,input:X.value,inst:$,continue:!W.abort})}}),iX=V("$ZodCheckEndsWith",($,W)=>{L0.init($,W);let Q=new RegExp(`.*${b1(W.suffix)}$`);W.pattern??(W.pattern=Q),$._zod.onattach.push((X)=>{let G=X._zod.bag;G.patterns??(G.patterns=new Set),G.patterns.add(Q)}),$._zod.check=(X)=>{if(X.value.endsWith(W.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:W.suffix,input:X.value,inst:$,continue:!W.abort})}});var nX=V("$ZodCheckOverwrite",($,W)=>{L0.init($,W),$._zod.check=(Q)=>{Q.value=W.tx(Q.value)}});class x${constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let Q=$.split(`
|
|
11
|
-
`).filter((J)=>J),
|
|
12
|
-
`))}}var
|
|
13
|
-
if (${
|
|
14
|
-
payload.issues = payload.issues.concat(${
|
|
2
|
+
var Pz=Object.create;var{getPrototypeOf:Vz,defineProperty:j9,getOwnPropertyNames:jz}=Object;var Mz=Object.prototype.hasOwnProperty;function qz(W){return this[W]}var Iz,Nz,RQ=(W,$,Q)=>{var G=W!=null&&typeof W==="object";if(G){var X=$?Iz??=new WeakMap:Nz??=new WeakMap,J=X.get(W);if(J)return J}Q=W!=null?Pz(Vz(W)):{};let w=$||!W||!W.__esModule?j9(Q,"default",{value:W,enumerable:!0}):Q;for(let Y of jz(W))if(!Mz.call(w,Y))j9(w,Y,{get:qz.bind(W,Y),enumerable:!0});if(G)X.set(W,w);return w};var N=(W,$)=>()=>($||W(($={exports:{}}).exports,$),$.exports);var Ez=(W)=>W;function Tz(W,$){this[W]=Ez.bind(null,$)}var SQ=(W,$)=>{for(var Q in $)j9(W,Q,{get:$[Q],enumerable:!0,configurable:!0,set:Tz.bind($,Q)})};var G4=N((Cw)=>{Object.defineProperty(Cw,"__esModule",{value:!0});Cw.regexpCode=Cw.getEsmExportName=Cw.getProperty=Cw.safeStringify=Cw.stringify=Cw.strConcat=Cw.addCodeArg=Cw.str=Cw._=Cw.nil=Cw._Code=Cw.Name=Cw.IDENTIFIER=Cw._CodeOrName=void 0;class AW{}Cw._CodeOrName=AW;Cw.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Y6 extends AW{constructor(W){super();if(!Cw.IDENTIFIER.test(W))throw Error("CodeGen: name must be a valid identifier");this.str=W}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}Cw.Name=Y6;class d0 extends AW{constructor(W){super();this._items=typeof W==="string"?[W]:W}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let W=this._items[0];return W===""||W==='""'}get str(){var W;return(W=this._str)!==null&&W!==void 0?W:this._str=this._items.reduce(($,Q)=>`${$}${Q}`,"")}get names(){var W;return(W=this._names)!==null&&W!==void 0?W:this._names=this._items.reduce(($,Q)=>{if(Q instanceof Y6)$[Q.str]=($[Q.str]||0)+1;return $},{})}}Cw._Code=d0;Cw.nil=new d0("");function Rw(W,...$){let Q=[W[0]],G=0;while(G<$.length)C$(Q,$[G]),Q.push(W[++G]);return new d0(Q)}Cw._=Rw;var S$=new d0("+");function Sw(W,...$){let Q=[Q4(W[0])],G=0;while(G<$.length)Q.push(S$),C$(Q,$[G]),Q.push(S$,Q4(W[++G]));return sU(Q),new d0(Q)}Cw.str=Sw;function C$(W,$){if($ instanceof d0)W.push(...$._items);else if($ instanceof Y6)W.push($);else W.push(WL($))}Cw.addCodeArg=C$;function sU(W){let $=1;while($<W.length-1){if(W[$]===S$){let Q=aU(W[$-1],W[$+1]);if(Q!==void 0){W.splice($-1,3,Q);continue}W[$++]="+"}$++}}function aU(W,$){if($==='""')return W;if(W==='""')return $;if(typeof W=="string"){if($ instanceof Y6||W[W.length-1]!=='"')return;if(typeof $!="string")return`${W.slice(0,-1)}${$}"`;if($[0]==='"')return W.slice(0,-1)+$.slice(1);return}if(typeof $=="string"&&$[0]==='"'&&!(W instanceof Y6))return`"${W}${$.slice(1)}`;return}function eU(W,$){return $.emptyStr()?W:W.emptyStr()?$:Sw`${W}${$}`}Cw.strConcat=eU;function WL(W){return typeof W=="number"||typeof W=="boolean"||W===null?W:Q4(Array.isArray(W)?W.join(","):W)}function $L(W){return new d0(Q4(W))}Cw.stringify=$L;function Q4(W){return JSON.stringify(W).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Cw.safeStringify=Q4;function QL(W){return typeof W=="string"&&Cw.IDENTIFIER.test(W)?new d0(`.${W}`):Rw`[${W}]`}Cw.getProperty=QL;function GL(W){if(typeof W=="string"&&Cw.IDENTIFIER.test(W))return new d0(`${W}`);throw Error(`CodeGen: invalid export name: ${W}, use explicit $id name mapping`)}Cw.getEsmExportName=GL;function XL(W){return new d0(W.toString())}Cw.regexpCode=XL});var x$=N((xw)=>{Object.defineProperty(xw,"__esModule",{value:!0});xw.ValueScope=xw.ValueScopeName=xw.Scope=xw.varKinds=xw.UsedValueState=void 0;var N0=G4();class vw extends Error{constructor(W){super(`CodeGen: "code" for ${W} not defined`);this.value=W.value}}var ZW;(function(W){W[W.Started=0]="Started",W[W.Completed=1]="Completed"})(ZW||(xw.UsedValueState=ZW={}));xw.varKinds={const:new N0.Name("const"),let:new N0.Name("let"),var:new N0.Name("var")};class v${constructor({prefixes:W,parent:$}={}){this._names={},this._prefixes=W,this._parent=$}toName(W){return W instanceof N0.Name?W:this.name(W)}name(W){return new N0.Name(this._newName(W))}_newName(W){let $=this._names[W]||this._nameGroup(W);return`${W}${$.index++}`}_nameGroup(W){var $,Q;if(((Q=($=this._parent)===null||$===void 0?void 0:$._prefixes)===null||Q===void 0?void 0:Q.has(W))||this._prefixes&&!this._prefixes.has(W))throw Error(`CodeGen: prefix "${W}" is not allowed in this scope`);return this._names[W]={prefix:W,index:0}}}xw.Scope=v$;class _$ extends N0.Name{constructor(W,$){super($);this.prefix=W}setValue(W,{property:$,itemIndex:Q}){this.value=W,this.scopePath=N0._`.${new N0.Name($)}[${Q}]`}}xw.ValueScopeName=_$;var OL=N0._`\n`;class _w extends v${constructor(W){super(W);this._values={},this._scope=W.scope,this.opts={...W,_n:W.lines?OL:N0.nil}}get(){return this._scope}name(W){return new _$(W,this._newName(W))}value(W,$){var Q;if($.ref===void 0)throw Error("CodeGen: ref must be passed in value");let G=this.toName(W),{prefix:X}=G,J=(Q=$.key)!==null&&Q!==void 0?Q:$.ref,w=this._values[X];if(w){let H=w.get(J);if(H)return H}else w=this._values[X]=new Map;w.set(J,G);let Y=this._scope[X]||(this._scope[X]=[]),b=Y.length;return Y[b]=$.ref,G.setValue($,{property:X,itemIndex:b}),G}getValue(W,$){let Q=this._values[W];if(!Q)return;return Q.get($)}scopeRefs(W,$=this._values){return this._reduceValues($,(Q)=>{if(Q.scopePath===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return N0._`${W}${Q.scopePath}`})}scopeCode(W=this._values,$,Q){return this._reduceValues(W,(G)=>{if(G.value===void 0)throw Error(`CodeGen: name "${G}" has no value`);return G.value.code},$,Q)}_reduceValues(W,$,Q={},G){let X=N0.nil;for(let J in W){let w=W[J];if(!w)continue;let Y=Q[J]=Q[J]||new Map;w.forEach((b)=>{if(Y.has(b))return;Y.set(b,ZW.Started);let H=$(b);if(H){let z=this.opts.es5?xw.varKinds.var:xw.varKinds.const;X=N0._`${X}${z} ${b} = ${H};${this.opts._n}`}else if(H=G===null||G===void 0?void 0:G(b))X=N0._`${X}${H}${this.opts._n}`;else throw new vw(b);Y.set(b,ZW.Completed)})}return X}}xw.ValueScope=_w});var g=N((E0)=>{Object.defineProperty(E0,"__esModule",{value:!0});E0.or=E0.and=E0.not=E0.CodeGen=E0.operators=E0.varKinds=E0.ValueScopeName=E0.ValueScope=E0.Scope=E0.Name=E0.regexpCode=E0.stringify=E0.getProperty=E0.nil=E0.strConcat=E0.str=E0._=void 0;var n=G4(),o0=x$(),S1=G4();Object.defineProperty(E0,"_",{enumerable:!0,get:function(){return S1._}});Object.defineProperty(E0,"str",{enumerable:!0,get:function(){return S1.str}});Object.defineProperty(E0,"strConcat",{enumerable:!0,get:function(){return S1.strConcat}});Object.defineProperty(E0,"nil",{enumerable:!0,get:function(){return S1.nil}});Object.defineProperty(E0,"getProperty",{enumerable:!0,get:function(){return S1.getProperty}});Object.defineProperty(E0,"stringify",{enumerable:!0,get:function(){return S1.stringify}});Object.defineProperty(E0,"regexpCode",{enumerable:!0,get:function(){return S1.regexpCode}});Object.defineProperty(E0,"Name",{enumerable:!0,get:function(){return S1.Name}});var qW=x$();Object.defineProperty(E0,"Scope",{enumerable:!0,get:function(){return qW.Scope}});Object.defineProperty(E0,"ValueScope",{enumerable:!0,get:function(){return qW.ValueScope}});Object.defineProperty(E0,"ValueScopeName",{enumerable:!0,get:function(){return qW.ValueScopeName}});Object.defineProperty(E0,"varKinds",{enumerable:!0,get:function(){return qW.varKinds}});E0.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class C1{optimizeNodes(){return this}optimizeNames(W,$){return this}}class yw extends C1{constructor(W,$,Q){super();this.varKind=W,this.name=$,this.rhs=Q}render({es5:W,_n:$}){let Q=W?o0.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${Q} ${this.name}${G};`+$}optimizeNames(W,$){if(!W[this.name.str])return;if(this.rhs)this.rhs=H6(this.rhs,W,$);return this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class f$ extends C1{constructor(W,$,Q){super();this.lhs=W,this.rhs=$,this.sideEffects=Q}render({_n:W}){return`${this.lhs} = ${this.rhs};`+W}optimizeNames(W,$){if(this.lhs instanceof n.Name&&!W[this.lhs.str]&&!this.sideEffects)return;return this.rhs=H6(this.rhs,W,$),this}get names(){let W=this.lhs instanceof n.Name?{}:{...this.lhs.names};return MW(W,this.rhs)}}class fw extends f${constructor(W,$,Q,G){super(W,Q,G);this.op=$}render({_n:W}){return`${this.lhs} ${this.op}= ${this.rhs};`+W}}class uw extends C1{constructor(W){super();this.label=W,this.names={}}render({_n:W}){return`${this.label}:`+W}}class cw extends C1{constructor(W){super();this.label=W,this.names={}}render({_n:W}){return`break${this.label?` ${this.label}`:""};`+W}}class mw extends C1{constructor(W){super();this.error=W}render({_n:W}){return`throw ${this.error};`+W}get names(){return this.error.names}}class lw extends C1{constructor(W){super();this.code=W}render({_n:W}){return`${this.code};`+W}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(W,$){return this.code=H6(this.code,W,$),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class IW extends C1{constructor(W=[]){super();this.nodes=W}render(W){return this.nodes.reduce(($,Q)=>$+Q.render(W),"")}optimizeNodes(){let{nodes:W}=this,$=W.length;while($--){let Q=W[$].optimizeNodes();if(Array.isArray(Q))W.splice($,1,...Q);else if(Q)W[$]=Q;else W.splice($,1)}return W.length>0?this:void 0}optimizeNames(W,$){let{nodes:Q}=this,G=Q.length;while(G--){let X=Q[G];if(X.optimizeNames(W,$))continue;VL(W,X.names),Q.splice(G,1)}return Q.length>0?this:void 0}get names(){return this.nodes.reduce((W,$)=>m1(W,$.names),{})}}class k1 extends IW{render(W){return"{"+W._n+super.render(W)+"}"+W._n}}class gw extends IW{}class X4 extends k1{}X4.kind="else";class D1 extends k1{constructor(W,$){super($);this.condition=W}render(W){let $=`if(${this.condition})`+super.render(W);if(this.else)$+="else "+this.else.render(W);return $}optimizeNodes(){super.optimizeNodes();let W=this.condition;if(W===!0)return this.nodes;let $=this.else;if($){let Q=$.optimizeNodes();$=this.else=Array.isArray(Q)?new X4(Q):Q}if($){if(W===!1)return $ instanceof D1?$:$.nodes;if(this.nodes.length)return this;return new D1(ow(W),$ instanceof D1?[$]:$.nodes)}if(W===!1||!this.nodes.length)return;return this}optimizeNames(W,$){var Q;if(this.else=(Q=this.else)===null||Q===void 0?void 0:Q.optimizeNames(W,$),!(super.optimizeNames(W,$)||this.else))return;return this.condition=H6(this.condition,W,$),this}get names(){let W=super.names;if(MW(W,this.condition),this.else)m1(W,this.else.names);return W}}D1.kind="if";class b6 extends k1{}b6.kind="for";class pw extends b6{constructor(W){super();this.iteration=W}render(W){return`for(${this.iteration})`+super.render(W)}optimizeNames(W,$){if(!super.optimizeNames(W,$))return;return this.iteration=H6(this.iteration,W,$),this}get names(){return m1(super.names,this.iteration.names)}}class iw extends b6{constructor(W,$,Q,G){super();this.varKind=W,this.name=$,this.from=Q,this.to=G}render(W){let $=W.es5?o0.varKinds.var:this.varKind,{name:Q,from:G,to:X}=this;return`for(${$} ${Q}=${G}; ${Q}<${X}; ${Q}++)`+super.render(W)}get names(){let W=MW(super.names,this.from);return MW(W,this.to)}}class h$ extends b6{constructor(W,$,Q,G){super();this.loop=W,this.varKind=$,this.name=Q,this.iterable=G}render(W){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(W)}optimizeNames(W,$){if(!super.optimizeNames(W,$))return;return this.iterable=H6(this.iterable,W,$),this}get names(){return m1(super.names,this.iterable.names)}}class KW extends k1{constructor(W,$,Q){super();this.name=W,this.args=$,this.async=Q}render(W){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(W)}}KW.kind="func";class PW extends IW{render(W){return"return "+super.render(W)}}PW.kind="return";class nw extends k1{render(W){let $="try"+super.render(W);if(this.catch)$+=this.catch.render(W);if(this.finally)$+=this.finally.render(W);return $}optimizeNodes(){var W,$;return super.optimizeNodes(),(W=this.catch)===null||W===void 0||W.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(W,$){var Q,G;return super.optimizeNames(W,$),(Q=this.catch)===null||Q===void 0||Q.optimizeNames(W,$),(G=this.finally)===null||G===void 0||G.optimizeNames(W,$),this}get names(){let W=super.names;if(this.catch)m1(W,this.catch.names);if(this.finally)m1(W,this.finally.names);return W}}class VW extends k1{constructor(W){super();this.error=W}render(W){return`catch(${this.error})`+super.render(W)}}VW.kind="catch";class jW extends k1{render(W){return"finally"+super.render(W)}}jW.kind="finally";class dw{constructor(W,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
3
|
+
`:""},this._extScope=W,this._scope=new o0.Scope({parent:W}),this._nodes=[new gw]}toString(){return this._root.render(this.opts)}name(W){return this._scope.name(W)}scopeName(W){return this._extScope.name(W)}scopeValue(W,$){let Q=this._extScope.value(W,$);return(this._values[Q.prefix]||(this._values[Q.prefix]=new Set)).add(Q),Q}getScopeValue(W,$){return this._extScope.getValue(W,$)}scopeRefs(W){return this._extScope.scopeRefs(W,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(W,$,Q,G){let X=this._scope.toName($);if(Q!==void 0&&G)this._constants[X.str]=Q;return this._leafNode(new yw(W,X,Q)),X}const(W,$,Q){return this._def(o0.varKinds.const,W,$,Q)}let(W,$,Q){return this._def(o0.varKinds.let,W,$,Q)}var(W,$,Q){return this._def(o0.varKinds.var,W,$,Q)}assign(W,$,Q){return this._leafNode(new f$(W,$,Q))}add(W,$){return this._leafNode(new fw(W,E0.operators.ADD,$))}code(W){if(typeof W=="function")W();else if(W!==n.nil)this._leafNode(new lw(W));return this}object(...W){let $=["{"];for(let[Q,G]of W){if($.length>1)$.push(",");if($.push(Q),Q!==G||this.opts.es5)$.push(":"),(0,n.addCodeArg)($,G)}return $.push("}"),new n._Code($)}if(W,$,Q){if(this._blockNode(new D1(W)),$&&Q)this.code($).else().code(Q).endIf();else if($)this.code($).endIf();else if(Q)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(W){return this._elseNode(new D1(W))}else(){return this._elseNode(new X4)}endIf(){return this._endBlockNode(D1,X4)}_for(W,$){if(this._blockNode(W),$)this.code($).endFor();return this}for(W,$){return this._for(new pw(W),$)}forRange(W,$,Q,G,X=this.opts.es5?o0.varKinds.var:o0.varKinds.let){let J=this._scope.toName(W);return this._for(new iw(X,J,$,Q),()=>G(J))}forOf(W,$,Q,G=o0.varKinds.const){let X=this._scope.toName(W);if(this.opts.es5){let J=$ instanceof n.Name?$:this.var("_arr",$);return this.forRange("_i",0,n._`${J}.length`,(w)=>{this.var(X,n._`${J}[${w}]`),Q(X)})}return this._for(new h$("of",G,X,$),()=>Q(X))}forIn(W,$,Q,G=this.opts.es5?o0.varKinds.var:o0.varKinds.const){if(this.opts.ownProperties)return this.forOf(W,n._`Object.keys(${$})`,Q);let X=this._scope.toName(W);return this._for(new h$("in",G,X,$),()=>Q(X))}endFor(){return this._endBlockNode(b6)}label(W){return this._leafNode(new uw(W))}break(W){return this._leafNode(new cw(W))}return(W){let $=new PW;if(this._blockNode($),this.code(W),$.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(PW)}try(W,$,Q){if(!$&&!Q)throw Error('CodeGen: "try" without "catch" and "finally"');let G=new nw;if(this._blockNode(G),this.code(W),$){let X=this.name("e");this._currNode=G.catch=new VW(X),$(X)}if(Q)this._currNode=G.finally=new jW,this.code(Q);return this._endBlockNode(VW,jW)}throw(W){return this._leafNode(new mw(W))}block(W,$){if(this._blockStarts.push(this._nodes.length),W)this.code(W).endBlock($);return this}endBlock(W){let $=this._blockStarts.pop();if($===void 0)throw Error("CodeGen: not in self-balancing block");let Q=this._nodes.length-$;if(Q<0||W!==void 0&&Q!==W)throw Error(`CodeGen: wrong number of nodes: ${Q} vs ${W} expected`);return this._nodes.length=$,this}func(W,$=n.nil,Q,G){if(this._blockNode(new KW(W,$,Q)),G)this.code(G).endFunc();return this}endFunc(){return this._endBlockNode(KW)}optimize(W=1){while(W-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(W){return this._currNode.nodes.push(W),this}_blockNode(W){this._currNode.nodes.push(W),this._nodes.push(W)}_endBlockNode(W,$){let Q=this._currNode;if(Q instanceof W||$&&Q instanceof $)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${$?`${W.kind}/${$.kind}`:W.kind}"`)}_elseNode(W){let $=this._currNode;if(!($ instanceof D1))throw Error('CodeGen: "else" without "if"');return this._currNode=$.else=W,this}get _root(){return this._nodes[0]}get _currNode(){let W=this._nodes;return W[W.length-1]}set _currNode(W){let $=this._nodes;$[$.length-1]=W}}E0.CodeGen=dw;function m1(W,$){for(let Q in $)W[Q]=(W[Q]||0)+($[Q]||0);return W}function MW(W,$){return $ instanceof n._CodeOrName?m1(W,$.names):W}function H6(W,$,Q){if(W instanceof n.Name)return G(W);if(!X(W))return W;return new n._Code(W._items.reduce((J,w)=>{if(w instanceof n.Name)w=G(w);if(w instanceof n._Code)J.push(...w._items);else J.push(w);return J},[]));function G(J){let w=Q[J.str];if(w===void 0||$[J.str]!==1)return J;return delete $[J.str],w}function X(J){return J instanceof n._Code&&J._items.some((w)=>w instanceof n.Name&&$[w.str]===1&&Q[w.str]!==void 0)}}function VL(W,$){for(let Q in $)W[Q]=(W[Q]||0)-($[Q]||0)}function ow(W){return typeof W=="boolean"||typeof W=="number"||W===null?!W:n._`!${y$(W)}`}E0.not=ow;var jL=tw(E0.operators.AND);function ML(...W){return W.reduce(jL)}E0.and=ML;var qL=tw(E0.operators.OR);function IL(...W){return W.reduce(qL)}E0.or=IL;function tw(W){return($,Q)=>$===n.nil?Q:Q===n.nil?$:n._`${y$($)} ${W} ${y$(Q)}`}function y$(W){return W instanceof n.Name?W:n._`(${W})`}});var t=N((XY)=>{Object.defineProperty(XY,"__esModule",{value:!0});XY.checkStrictMode=XY.getErrorPath=XY.Type=XY.useFunc=XY.setEvaluated=XY.evaluatedPropsToName=XY.mergeEvaluated=XY.eachItem=XY.unescapeJsonPointer=XY.escapeJsonPointer=XY.escapeFragment=XY.unescapeFragment=XY.schemaRefOrVal=XY.schemaHasRulesButRef=XY.schemaHasRules=XY.checkUnknownRules=XY.alwaysValidSchema=XY.toHash=void 0;var a=g(),RL=G4();function SL(W){let $={};for(let Q of W)$[Q]=!0;return $}XY.toHash=SL;function CL(W,$){if(typeof $=="boolean")return $;if(Object.keys($).length===0)return!0;return ew(W,$),!WY($,W.self.RULES.all)}XY.alwaysValidSchema=CL;function ew(W,$=W.schema){let{opts:Q,self:G}=W;if(!Q.strictSchema)return;if(typeof $==="boolean")return;let X=G.RULES.keywords;for(let J in $)if(!X[J])GY(W,`unknown keyword: "${J}"`)}XY.checkUnknownRules=ew;function WY(W,$){if(typeof W=="boolean")return!W;for(let Q in W)if($[Q])return!0;return!1}XY.schemaHasRules=WY;function kL(W,$){if(typeof W=="boolean")return!W;for(let Q in W)if(Q!=="$ref"&&$.all[Q])return!0;return!1}XY.schemaHasRulesButRef=kL;function vL({topSchemaRef:W,schemaPath:$},Q,G,X){if(!X){if(typeof Q=="number"||typeof Q=="boolean")return Q;if(typeof Q=="string")return a._`${Q}`}return a._`${W}${$}${(0,a.getProperty)(G)}`}XY.schemaRefOrVal=vL;function _L(W){return $Y(decodeURIComponent(W))}XY.unescapeFragment=_L;function xL(W){return encodeURIComponent(c$(W))}XY.escapeFragment=xL;function c$(W){if(typeof W=="number")return`${W}`;return W.replace(/~/g,"~0").replace(/\//g,"~1")}XY.escapeJsonPointer=c$;function $Y(W){return W.replace(/~1/g,"/").replace(/~0/g,"~")}XY.unescapeJsonPointer=$Y;function hL(W,$){if(Array.isArray(W))for(let Q of W)$(Q);else $(W)}XY.eachItem=hL;function sw({mergeNames:W,mergeToName:$,mergeValues:Q,resultToName:G}){return(X,J,w,Y)=>{let b=w===void 0?J:w instanceof a.Name?(J instanceof a.Name?W(X,J,w):$(X,J,w),w):J instanceof a.Name?($(X,w,J),J):Q(J,w);return Y===a.Name&&!(b instanceof a.Name)?G(X,b):b}}XY.mergeEvaluated={props:sw({mergeNames:(W,$,Q)=>W.if(a._`${Q} !== true && ${$} !== undefined`,()=>{W.if(a._`${$} === true`,()=>W.assign(Q,!0),()=>W.assign(Q,a._`${Q} || {}`).code(a._`Object.assign(${Q}, ${$})`))}),mergeToName:(W,$,Q)=>W.if(a._`${Q} !== true`,()=>{if($===!0)W.assign(Q,!0);else W.assign(Q,a._`${Q} || {}`),m$(W,Q,$)}),mergeValues:(W,$)=>W===!0?!0:{...W,...$},resultToName:QY}),items:sw({mergeNames:(W,$,Q)=>W.if(a._`${Q} !== true && ${$} !== undefined`,()=>W.assign(Q,a._`${$} === true ? true : ${Q} > ${$} ? ${Q} : ${$}`)),mergeToName:(W,$,Q)=>W.if(a._`${Q} !== true`,()=>W.assign(Q,$===!0?!0:a._`${Q} > ${$} ? ${Q} : ${$}`)),mergeValues:(W,$)=>W===!0?!0:Math.max(W,$),resultToName:(W,$)=>W.var("items",$)})};function QY(W,$){if($===!0)return W.var("props",!0);let Q=W.var("props",a._`{}`);if($!==void 0)m$(W,Q,$);return Q}XY.evaluatedPropsToName=QY;function m$(W,$,Q){Object.keys(Q).forEach((G)=>W.assign(a._`${$}${(0,a.getProperty)(G)}`,!0))}XY.setEvaluated=m$;var aw={};function yL(W,$){return W.scopeValue("func",{ref:$,code:aw[$.code]||(aw[$.code]=new RL._Code($.code))})}XY.useFunc=yL;var u$;(function(W){W[W.Num=0]="Num",W[W.Str=1]="Str"})(u$||(XY.Type=u$={}));function fL(W,$,Q){if(W instanceof a.Name){let G=$===u$.Num;return Q?G?a._`"[" + ${W} + "]"`:a._`"['" + ${W} + "']"`:G?a._`"/" + ${W}`:a._`"/" + ${W}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Q?(0,a.getProperty)(W).toString():"/"+c$(W)}XY.getErrorPath=fL;function GY(W,$,Q=W.opts.strictSchema){if(!Q)return;if($=`strict mode: ${$}`,Q===!0)throw Error($);W.self.logger.warn($)}XY.checkStrictMode=GY});var F1=N((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});var V0=g(),QB={data:new V0.Name("data"),valCxt:new V0.Name("valCxt"),instancePath:new V0.Name("instancePath"),parentData:new V0.Name("parentData"),parentDataProperty:new V0.Name("parentDataProperty"),rootData:new V0.Name("rootData"),dynamicAnchors:new V0.Name("dynamicAnchors"),vErrors:new V0.Name("vErrors"),errors:new V0.Name("errors"),this:new V0.Name("this"),self:new V0.Name("self"),scope:new V0.Name("scope"),json:new V0.Name("json"),jsonPos:new V0.Name("jsonPos"),jsonLen:new V0.Name("jsonLen"),jsonPart:new V0.Name("jsonPart")};wY.default=QB});var J4=N((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.extendErrors=zY.resetErrorsCount=zY.reportExtraError=zY.reportError=zY.keyword$DataError=zY.keywordError=void 0;var d=g(),EW=t(),M0=F1();zY.keywordError={message:({keyword:W})=>d.str`must pass "${W}" keyword validation`};zY.keyword$DataError={message:({keyword:W,schemaType:$})=>$?d.str`"${W}" keyword must be ${$} ($data)`:d.str`"${W}" keyword is invalid ($data)`};function XB(W,$=zY.keywordError,Q,G){let{it:X}=W,{gen:J,compositeRule:w,allErrors:Y}=X,b=HY(W,$,Q);if(G!==null&&G!==void 0?G:w||Y)YY(J,b);else bY(X,d._`[${b}]`)}zY.reportError=XB;function JB(W,$=zY.keywordError,Q){let{it:G}=W,{gen:X,compositeRule:J,allErrors:w}=G,Y=HY(W,$,Q);if(YY(X,Y),!(J||w))bY(G,M0.default.vErrors)}zY.reportExtraError=JB;function wB(W,$){W.assign(M0.default.errors,$),W.if(d._`${M0.default.vErrors} !== null`,()=>W.if($,()=>W.assign(d._`${M0.default.vErrors}.length`,$),()=>W.assign(M0.default.vErrors,null)))}zY.resetErrorsCount=wB;function YB({gen:W,keyword:$,schemaValue:Q,data:G,errsCount:X,it:J}){if(X===void 0)throw Error("ajv implementation error");let w=W.name("err");W.forRange("i",X,M0.default.errors,(Y)=>{if(W.const(w,d._`${M0.default.vErrors}[${Y}]`),W.if(d._`${w}.instancePath === undefined`,()=>W.assign(d._`${w}.instancePath`,(0,d.strConcat)(M0.default.instancePath,J.errorPath))),W.assign(d._`${w}.schemaPath`,d.str`${J.errSchemaPath}/${$}`),J.opts.verbose)W.assign(d._`${w}.schema`,Q),W.assign(d._`${w}.data`,G)})}zY.extendErrors=YB;function YY(W,$){let Q=W.const("err",$);W.if(d._`${M0.default.vErrors} === null`,()=>W.assign(M0.default.vErrors,d._`[${Q}]`),d._`${M0.default.vErrors}.push(${Q})`),W.code(d._`${M0.default.errors}++`)}function bY(W,$){let{gen:Q,validateName:G,schemaEnv:X}=W;if(X.$async)Q.throw(d._`new ${W.ValidationError}(${$})`);else Q.assign(d._`${G}.errors`,$),Q.return(!1)}var l1={keyword:new d.Name("keyword"),schemaPath:new d.Name("schemaPath"),params:new d.Name("params"),propertyName:new d.Name("propertyName"),message:new d.Name("message"),schema:new d.Name("schema"),parentSchema:new d.Name("parentSchema")};function HY(W,$,Q){let{createErrors:G}=W.it;if(G===!1)return d._`{}`;return bB(W,$,Q)}function bB(W,$,Q={}){let{gen:G,it:X}=W,J=[HB(X,Q),zB(W,Q)];return DB(W,$,J),G.object(...J)}function HB({errorPath:W},{instancePath:$}){let Q=$?d.str`${W}${(0,EW.getErrorPath)($,EW.Type.Str)}`:W;return[M0.default.instancePath,(0,d.strConcat)(M0.default.instancePath,Q)]}function zB({keyword:W,it:{errSchemaPath:$}},{schemaPath:Q,parentSchema:G}){let X=G?$:d.str`${$}/${W}`;if(Q)X=d.str`${X}${(0,EW.getErrorPath)(Q,EW.Type.Str)}`;return[l1.schemaPath,X]}function DB(W,{params:$,message:Q},G){let{keyword:X,data:J,schemaValue:w,it:Y}=W,{opts:b,propertyName:H,topSchemaRef:z,schemaPath:F}=Y;if(G.push([l1.keyword,X],[l1.params,typeof $=="function"?$(W):$||d._`{}`]),b.messages)G.push([l1.message,typeof Q=="function"?Q(W):Q]);if(b.verbose)G.push([l1.schema,w],[l1.parentSchema,d._`${z}${F}`],[M0.default.data,J]);if(H)G.push([l1.propertyName,H])}});var BY=N((UY)=>{Object.defineProperty(UY,"__esModule",{value:!0});UY.boolOrEmptySchema=UY.topBoolOrEmptySchema=void 0;var AB=J4(),OB=g(),ZB=F1(),KB={message:"boolean schema is false"};function PB(W){let{gen:$,schema:Q,validateName:G}=W;if(Q===!1)FY(W,!1);else if(typeof Q=="object"&&Q.$async===!0)$.return(ZB.default.data);else $.assign(OB._`${G}.errors`,null),$.return(!0)}UY.topBoolOrEmptySchema=PB;function VB(W,$){let{gen:Q,schema:G}=W;if(G===!1)Q.var($,!1),FY(W);else Q.var($,!0)}UY.boolOrEmptySchema=VB;function FY(W,$){let{gen:Q,data:G}=W,X={gen:Q,keyword:"false schema",data:G,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:W};(0,AB.reportError)(X,KB,void 0,$)}});var g$=N((AY)=>{Object.defineProperty(AY,"__esModule",{value:!0});AY.getRules=AY.isJSONType=void 0;var MB=["string","number","integer","boolean","null","object","array"],qB=new Set(MB);function IB(W){return typeof W=="string"&&qB.has(W)}AY.isJSONType=IB;function NB(){let W={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...W,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},W.number,W.string,W.array,W.object],post:{rules:[]},all:{},keywords:{}}}AY.getRules=NB});var p$=N((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.shouldUseRule=PY.shouldUseGroup=PY.schemaHasRulesForType=void 0;function TB({schema:W,self:$},Q){let G=$.RULES.types[Q];return G&&G!==!0&&ZY(W,G)}PY.schemaHasRulesForType=TB;function ZY(W,$){return $.rules.some((Q)=>KY(W,Q))}PY.shouldUseGroup=ZY;function KY(W,$){var Q;return W[$.keyword]!==void 0||((Q=$.definition.implements)===null||Q===void 0?void 0:Q.some((G)=>W[G]!==void 0))}PY.shouldUseRule=KY});var w4=N((IY)=>{Object.defineProperty(IY,"__esModule",{value:!0});IY.reportTypeError=IY.checkDataTypes=IY.checkDataType=IY.coerceAndCheckDataType=IY.getJSONTypes=IY.getSchemaTypes=IY.DataType=void 0;var CB=g$(),kB=p$(),vB=J4(),m=g(),jY=t(),z6;(function(W){W[W.Correct=0]="Correct",W[W.Wrong=1]="Wrong"})(z6||(IY.DataType=z6={}));function _B(W){let $=MY(W.type);if($.includes("null")){if(W.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!$.length&&W.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(W.nullable===!0)$.push("null")}return $}IY.getSchemaTypes=_B;function MY(W){let $=Array.isArray(W)?W:W?[W]:[];if($.every(CB.isJSONType))return $;throw Error("type must be JSONType or JSONType[]: "+$.join(","))}IY.getJSONTypes=MY;function xB(W,$){let{gen:Q,data:G,opts:X}=W,J=hB($,X.coerceTypes),w=$.length>0&&!(J.length===0&&$.length===1&&(0,kB.schemaHasRulesForType)(W,$[0]));if(w){let Y=n$($,G,X.strictNumbers,z6.Wrong);Q.if(Y,()=>{if(J.length)yB(W,$,J);else d$(W)})}return w}IY.coerceAndCheckDataType=xB;var qY=new Set(["string","number","integer","boolean","null"]);function hB(W,$){return $?W.filter((Q)=>qY.has(Q)||$==="array"&&Q==="array"):[]}function yB(W,$,Q){let{gen:G,data:X,opts:J}=W,w=G.let("dataType",m._`typeof ${X}`),Y=G.let("coerced",m._`undefined`);if(J.coerceTypes==="array")G.if(m._`${w} == 'object' && Array.isArray(${X}) && ${X}.length == 1`,()=>G.assign(X,m._`${X}[0]`).assign(w,m._`typeof ${X}`).if(n$($,X,J.strictNumbers),()=>G.assign(Y,X)));G.if(m._`${Y} !== undefined`);for(let H of Q)if(qY.has(H)||H==="array"&&J.coerceTypes==="array")b(H);G.else(),d$(W),G.endIf(),G.if(m._`${Y} !== undefined`,()=>{G.assign(X,Y),fB(W,Y)});function b(H){switch(H){case"string":G.elseIf(m._`${w} == "number" || ${w} == "boolean"`).assign(Y,m._`"" + ${X}`).elseIf(m._`${X} === null`).assign(Y,m._`""`);return;case"number":G.elseIf(m._`${w} == "boolean" || ${X} === null
|
|
4
|
+
|| (${w} == "string" && ${X} && ${X} == +${X})`).assign(Y,m._`+${X}`);return;case"integer":G.elseIf(m._`${w} === "boolean" || ${X} === null
|
|
5
|
+
|| (${w} === "string" && ${X} && ${X} == +${X} && !(${X} % 1))`).assign(Y,m._`+${X}`);return;case"boolean":G.elseIf(m._`${X} === "false" || ${X} === 0 || ${X} === null`).assign(Y,!1).elseIf(m._`${X} === "true" || ${X} === 1`).assign(Y,!0);return;case"null":G.elseIf(m._`${X} === "" || ${X} === 0 || ${X} === false`),G.assign(Y,null);return;case"array":G.elseIf(m._`${w} === "string" || ${w} === "number"
|
|
6
|
+
|| ${w} === "boolean" || ${X} === null`).assign(Y,m._`[${X}]`)}}}function fB({gen:W,parentData:$,parentDataProperty:Q},G){W.if(m._`${$} !== undefined`,()=>W.assign(m._`${$}[${Q}]`,G))}function i$(W,$,Q,G=z6.Correct){let X=G===z6.Correct?m.operators.EQ:m.operators.NEQ,J;switch(W){case"null":return m._`${$} ${X} null`;case"array":J=m._`Array.isArray(${$})`;break;case"object":J=m._`${$} && typeof ${$} == "object" && !Array.isArray(${$})`;break;case"integer":J=w(m._`!(${$} % 1) && !isNaN(${$})`);break;case"number":J=w();break;default:return m._`typeof ${$} ${X} ${W}`}return G===z6.Correct?J:(0,m.not)(J);function w(Y=m.nil){return(0,m.and)(m._`typeof ${$} == "number"`,Y,Q?m._`isFinite(${$})`:m.nil)}}IY.checkDataType=i$;function n$(W,$,Q,G){if(W.length===1)return i$(W[0],$,Q,G);let X,J=(0,jY.toHash)(W);if(J.array&&J.object){let w=m._`typeof ${$} != "object"`;X=J.null?w:m._`!${$} || ${w}`,delete J.null,delete J.array,delete J.object}else X=m.nil;if(J.number)delete J.integer;for(let w in J)X=(0,m.and)(X,i$(w,$,Q,G));return X}IY.checkDataTypes=n$;var uB={message:({schema:W})=>`must be ${W}`,params:({schema:W,schemaValue:$})=>typeof W=="string"?m._`{type: ${W}}`:m._`{type: ${$}}`};function d$(W){let $=cB(W);(0,vB.reportError)($,uB)}IY.reportTypeError=d$;function cB(W){let{gen:$,data:Q,schema:G}=W,X=(0,jY.schemaRefOrVal)(W,G,"type");return{gen:$,keyword:"type",data:Q,schema:G.type,schemaCode:X,schemaValue:X,parentSchema:G,params:{},it:W}}});var SY=N((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});TY.assignDefaults=void 0;var D6=g(),dB=t();function oB(W,$){let{properties:Q,items:G}=W.schema;if($==="object"&&Q)for(let X in Q)EY(W,X,Q[X].default);else if($==="array"&&Array.isArray(G))G.forEach((X,J)=>EY(W,J,X.default))}TY.assignDefaults=oB;function EY(W,$,Q){let{gen:G,compositeRule:X,data:J,opts:w}=W;if(Q===void 0)return;let Y=D6._`${J}${(0,D6.getProperty)($)}`;if(X){(0,dB.checkStrictMode)(W,`default is ignored for: ${Y}`);return}let b=D6._`${Y} === undefined`;if(w.useDefaults==="empty")b=D6._`${b} || ${Y} === null || ${Y} === ""`;G.if(b,D6._`${Y} = ${(0,D6.stringify)(Q)}`)}});var m0=N((vY)=>{Object.defineProperty(vY,"__esModule",{value:!0});vY.validateUnion=vY.validateArray=vY.usePattern=vY.callValidateCode=vY.schemaProperties=vY.allSchemaProperties=vY.noPropertyInData=vY.propertyInData=vY.isOwnProperty=vY.hasPropFunc=vY.reportMissingProp=vY.checkMissingProp=vY.checkReportMissingProp=void 0;var Q0=g(),o$=t(),v1=F1(),tB=t();function rB(W,$){let{gen:Q,data:G,it:X}=W;Q.if(r$(Q,G,$,X.opts.ownProperties),()=>{W.setParams({missingProperty:Q0._`${$}`},!0),W.error()})}vY.checkReportMissingProp=rB;function sB({gen:W,data:$,it:{opts:Q}},G,X){return(0,Q0.or)(...G.map((J)=>(0,Q0.and)(r$(W,$,J,Q.ownProperties),Q0._`${X} = ${J}`)))}vY.checkMissingProp=sB;function aB(W,$){W.setParams({missingProperty:$},!0),W.error()}vY.reportMissingProp=aB;function CY(W){return W.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Q0._`Object.prototype.hasOwnProperty`})}vY.hasPropFunc=CY;function t$(W,$,Q){return Q0._`${CY(W)}.call(${$}, ${Q})`}vY.isOwnProperty=t$;function eB(W,$,Q,G){let X=Q0._`${$}${(0,Q0.getProperty)(Q)} !== undefined`;return G?Q0._`${X} && ${t$(W,$,Q)}`:X}vY.propertyInData=eB;function r$(W,$,Q,G){let X=Q0._`${$}${(0,Q0.getProperty)(Q)} === undefined`;return G?(0,Q0.or)(X,(0,Q0.not)(t$(W,$,Q))):X}vY.noPropertyInData=r$;function kY(W){return W?Object.keys(W).filter(($)=>$!=="__proto__"):[]}vY.allSchemaProperties=kY;function WA(W,$){return kY($).filter((Q)=>!(0,o$.alwaysValidSchema)(W,$[Q]))}vY.schemaProperties=WA;function $A({schemaCode:W,data:$,it:{gen:Q,topSchemaRef:G,schemaPath:X,errorPath:J},it:w},Y,b,H){let z=H?Q0._`${W}, ${$}, ${G}${X}`:$,F=[[v1.default.instancePath,(0,Q0.strConcat)(v1.default.instancePath,J)],[v1.default.parentData,w.parentData],[v1.default.parentDataProperty,w.parentDataProperty],[v1.default.rootData,v1.default.rootData]];if(w.opts.dynamicRef)F.push([v1.default.dynamicAnchors,v1.default.dynamicAnchors]);let U=Q0._`${z}, ${Q.object(...F)}`;return b!==Q0.nil?Q0._`${Y}.call(${b}, ${U})`:Q0._`${Y}(${U})`}vY.callValidateCode=$A;var QA=Q0._`new RegExp`;function GA({gen:W,it:{opts:$}},Q){let G=$.unicodeRegExp?"u":"",{regExp:X}=$.code,J=X(Q,G);return W.scopeValue("pattern",{key:J.toString(),ref:J,code:Q0._`${X.code==="new RegExp"?QA:(0,tB.useFunc)(W,X)}(${Q}, ${G})`})}vY.usePattern=GA;function XA(W){let{gen:$,data:Q,keyword:G,it:X}=W,J=$.name("valid");if(X.allErrors){let Y=$.let("valid",!0);return w(()=>$.assign(Y,!1)),Y}return $.var(J,!0),w(()=>$.break()),J;function w(Y){let b=$.const("len",Q0._`${Q}.length`);$.forRange("i",0,b,(H)=>{W.subschema({keyword:G,dataProp:H,dataPropType:o$.Type.Num},J),$.if((0,Q0.not)(J),Y)})}}vY.validateArray=XA;function JA(W){let{gen:$,schema:Q,keyword:G,it:X}=W;if(!Array.isArray(Q))throw Error("ajv implementation error");if(Q.some((b)=>(0,o$.alwaysValidSchema)(X,b))&&!X.opts.unevaluated)return;let w=$.let("valid",!1),Y=$.name("_valid");$.block(()=>Q.forEach((b,H)=>{let z=W.subschema({keyword:G,schemaProp:H,compositeRule:!0},Y);if($.assign(w,Q0._`${w} || ${Y}`),!W.mergeValidEvaluated(z,Y))$.if((0,Q0.not)(w))})),W.result(w,()=>W.reset(),()=>W.error(!0))}vY.validateUnion=JA});var uY=N((yY)=>{Object.defineProperty(yY,"__esModule",{value:!0});yY.validateKeywordUsage=yY.validSchemaType=yY.funcKeywordCode=yY.macroKeywordCode=void 0;var q0=g(),g1=F1(),ZA=m0(),KA=J4();function PA(W,$){let{gen:Q,keyword:G,schema:X,parentSchema:J,it:w}=W,Y=$.macro.call(w.self,X,J,w),b=hY(Q,G,Y);if(w.opts.validateSchema!==!1)w.self.validateSchema(Y,!0);let H=Q.name("valid");W.subschema({schema:Y,schemaPath:q0.nil,errSchemaPath:`${w.errSchemaPath}/${G}`,topSchemaRef:b,compositeRule:!0},H),W.pass(H,()=>W.error(!0))}yY.macroKeywordCode=PA;function VA(W,$){var Q;let{gen:G,keyword:X,schema:J,parentSchema:w,$data:Y,it:b}=W;MA(b,$);let H=!Y&&$.compile?$.compile.call(b.self,J,w,b):$.validate,z=hY(G,X,H),F=G.let("valid");W.block$data(F,U),W.ok((Q=$.valid)!==null&&Q!==void 0?Q:F);function U(){if($.errors===!1){if(P(),$.modifying)xY(W);q(()=>W.error())}else{let M=$.async?L():Z();if($.modifying)xY(W);q(()=>jA(W,M))}}function L(){let M=G.let("ruleErrs",null);return G.try(()=>P(q0._`await `),(S)=>G.assign(F,!1).if(q0._`${S} instanceof ${b.ValidationError}`,()=>G.assign(M,q0._`${S}.errors`),()=>G.throw(S))),M}function Z(){let M=q0._`${z}.errors`;return G.assign(M,null),P(q0.nil),M}function P(M=$.async?q0._`await `:q0.nil){let S=b.opts.passContext?g1.default.this:g1.default.self,C=!(("compile"in $)&&!Y||$.schema===!1);G.assign(F,q0._`${M}${(0,ZA.callValidateCode)(W,z,S,C)}`,$.modifying)}function q(M){var S;G.if((0,q0.not)((S=$.valid)!==null&&S!==void 0?S:F),M)}}yY.funcKeywordCode=VA;function xY(W){let{gen:$,data:Q,it:G}=W;$.if(G.parentData,()=>$.assign(Q,q0._`${G.parentData}[${G.parentDataProperty}]`))}function jA(W,$){let{gen:Q}=W;Q.if(q0._`Array.isArray(${$})`,()=>{Q.assign(g1.default.vErrors,q0._`${g1.default.vErrors} === null ? ${$} : ${g1.default.vErrors}.concat(${$})`).assign(g1.default.errors,q0._`${g1.default.vErrors}.length`),(0,KA.extendErrors)(W)},()=>W.error())}function MA({schemaEnv:W},$){if($.async&&!W.$async)throw Error("async keyword in sync schema")}function hY(W,$,Q){if(Q===void 0)throw Error(`keyword "${$}" failed to compile`);return W.scopeValue("keyword",typeof Q=="function"?{ref:Q}:{ref:Q,code:(0,q0.stringify)(Q)})}function qA(W,$,Q=!1){return!$.length||$.some((G)=>G==="array"?Array.isArray(W):G==="object"?W&&typeof W=="object"&&!Array.isArray(W):typeof W==G||Q&&typeof W>"u")}yY.validSchemaType=qA;function IA({schema:W,opts:$,self:Q,errSchemaPath:G},X,J){if(Array.isArray(X.keyword)?!X.keyword.includes(J):X.keyword!==J)throw Error("ajv implementation error");let w=X.dependencies;if(w===null||w===void 0?void 0:w.some((Y)=>!Object.prototype.hasOwnProperty.call(W,Y)))throw Error(`parent schema must have dependencies of ${J}: ${w.join(",")}`);if(X.validateSchema){if(!X.validateSchema(W[J])){let b=`keyword "${J}" value is invalid at path "${G}": `+Q.errorsText(X.validateSchema.errors);if($.validateSchema==="log")Q.logger.error(b);else throw Error(b)}}}yY.validateKeywordUsage=IA});var gY=N((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});mY.extendSubschemaMode=mY.extendSubschemaData=mY.getSubschema=void 0;var Q1=g(),cY=t();function RA(W,{keyword:$,schemaProp:Q,schema:G,schemaPath:X,errSchemaPath:J,topSchemaRef:w}){if($!==void 0&&G!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if($!==void 0){let Y=W.schema[$];return Q===void 0?{schema:Y,schemaPath:Q1._`${W.schemaPath}${(0,Q1.getProperty)($)}`,errSchemaPath:`${W.errSchemaPath}/${$}`}:{schema:Y[Q],schemaPath:Q1._`${W.schemaPath}${(0,Q1.getProperty)($)}${(0,Q1.getProperty)(Q)}`,errSchemaPath:`${W.errSchemaPath}/${$}/${(0,cY.escapeFragment)(Q)}`}}if(G!==void 0){if(X===void 0||J===void 0||w===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:G,schemaPath:X,topSchemaRef:w,errSchemaPath:J}}throw Error('either "keyword" or "schema" must be passed')}mY.getSubschema=RA;function SA(W,$,{dataProp:Q,dataPropType:G,data:X,dataTypes:J,propertyName:w}){if(X!==void 0&&Q!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:Y}=$;if(Q!==void 0){let{errorPath:H,dataPathArr:z,opts:F}=$,U=Y.let("data",Q1._`${$.data}${(0,Q1.getProperty)(Q)}`,!0);b(U),W.errorPath=Q1.str`${H}${(0,cY.getErrorPath)(Q,G,F.jsPropertySyntax)}`,W.parentDataProperty=Q1._`${Q}`,W.dataPathArr=[...z,W.parentDataProperty]}if(X!==void 0){let H=X instanceof Q1.Name?X:Y.let("data",X,!0);if(b(H),w!==void 0)W.propertyName=w}if(J)W.dataTypes=J;function b(H){W.data=H,W.dataLevel=$.dataLevel+1,W.dataTypes=[],$.definedProperties=new Set,W.parentData=$.data,W.dataNames=[...$.dataNames,H]}}mY.extendSubschemaData=SA;function CA(W,{jtdDiscriminator:$,jtdMetadata:Q,compositeRule:G,createErrors:X,allErrors:J}){if(G!==void 0)W.compositeRule=G;if(X!==void 0)W.createErrors=X;if(J!==void 0)W.allErrors=J;W.jtdDiscriminator=$,W.jtdMetadata=Q}mY.extendSubschemaMode=CA});var s$=N((cR,pY)=>{pY.exports=function W($,Q){if($===Q)return!0;if($&&Q&&typeof $=="object"&&typeof Q=="object"){if($.constructor!==Q.constructor)return!1;var G,X,J;if(Array.isArray($)){if(G=$.length,G!=Q.length)return!1;for(X=G;X--!==0;)if(!W($[X],Q[X]))return!1;return!0}if($.constructor===RegExp)return $.source===Q.source&&$.flags===Q.flags;if($.valueOf!==Object.prototype.valueOf)return $.valueOf()===Q.valueOf();if($.toString!==Object.prototype.toString)return $.toString()===Q.toString();if(J=Object.keys($),G=J.length,G!==Object.keys(Q).length)return!1;for(X=G;X--!==0;)if(!Object.prototype.hasOwnProperty.call(Q,J[X]))return!1;for(X=G;X--!==0;){var w=J[X];if(!W($[w],Q[w]))return!1}return!0}return $!==$&&Q!==Q}});var nY=N((mR,iY)=>{var _1=iY.exports=function(W,$,Q){if(typeof $=="function")Q=$,$={};Q=$.cb||Q;var G=typeof Q=="function"?Q:Q.pre||function(){},X=Q.post||function(){};TW($,G,X,W,"",W)};_1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};_1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};_1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};_1.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function TW(W,$,Q,G,X,J,w,Y,b,H){if(G&&typeof G=="object"&&!Array.isArray(G)){$(G,X,J,w,Y,b,H);for(var z in G){var F=G[z];if(Array.isArray(F)){if(z in _1.arrayKeywords)for(var U=0;U<F.length;U++)TW(W,$,Q,F[U],X+"/"+z+"/"+U,J,X,z,G,U)}else if(z in _1.propsKeywords){if(F&&typeof F=="object")for(var L in F)TW(W,$,Q,F[L],X+"/"+z+"/"+_A(L),J,X,z,G,L)}else if(z in _1.keywords||W.allKeys&&!(z in _1.skipKeywords))TW(W,$,Q,F,X+"/"+z,J,X,z,G)}Q(G,X,J,w,Y,b,H)}}function _A(W){return W.replace(/~/g,"~0").replace(/\//g,"~1")}});var Y4=N((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});rY.getSchemaRefs=rY.resolveUrl=rY.normalizeId=rY._getFullPath=rY.getFullPath=rY.inlineRef=void 0;var xA=t(),hA=s$(),yA=nY(),fA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function uA(W,$=!0){if(typeof W=="boolean")return!0;if($===!0)return!a$(W);if(!$)return!1;return dY(W)<=$}rY.inlineRef=uA;var cA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a$(W){for(let $ in W){if(cA.has($))return!0;let Q=W[$];if(Array.isArray(Q)&&Q.some(a$))return!0;if(typeof Q=="object"&&a$(Q))return!0}return!1}function dY(W){let $=0;for(let Q in W){if(Q==="$ref")return 1/0;if($++,fA.has(Q))continue;if(typeof W[Q]=="object")(0,xA.eachItem)(W[Q],(G)=>$+=dY(G));if($===1/0)return 1/0}return $}function oY(W,$="",Q){if(Q!==!1)$=F6($);let G=W.parse($);return tY(W,G)}rY.getFullPath=oY;function tY(W,$){return W.serialize($).split("#")[0]+"#"}rY._getFullPath=tY;var mA=/#\/?$/;function F6(W){return W?W.replace(mA,""):""}rY.normalizeId=F6;function lA(W,$,Q){return Q=F6(Q),W.resolve($,Q)}rY.resolveUrl=lA;var gA=/^[a-z_][-a-z0-9._]*$/i;function pA(W,$){if(typeof W=="boolean")return{};let{schemaId:Q,uriResolver:G}=this.opts,X=F6(W[Q]||$),J={"":X},w=oY(G,X,!1),Y={},b=new Set;return yA(W,{allKeys:!0},(F,U,L,Z)=>{if(Z===void 0)return;let P=w+U,q=J[Z];if(typeof F[Q]=="string")q=M.call(this,F[Q]);S.call(this,F.$anchor),S.call(this,F.$dynamicAnchor),J[U]=q;function M(C){let _=this.opts.uriResolver.resolve;if(C=F6(q?_(q,C):C),b.has(C))throw z(C);b.add(C);let k=this.refs[C];if(typeof k=="string")k=this.refs[k];if(typeof k=="object")H(F,k.schema,C);else if(C!==F6(P))if(C[0]==="#")H(F,Y[C],C),Y[C]=F;else this.refs[C]=P;return C}function S(C){if(typeof C=="string"){if(!gA.test(C))throw Error(`invalid anchor "${C}"`);M.call(this,`#${C}`)}}}),Y;function H(F,U,L){if(U!==void 0&&!hA(F,U))throw z(L)}function z(F){return Error(`reference "${F}" resolves to more than one schema`)}}rY.getSchemaRefs=pA});var z4=N((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});F7.getData=F7.KeywordCxt=F7.validateFunctionCode=void 0;var Q7=BY(),aY=w4(),W8=p$(),RW=w4(),rA=SY(),H4=uY(),e$=gY(),R=g(),f=F1(),sA=Y4(),U1=t(),b4=J4();function aA(W){if(J7(W)){if(w7(W),X7(W)){$O(W);return}}G7(W,()=>(0,Q7.topBoolOrEmptySchema)(W))}F7.validateFunctionCode=aA;function G7({gen:W,validateName:$,schema:Q,schemaEnv:G,opts:X},J){if(X.code.es5)W.func($,R._`${f.default.data}, ${f.default.valCxt}`,G.$async,()=>{W.code(R._`"use strict"; ${eY(Q,X)}`),WO(W,X),W.code(J)});else W.func($,R._`${f.default.data}, ${eA(X)}`,G.$async,()=>W.code(eY(Q,X)).code(J))}function eA(W){return R._`{${f.default.instancePath}="", ${f.default.parentData}, ${f.default.parentDataProperty}, ${f.default.rootData}=${f.default.data}${W.dynamicRef?R._`, ${f.default.dynamicAnchors}={}`:R.nil}}={}`}function WO(W,$){W.if(f.default.valCxt,()=>{if(W.var(f.default.instancePath,R._`${f.default.valCxt}.${f.default.instancePath}`),W.var(f.default.parentData,R._`${f.default.valCxt}.${f.default.parentData}`),W.var(f.default.parentDataProperty,R._`${f.default.valCxt}.${f.default.parentDataProperty}`),W.var(f.default.rootData,R._`${f.default.valCxt}.${f.default.rootData}`),$.dynamicRef)W.var(f.default.dynamicAnchors,R._`${f.default.valCxt}.${f.default.dynamicAnchors}`)},()=>{if(W.var(f.default.instancePath,R._`""`),W.var(f.default.parentData,R._`undefined`),W.var(f.default.parentDataProperty,R._`undefined`),W.var(f.default.rootData,f.default.data),$.dynamicRef)W.var(f.default.dynamicAnchors,R._`{}`)})}function $O(W){let{schema:$,opts:Q,gen:G}=W;G7(W,()=>{if(Q.$comment&&$.$comment)b7(W);if(wO(W),G.let(f.default.vErrors,null),G.let(f.default.errors,0),Q.unevaluated)QO(W);Y7(W),HO(W)});return}function QO(W){let{gen:$,validateName:Q}=W;W.evaluated=$.const("evaluated",R._`${Q}.evaluated`),$.if(R._`${W.evaluated}.dynamicProps`,()=>$.assign(R._`${W.evaluated}.props`,R._`undefined`)),$.if(R._`${W.evaluated}.dynamicItems`,()=>$.assign(R._`${W.evaluated}.items`,R._`undefined`))}function eY(W,$){let Q=typeof W=="object"&&W[$.schemaId];return Q&&($.code.source||$.code.process)?R._`/*# sourceURL=${Q} */`:R.nil}function GO(W,$){if(J7(W)){if(w7(W),X7(W)){XO(W,$);return}}(0,Q7.boolOrEmptySchema)(W,$)}function X7({schema:W,self:$}){if(typeof W=="boolean")return!W;for(let Q in W)if($.RULES.all[Q])return!0;return!1}function J7(W){return typeof W.schema!="boolean"}function XO(W,$){let{schema:Q,gen:G,opts:X}=W;if(X.$comment&&Q.$comment)b7(W);YO(W),bO(W);let J=G.const("_errs",f.default.errors);Y7(W,J),G.var($,R._`${J} === ${f.default.errors}`)}function w7(W){(0,U1.checkUnknownRules)(W),JO(W)}function Y7(W,$){if(W.opts.jtd)return W7(W,[],!1,$);let Q=(0,aY.getSchemaTypes)(W.schema),G=(0,aY.coerceAndCheckDataType)(W,Q);W7(W,Q,!G,$)}function JO(W){let{schema:$,errSchemaPath:Q,opts:G,self:X}=W;if($.$ref&&G.ignoreKeywordsWithRef&&(0,U1.schemaHasRulesButRef)($,X.RULES))X.logger.warn(`$ref: keywords ignored in schema at path "${Q}"`)}function wO(W){let{schema:$,opts:Q}=W;if($.default!==void 0&&Q.useDefaults&&Q.strictSchema)(0,U1.checkStrictMode)(W,"default is ignored in the schema root")}function YO(W){let $=W.schema[W.opts.schemaId];if($)W.baseId=(0,sA.resolveUrl)(W.opts.uriResolver,W.baseId,$)}function bO(W){if(W.schema.$async&&!W.schemaEnv.$async)throw Error("async schema in sync schema")}function b7({gen:W,schemaEnv:$,schema:Q,errSchemaPath:G,opts:X}){let J=Q.$comment;if(X.$comment===!0)W.code(R._`${f.default.self}.logger.log(${J})`);else if(typeof X.$comment=="function"){let w=R.str`${G}/$comment`,Y=W.scopeValue("root",{ref:$.root});W.code(R._`${f.default.self}.opts.$comment(${J}, ${w}, ${Y}.schema)`)}}function HO(W){let{gen:$,schemaEnv:Q,validateName:G,ValidationError:X,opts:J}=W;if(Q.$async)$.if(R._`${f.default.errors} === 0`,()=>$.return(f.default.data),()=>$.throw(R._`new ${X}(${f.default.vErrors})`));else{if($.assign(R._`${G}.errors`,f.default.vErrors),J.unevaluated)zO(W);$.return(R._`${f.default.errors} === 0`)}}function zO({gen:W,evaluated:$,props:Q,items:G}){if(Q instanceof R.Name)W.assign(R._`${$}.props`,Q);if(G instanceof R.Name)W.assign(R._`${$}.items`,G)}function W7(W,$,Q,G){let{gen:X,schema:J,data:w,allErrors:Y,opts:b,self:H}=W,{RULES:z}=H;if(J.$ref&&(b.ignoreKeywordsWithRef||!(0,U1.schemaHasRulesButRef)(J,z))){X.block(()=>z7(W,"$ref",z.all.$ref.definition));return}if(!b.jtd)DO(W,$);X.block(()=>{for(let U of z.rules)F(U);F(z.post)});function F(U){if(!(0,W8.shouldUseGroup)(J,U))return;if(U.type){if(X.if((0,RW.checkDataType)(U.type,w,b.strictNumbers)),$7(W,U),$.length===1&&$[0]===U.type&&Q)X.else(),(0,RW.reportTypeError)(W);X.endIf()}else $7(W,U);if(!Y)X.if(R._`${f.default.errors} === ${G||0}`)}}function $7(W,$){let{gen:Q,schema:G,opts:{useDefaults:X}}=W;if(X)(0,rA.assignDefaults)(W,$.type);Q.block(()=>{for(let J of $.rules)if((0,W8.shouldUseRule)(G,J))z7(W,J.keyword,J.definition,$.type)})}function DO(W,$){if(W.schemaEnv.meta||!W.opts.strictTypes)return;if(FO(W,$),!W.opts.allowUnionTypes)UO(W,$);LO(W,W.dataTypes)}function FO(W,$){if(!$.length)return;if(!W.dataTypes.length){W.dataTypes=$;return}$.forEach((Q)=>{if(!H7(W.dataTypes,Q))$8(W,`type "${Q}" not allowed by context "${W.dataTypes.join(",")}"`)}),AO(W,$)}function UO(W,$){if($.length>1&&!($.length===2&&$.includes("null")))$8(W,"use allowUnionTypes to allow union type keyword")}function LO(W,$){let Q=W.self.RULES.all;for(let G in Q){let X=Q[G];if(typeof X=="object"&&(0,W8.shouldUseRule)(W.schema,X)){let{type:J}=X.definition;if(J.length&&!J.some((w)=>BO($,w)))$8(W,`missing type "${J.join(",")}" for keyword "${G}"`)}}}function BO(W,$){return W.includes($)||$==="number"&&W.includes("integer")}function H7(W,$){return W.includes($)||$==="integer"&&W.includes("number")}function AO(W,$){let Q=[];for(let G of W.dataTypes)if(H7($,G))Q.push(G);else if($.includes("integer")&&G==="number")Q.push("integer");W.dataTypes=Q}function $8(W,$){let Q=W.schemaEnv.baseId+W.errSchemaPath;$+=` at "${Q}" (strictTypes)`,(0,U1.checkStrictMode)(W,$,W.opts.strictTypes)}class Q8{constructor(W,$,Q){if((0,H4.validateKeywordUsage)(W,$,Q),this.gen=W.gen,this.allErrors=W.allErrors,this.keyword=Q,this.data=W.data,this.schema=W.schema[Q],this.$data=$.$data&&W.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,U1.schemaRefOrVal)(W,this.schema,Q,this.$data),this.schemaType=$.schemaType,this.parentSchema=W.schema,this.params={},this.it=W,this.def=$,this.$data)this.schemaCode=W.gen.const("vSchema",D7(this.$data,W));else if(this.schemaCode=this.schemaValue,!(0,H4.validSchemaType)(this.schema,$.schemaType,$.allowUndefined))throw Error(`${Q} value must be ${JSON.stringify($.schemaType)}`);if("code"in $?$.trackErrors:$.errors!==!1)this.errsCount=W.gen.const("_errs",f.default.errors)}result(W,$,Q){this.failResult((0,R.not)(W),$,Q)}failResult(W,$,Q){if(this.gen.if(W),Q)Q();else this.error();if($){if(this.gen.else(),$(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(W,$){this.failResult((0,R.not)(W),void 0,$)}fail(W){if(W===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(W),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(W){if(!this.$data)return this.fail(W);let{schemaCode:$}=this;this.fail(R._`${$} !== undefined && (${(0,R.or)(this.invalid$data(),W)})`)}error(W,$,Q){if($){this.setParams($),this._error(W,Q),this.setParams({});return}this._error(W,Q)}_error(W,$){(W?b4.reportExtraError:b4.reportError)(this,this.def.error,$)}$dataError(){(0,b4.reportError)(this,this.def.$dataError||b4.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,b4.resetErrorsCount)(this.gen,this.errsCount)}ok(W){if(!this.allErrors)this.gen.if(W)}setParams(W,$){if($)Object.assign(this.params,W);else this.params=W}block$data(W,$,Q=R.nil){this.gen.block(()=>{this.check$data(W,Q),$()})}check$data(W=R.nil,$=R.nil){if(!this.$data)return;let{gen:Q,schemaCode:G,schemaType:X,def:J}=this;if(Q.if((0,R.or)(R._`${G} === undefined`,$)),W!==R.nil)Q.assign(W,!0);if(X.length||J.validateSchema){if(Q.elseIf(this.invalid$data()),this.$dataError(),W!==R.nil)Q.assign(W,!1)}Q.else()}invalid$data(){let{gen:W,schemaCode:$,schemaType:Q,def:G,it:X}=this;return(0,R.or)(J(),w());function J(){if(Q.length){if(!($ instanceof R.Name))throw Error("ajv implementation error");let Y=Array.isArray(Q)?Q:[Q];return R._`${(0,RW.checkDataTypes)(Y,$,X.opts.strictNumbers,RW.DataType.Wrong)}`}return R.nil}function w(){if(G.validateSchema){let Y=W.scopeValue("validate$data",{ref:G.validateSchema});return R._`!${Y}(${$})`}return R.nil}}subschema(W,$){let Q=(0,e$.getSubschema)(this.it,W);(0,e$.extendSubschemaData)(Q,this.it,W),(0,e$.extendSubschemaMode)(Q,W);let G={...this.it,...Q,items:void 0,props:void 0};return GO(G,$),G}mergeEvaluated(W,$){let{it:Q,gen:G}=this;if(!Q.opts.unevaluated)return;if(Q.props!==!0&&W.props!==void 0)Q.props=U1.mergeEvaluated.props(G,W.props,Q.props,$);if(Q.items!==!0&&W.items!==void 0)Q.items=U1.mergeEvaluated.items(G,W.items,Q.items,$)}mergeValidEvaluated(W,$){let{it:Q,gen:G}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return G.if($,()=>this.mergeEvaluated(W,R.Name)),!0}}F7.KeywordCxt=Q8;function z7(W,$,Q,G){let X=new Q8(W,Q,$);if("code"in Q)Q.code(X,G);else if(X.$data&&Q.validate)(0,H4.funcKeywordCode)(X,Q);else if("macro"in Q)(0,H4.macroKeywordCode)(X,Q);else if(Q.compile||Q.validate)(0,H4.funcKeywordCode)(X,Q)}var OO=/^\/(?:[^~]|~0|~1)*$/,ZO=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function D7(W,{dataLevel:$,dataNames:Q,dataPathArr:G}){let X,J;if(W==="")return f.default.rootData;if(W[0]==="/"){if(!OO.test(W))throw Error(`Invalid JSON-pointer: ${W}`);X=W,J=f.default.rootData}else{let H=ZO.exec(W);if(!H)throw Error(`Invalid JSON-pointer: ${W}`);let z=+H[1];if(X=H[2],X==="#"){if(z>=$)throw Error(b("property/index",z));return G[$-z]}if(z>$)throw Error(b("data",z));if(J=Q[$-z],!X)return J}let w=J,Y=X.split("/");for(let H of Y)if(H)J=R._`${J}${(0,R.getProperty)((0,U1.unescapeJsonPointer)(H))}`,w=R._`${w} && ${J}`;return w;function b(H,z){return`Cannot access ${H} ${z} levels up, current level is ${$}`}}F7.getData=D7});var SW=N((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});class L7 extends Error{constructor(W){super("validation failed");this.errors=W,this.ajv=this.validation=!0}}B7.default=L7});var D4=N((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});var G8=Y4();class A7 extends Error{constructor(W,$,Q,G){super(G||`can't resolve reference ${Q} from id ${$}`);this.missingRef=(0,G8.resolveUrl)(W,$,Q),this.missingSchema=(0,G8.normalizeId)((0,G8.getFullPath)(W,this.missingRef))}}O7.default=A7});var kW=N((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.resolveSchema=P7.getCompilingSchema=P7.resolveRef=P7.compileSchema=P7.SchemaEnv=void 0;var t0=g(),MO=SW(),p1=F1(),r0=Y4(),Z7=t(),qO=z4();class F4{constructor(W){var $;this.refs={},this.dynamicAnchors={};let Q;if(typeof W.schema=="object")Q=W.schema;this.schema=W.schema,this.schemaId=W.schemaId,this.root=W.root||this,this.baseId=($=W.baseId)!==null&&$!==void 0?$:(0,r0.normalizeId)(Q===null||Q===void 0?void 0:Q[W.schemaId||"$id"]),this.schemaPath=W.schemaPath,this.localRefs=W.localRefs,this.meta=W.meta,this.$async=Q===null||Q===void 0?void 0:Q.$async,this.refs={}}}P7.SchemaEnv=F4;function J8(W){let $=K7.call(this,W);if($)return $;let Q=(0,r0.getFullPath)(this.opts.uriResolver,W.root.baseId),{es5:G,lines:X}=this.opts.code,{ownProperties:J}=this.opts,w=new t0.CodeGen(this.scope,{es5:G,lines:X,ownProperties:J}),Y;if(W.$async)Y=w.scopeValue("Error",{ref:MO.default,code:t0._`require("ajv/dist/runtime/validation_error").default`});let b=w.scopeName("validate");W.validateName=b;let H={gen:w,allErrors:this.opts.allErrors,data:p1.default.data,parentData:p1.default.parentData,parentDataProperty:p1.default.parentDataProperty,dataNames:[p1.default.data],dataPathArr:[t0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:w.scopeValue("schema",this.opts.code.source===!0?{ref:W.schema,code:(0,t0.stringify)(W.schema)}:{ref:W.schema}),validateName:b,ValidationError:Y,schema:W.schema,schemaEnv:W,rootId:Q,baseId:W.baseId||Q,schemaPath:t0.nil,errSchemaPath:W.schemaPath||(this.opts.jtd?"":"#"),errorPath:t0._`""`,opts:this.opts,self:this},z;try{this._compilations.add(W),(0,qO.validateFunctionCode)(H),w.optimize(this.opts.code.optimize);let F=w.toString();if(z=`${w.scopeRefs(p1.default.scope)}return ${F}`,this.opts.code.process)z=this.opts.code.process(z,W);let L=Function(`${p1.default.self}`,`${p1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(b,{ref:L}),L.errors=null,L.schema=W.schema,L.schemaEnv=W,W.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:b,validateCode:F,scopeValues:w._values};if(this.opts.unevaluated){let{props:Z,items:P}=H;if(L.evaluated={props:Z instanceof t0.Name?void 0:Z,items:P instanceof t0.Name?void 0:P,dynamicProps:Z instanceof t0.Name,dynamicItems:P instanceof t0.Name},L.source)L.source.evaluated=(0,t0.stringify)(L.evaluated)}return W.validate=L,W}catch(F){if(delete W.validate,delete W.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw F}finally{this._compilations.delete(W)}}P7.compileSchema=J8;function IO(W,$,Q){var G;Q=(0,r0.resolveUrl)(this.opts.uriResolver,$,Q);let X=W.refs[Q];if(X)return X;let J=TO.call(this,W,Q);if(J===void 0){let w=(G=W.localRefs)===null||G===void 0?void 0:G[Q],{schemaId:Y}=this.opts;if(w)J=new F4({schema:w,schemaId:Y,root:W,baseId:$})}if(J===void 0)return;return W.refs[Q]=NO.call(this,J)}P7.resolveRef=IO;function NO(W){if((0,r0.inlineRef)(W.schema,this.opts.inlineRefs))return W.schema;return W.validate?W:J8.call(this,W)}function K7(W){for(let $ of this._compilations)if(EO($,W))return $}P7.getCompilingSchema=K7;function EO(W,$){return W.schema===$.schema&&W.root===$.root&&W.baseId===$.baseId}function TO(W,$){let Q;while(typeof(Q=this.refs[$])=="string")$=Q;return Q||this.schemas[$]||CW.call(this,W,$)}function CW(W,$){let Q=this.opts.uriResolver.parse($),G=(0,r0._getFullPath)(this.opts.uriResolver,Q),X=(0,r0.getFullPath)(this.opts.uriResolver,W.baseId,void 0);if(Object.keys(W.schema).length>0&&G===X)return X8.call(this,Q,W);let J=(0,r0.normalizeId)(G),w=this.refs[J]||this.schemas[J];if(typeof w=="string"){let Y=CW.call(this,W,w);if(typeof(Y===null||Y===void 0?void 0:Y.schema)!=="object")return;return X8.call(this,Q,Y)}if(typeof(w===null||w===void 0?void 0:w.schema)!=="object")return;if(!w.validate)J8.call(this,w);if(J===(0,r0.normalizeId)($)){let{schema:Y}=w,{schemaId:b}=this.opts,H=Y[b];if(H)X=(0,r0.resolveUrl)(this.opts.uriResolver,X,H);return new F4({schema:Y,schemaId:b,root:W,baseId:X})}return X8.call(this,Q,w)}P7.resolveSchema=CW;var RO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function X8(W,{baseId:$,schema:Q,root:G}){var X;if(((X=W.fragment)===null||X===void 0?void 0:X[0])!=="/")return;for(let Y of W.fragment.slice(1).split("/")){if(typeof Q==="boolean")return;let b=Q[(0,Z7.unescapeFragment)(Y)];if(b===void 0)return;Q=b;let H=typeof Q==="object"&&Q[this.opts.schemaId];if(!RO.has(Y)&&H)$=(0,r0.resolveUrl)(this.opts.uriResolver,$,H)}let J;if(typeof Q!="boolean"&&Q.$ref&&!(0,Z7.schemaHasRulesButRef)(Q,this.RULES)){let Y=(0,r0.resolveUrl)(this.opts.uriResolver,$,Q.$ref);J=CW.call(this,G,Y)}let{schemaId:w}=this.opts;if(J=J||new F4({schema:Q,schemaId:w,root:G,baseId:$}),J.schema!==J.root.schema)return J;return}});var j7=N((dR,_O)=>{_O.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Y8=N((oR,N7)=>{var xO=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),q7=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function w8(W){let $="",Q=0,G=0;for(G=0;G<W.length;G++){if(Q=W[G].charCodeAt(0),Q===48)continue;if(!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";$+=W[G];break}for(G+=1;G<W.length;G++){if(Q=W[G].charCodeAt(0),!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";$+=W[G]}return $}var hO=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function M7(W){return W.length=0,!0}function yO(W,$,Q){if(W.length){let G=w8(W);if(G!=="")$.push(G);else return Q.error=!0,!1;W.length=0}return!0}function fO(W){let $=0,Q={error:!1,address:"",zone:""},G=[],X=[],J=!1,w=!1,Y=yO;for(let b=0;b<W.length;b++){let H=W[b];if(H==="["||H==="]")continue;if(H===":"){if(J===!0)w=!0;if(!Y(X,G,Q))break;if(++$>7){Q.error=!0;break}if(b>0&&W[b-1]===":")J=!0;G.push(":");continue}else if(H==="%"){if(!Y(X,G,Q))break;Y=M7}else{X.push(H);continue}}if(X.length)if(Y===M7)Q.zone=X.join("");else if(w)G.push(X.join(""));else G.push(w8(X));return Q.address=G.join(""),Q}function I7(W){if(uO(W,":")<2)return{host:W,isIPV6:!1};let $=fO(W);if(!$.error){let{address:Q,address:G}=$;if($.zone)Q+="%"+$.zone,G+="%25"+$.zone;return{host:Q,isIPV6:!0,escapedHost:G}}else return{host:W,isIPV6:!1}}function uO(W,$){let Q=0;for(let G=0;G<W.length;G++)if(W[G]===$)Q++;return Q}function cO(W){let $=W,Q=[],G=-1,X=0;while(X=$.length){if(X===1)if($===".")break;else if($==="/"){Q.push("/");break}else{Q.push($);break}else if(X===2){if($[0]==="."){if($[1]===".")break;else if($[1]==="/"){$=$.slice(2);continue}}else if($[0]==="/"){if($[1]==="."||$[1]==="/"){Q.push("/");break}}}else if(X===3){if($==="/.."){if(Q.length!==0)Q.pop();Q.push("/");break}}if($[0]==="."){if($[1]==="."){if($[2]==="/"){$=$.slice(3);continue}}else if($[1]==="/"){$=$.slice(2);continue}}else if($[0]==="/"){if($[1]==="."){if($[2]==="/"){$=$.slice(2);continue}else if($[2]==="."){if($[3]==="/"){if($=$.slice(3),Q.length!==0)Q.pop();continue}}}}if((G=$.indexOf("/",1))===-1){Q.push($);break}else Q.push($.slice(0,G)),$=$.slice(G)}return Q.join("")}function mO(W,$){let Q=$!==!0?escape:unescape;if(W.scheme!==void 0)W.scheme=Q(W.scheme);if(W.userinfo!==void 0)W.userinfo=Q(W.userinfo);if(W.host!==void 0)W.host=Q(W.host);if(W.path!==void 0)W.path=Q(W.path);if(W.query!==void 0)W.query=Q(W.query);if(W.fragment!==void 0)W.fragment=Q(W.fragment);return W}function lO(W){let $=[];if(W.userinfo!==void 0)$.push(W.userinfo),$.push("@");if(W.host!==void 0){let Q=unescape(W.host);if(!q7(Q)){let G=I7(Q);if(G.isIPV6===!0)Q=`[${G.escapedHost}]`;else Q=W.host}$.push(Q)}if(typeof W.port==="number"||typeof W.port==="string")$.push(":"),$.push(String(W.port));return $.length?$.join(""):void 0}N7.exports={nonSimpleDomain:hO,recomposeAuthority:lO,normalizeComponentEncoding:mO,removeDotSegments:cO,isIPv4:q7,isUUID:xO,normalizeIPv6:I7,stringArrayToHexStripped:w8}});var C7=N((tR,S7)=>{var{isUUID:gO}=Y8(),pO=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,iO=["http","https","ws","wss","urn","urn:uuid"];function nO(W){return iO.indexOf(W)!==-1}function b8(W){if(W.secure===!0)return!0;else if(W.secure===!1)return!1;else if(W.scheme)return W.scheme.length===3&&(W.scheme[0]==="w"||W.scheme[0]==="W")&&(W.scheme[1]==="s"||W.scheme[1]==="S")&&(W.scheme[2]==="s"||W.scheme[2]==="S");else return!1}function E7(W){if(!W.host)W.error=W.error||"HTTP URIs must have a host.";return W}function T7(W){let $=String(W.scheme).toLowerCase()==="https";if(W.port===($?443:80)||W.port==="")W.port=void 0;if(!W.path)W.path="/";return W}function dO(W){return W.secure=b8(W),W.resourceName=(W.path||"/")+(W.query?"?"+W.query:""),W.path=void 0,W.query=void 0,W}function oO(W){if(W.port===(b8(W)?443:80)||W.port==="")W.port=void 0;if(typeof W.secure==="boolean")W.scheme=W.secure?"wss":"ws",W.secure=void 0;if(W.resourceName){let[$,Q]=W.resourceName.split("?");W.path=$&&$!=="/"?$:void 0,W.query=Q,W.resourceName=void 0}return W.fragment=void 0,W}function tO(W,$){if(!W.path)return W.error="URN can not be parsed",W;let Q=W.path.match(pO);if(Q){let G=$.scheme||W.scheme||"urn";W.nid=Q[1].toLowerCase(),W.nss=Q[2];let X=`${G}:${$.nid||W.nid}`,J=H8(X);if(W.path=void 0,J)W=J.parse(W,$)}else W.error=W.error||"URN can not be parsed.";return W}function rO(W,$){if(W.nid===void 0)throw Error("URN without nid cannot be serialized");let Q=$.scheme||W.scheme||"urn",G=W.nid.toLowerCase(),X=`${Q}:${$.nid||G}`,J=H8(X);if(J)W=J.serialize(W,$);let w=W,Y=W.nss;return w.path=`${G||$.nid}:${Y}`,$.skipEscape=!0,w}function sO(W,$){let Q=W;if(Q.uuid=Q.nss,Q.nss=void 0,!$.tolerant&&(!Q.uuid||!gO(Q.uuid)))Q.error=Q.error||"UUID is not valid.";return Q}function aO(W){let $=W;return $.nss=(W.uuid||"").toLowerCase(),$}var R7={scheme:"http",domainHost:!0,parse:E7,serialize:T7},eO={scheme:"https",domainHost:R7.domainHost,parse:E7,serialize:T7},vW={scheme:"ws",domainHost:!0,parse:dO,serialize:oO},WZ={scheme:"wss",domainHost:vW.domainHost,parse:vW.parse,serialize:vW.serialize},$Z={scheme:"urn",parse:tO,serialize:rO,skipNormalize:!0},QZ={scheme:"urn:uuid",parse:sO,serialize:aO,skipNormalize:!0},_W={http:R7,https:eO,ws:vW,wss:WZ,urn:$Z,"urn:uuid":QZ};Object.setPrototypeOf(_W,null);function H8(W){return W&&(_W[W]||_W[W.toLowerCase()])||void 0}S7.exports={wsIsSecure:b8,SCHEMES:_W,isValidSchemeName:nO,getSchemeHandler:H8}});var _7=N((rR,hW)=>{var{normalizeIPv6:GZ,removeDotSegments:U4,recomposeAuthority:XZ,normalizeComponentEncoding:xW,isIPv4:JZ,nonSimpleDomain:wZ}=Y8(),{SCHEMES:YZ,getSchemeHandler:k7}=C7();function bZ(W,$){if(typeof W==="string")W=G1(L1(W,$),$);else if(typeof W==="object")W=L1(G1(W,$),$);return W}function HZ(W,$,Q){let G=Q?Object.assign({scheme:"null"},Q):{scheme:"null"},X=v7(L1(W,G),L1($,G),G,!0);return G.skipEscape=!0,G1(X,G)}function v7(W,$,Q,G){let X={};if(!G)W=L1(G1(W,Q),Q),$=L1(G1($,Q),Q);if(Q=Q||{},!Q.tolerant&&$.scheme)X.scheme=$.scheme,X.userinfo=$.userinfo,X.host=$.host,X.port=$.port,X.path=U4($.path||""),X.query=$.query;else{if($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)X.userinfo=$.userinfo,X.host=$.host,X.port=$.port,X.path=U4($.path||""),X.query=$.query;else{if(!$.path)if(X.path=W.path,$.query!==void 0)X.query=$.query;else X.query=W.query;else{if($.path[0]==="/")X.path=U4($.path);else{if((W.userinfo!==void 0||W.host!==void 0||W.port!==void 0)&&!W.path)X.path="/"+$.path;else if(!W.path)X.path=$.path;else X.path=W.path.slice(0,W.path.lastIndexOf("/")+1)+$.path;X.path=U4(X.path)}X.query=$.query}X.userinfo=W.userinfo,X.host=W.host,X.port=W.port}X.scheme=W.scheme}return X.fragment=$.fragment,X}function zZ(W,$,Q){if(typeof W==="string")W=unescape(W),W=G1(xW(L1(W,Q),!0),{...Q,skipEscape:!0});else if(typeof W==="object")W=G1(xW(W,!0),{...Q,skipEscape:!0});if(typeof $==="string")$=unescape($),$=G1(xW(L1($,Q),!0),{...Q,skipEscape:!0});else if(typeof $==="object")$=G1(xW($,!0),{...Q,skipEscape:!0});return W.toLowerCase()===$.toLowerCase()}function G1(W,$){let Q={host:W.host,scheme:W.scheme,userinfo:W.userinfo,port:W.port,path:W.path,query:W.query,nid:W.nid,nss:W.nss,uuid:W.uuid,fragment:W.fragment,reference:W.reference,resourceName:W.resourceName,secure:W.secure,error:""},G=Object.assign({},$),X=[],J=k7(G.scheme||Q.scheme);if(J&&J.serialize)J.serialize(Q,G);if(Q.path!==void 0)if(!G.skipEscape){if(Q.path=escape(Q.path),Q.scheme!==void 0)Q.path=Q.path.split("%3A").join(":")}else Q.path=unescape(Q.path);if(G.reference!=="suffix"&&Q.scheme)X.push(Q.scheme,":");let w=XZ(Q);if(w!==void 0){if(G.reference!=="suffix")X.push("//");if(X.push(w),Q.path&&Q.path[0]!=="/")X.push("/")}if(Q.path!==void 0){let Y=Q.path;if(!G.absolutePath&&(!J||!J.absolutePath))Y=U4(Y);if(w===void 0&&Y[0]==="/"&&Y[1]==="/")Y="/%2F"+Y.slice(2);X.push(Y)}if(Q.query!==void 0)X.push("?",Q.query);if(Q.fragment!==void 0)X.push("#",Q.fragment);return X.join("")}var DZ=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function L1(W,$){let Q=Object.assign({},$),G={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},X=!1;if(Q.reference==="suffix")if(Q.scheme)W=Q.scheme+":"+W;else W="//"+W;let J=W.match(DZ);if(J){if(G.scheme=J[1],G.userinfo=J[3],G.host=J[4],G.port=parseInt(J[5],10),G.path=J[6]||"",G.query=J[7],G.fragment=J[8],isNaN(G.port))G.port=J[5];if(G.host)if(JZ(G.host)===!1){let b=GZ(G.host);G.host=b.host.toLowerCase(),X=b.isIPV6}else X=!0;if(G.scheme===void 0&&G.userinfo===void 0&&G.host===void 0&&G.port===void 0&&G.query===void 0&&!G.path)G.reference="same-document";else if(G.scheme===void 0)G.reference="relative";else if(G.fragment===void 0)G.reference="absolute";else G.reference="uri";if(Q.reference&&Q.reference!=="suffix"&&Q.reference!==G.reference)G.error=G.error||"URI is not a "+Q.reference+" reference.";let w=k7(Q.scheme||G.scheme);if(!Q.unicodeSupport&&(!w||!w.unicodeSupport)){if(G.host&&(Q.domainHost||w&&w.domainHost)&&X===!1&&wZ(G.host))try{G.host=URL.domainToASCII(G.host.toLowerCase())}catch(Y){G.error=G.error||"Host's domain name can not be converted to ASCII: "+Y}}if(!w||w&&!w.skipNormalize){if(W.indexOf("%")!==-1){if(G.scheme!==void 0)G.scheme=unescape(G.scheme);if(G.host!==void 0)G.host=unescape(G.host)}if(G.path)G.path=escape(unescape(G.path));if(G.fragment)G.fragment=encodeURI(decodeURIComponent(G.fragment))}if(w&&w.parse)w.parse(G,Q)}else G.error=G.error||"URI can not be parsed.";return G}var z8={SCHEMES:YZ,normalize:bZ,resolve:HZ,resolveComponent:v7,equal:zZ,serialize:G1,parse:L1};hW.exports=z8;hW.exports.default=z8;hW.exports.fastUri=z8});var y7=N((h7)=>{Object.defineProperty(h7,"__esModule",{value:!0});var x7=_7();x7.code='require("ajv/dist/runtime/uri").default';h7.default=x7});var i7=N((B1)=>{Object.defineProperty(B1,"__esModule",{value:!0});B1.CodeGen=B1.Name=B1.nil=B1.stringify=B1.str=B1._=B1.KeywordCxt=void 0;var UZ=z4();Object.defineProperty(B1,"KeywordCxt",{enumerable:!0,get:function(){return UZ.KeywordCxt}});var U6=g();Object.defineProperty(B1,"_",{enumerable:!0,get:function(){return U6._}});Object.defineProperty(B1,"str",{enumerable:!0,get:function(){return U6.str}});Object.defineProperty(B1,"stringify",{enumerable:!0,get:function(){return U6.stringify}});Object.defineProperty(B1,"nil",{enumerable:!0,get:function(){return U6.nil}});Object.defineProperty(B1,"Name",{enumerable:!0,get:function(){return U6.Name}});Object.defineProperty(B1,"CodeGen",{enumerable:!0,get:function(){return U6.CodeGen}});var LZ=SW(),l7=D4(),BZ=g$(),L4=kW(),AZ=g(),B4=Y4(),yW=w4(),F8=t(),f7=j7(),OZ=y7(),g7=(W,$)=>new RegExp(W,$);g7.code="new RegExp";var ZZ=["removeAdditional","useDefaults","coerceTypes"],KZ=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PZ={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},VZ={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},u7=200;function jZ(W){var $,Q,G,X,J,w,Y,b,H,z,F,U,L,Z,P,q,M,S,C,_,k,S0,g0,C0,a1;let p0=W.strict,R6=($=W.code)===null||$===void 0?void 0:$.optimize,P1=R6===!0||R6===void 0?1:R6||0,TQ=(G=(Q=W.code)===null||Q===void 0?void 0:Q.regExp)!==null&&G!==void 0?G:g7,Kz=(X=W.uriResolver)!==null&&X!==void 0?X:OZ.default;return{strictSchema:(w=(J=W.strictSchema)!==null&&J!==void 0?J:p0)!==null&&w!==void 0?w:!0,strictNumbers:(b=(Y=W.strictNumbers)!==null&&Y!==void 0?Y:p0)!==null&&b!==void 0?b:!0,strictTypes:(z=(H=W.strictTypes)!==null&&H!==void 0?H:p0)!==null&&z!==void 0?z:"log",strictTuples:(U=(F=W.strictTuples)!==null&&F!==void 0?F:p0)!==null&&U!==void 0?U:"log",strictRequired:(Z=(L=W.strictRequired)!==null&&L!==void 0?L:p0)!==null&&Z!==void 0?Z:!1,code:W.code?{...W.code,optimize:P1,regExp:TQ}:{optimize:P1,regExp:TQ},loopRequired:(P=W.loopRequired)!==null&&P!==void 0?P:u7,loopEnum:(q=W.loopEnum)!==null&&q!==void 0?q:u7,meta:(M=W.meta)!==null&&M!==void 0?M:!0,messages:(S=W.messages)!==null&&S!==void 0?S:!0,inlineRefs:(C=W.inlineRefs)!==null&&C!==void 0?C:!0,schemaId:(_=W.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(k=W.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(S0=W.validateSchema)!==null&&S0!==void 0?S0:!0,validateFormats:(g0=W.validateFormats)!==null&&g0!==void 0?g0:!0,unicodeRegExp:(C0=W.unicodeRegExp)!==null&&C0!==void 0?C0:!0,int32range:(a1=W.int32range)!==null&&a1!==void 0?a1:!0,uriResolver:Kz}}class fW{constructor(W={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,W=this.opts={...W,...jZ(W)};let{es5:$,lines:Q}=this.opts.code;this.scope=new AZ.ValueScope({scope:{},prefixes:KZ,es5:$,lines:Q}),this.logger=TZ(W.logger);let G=W.validateFormats;if(W.validateFormats=!1,this.RULES=(0,BZ.getRules)(),c7.call(this,PZ,W,"NOT SUPPORTED"),c7.call(this,VZ,W,"DEPRECATED","warn"),this._metaOpts=NZ.call(this),W.formats)qZ.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),W.keywords)IZ.call(this,W.keywords);if(typeof W.meta=="object")this.addMetaSchema(W.meta);MZ.call(this),W.validateFormats=G}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:W,meta:$,schemaId:Q}=this.opts,G=f7;if(Q==="id")G={...f7},G.id=G.$id,delete G.$id;if($&&W)this.addMetaSchema(G,G[Q],!1)}defaultMeta(){let{meta:W,schemaId:$}=this.opts;return this.opts.defaultMeta=typeof W=="object"?W[$]||W:void 0}validate(W,$){let Q;if(typeof W=="string"){if(Q=this.getSchema(W),!Q)throw Error(`no schema with key or ref "${W}"`)}else Q=this.compile(W);let G=Q($);if(!("$async"in Q))this.errors=Q.errors;return G}compile(W,$){let Q=this._addSchema(W,$);return Q.validate||this._compileSchemaEnv(Q)}compileAsync(W,$){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:Q}=this.opts;return G.call(this,W,$);async function G(H,z){await X.call(this,H.$schema);let F=this._addSchema(H,z);return F.validate||J.call(this,F)}async function X(H){if(H&&!this.getSchema(H))await G.call(this,{$ref:H},!0)}async function J(H){try{return this._compileSchemaEnv(H)}catch(z){if(!(z instanceof l7.default))throw z;return w.call(this,z),await Y.call(this,z.missingSchema),J.call(this,H)}}function w({missingSchema:H,missingRef:z}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${z} cannot be resolved`)}async function Y(H){let z=await b.call(this,H);if(!this.refs[H])await X.call(this,z.$schema);if(!this.refs[H])this.addSchema(z,H,$)}async function b(H){let z=this._loading[H];if(z)return z;try{return await(this._loading[H]=Q(H))}finally{delete this._loading[H]}}}addSchema(W,$,Q,G=this.opts.validateSchema){if(Array.isArray(W)){for(let J of W)this.addSchema(J,void 0,Q,G);return this}let X;if(typeof W==="object"){let{schemaId:J}=this.opts;if(X=W[J],X!==void 0&&typeof X!="string")throw Error(`schema ${J} must be string`)}return $=(0,B4.normalizeId)($||X),this._checkUnique($),this.schemas[$]=this._addSchema(W,Q,$,G,!0),this}addMetaSchema(W,$,Q=this.opts.validateSchema){return this.addSchema(W,$,!0,Q),this}validateSchema(W,$){if(typeof W=="boolean")return!0;let Q;if(Q=W.$schema,Q!==void 0&&typeof Q!="string")throw Error("$schema must be a string");if(Q=Q||this.opts.defaultMeta||this.defaultMeta(),!Q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let G=this.validate(Q,W);if(!G&&$){let X="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(X);else throw Error(X)}return G}getSchema(W){let $;while(typeof($=m7.call(this,W))=="string")W=$;if($===void 0){let{schemaId:Q}=this.opts,G=new L4.SchemaEnv({schema:{},schemaId:Q});if($=L4.resolveSchema.call(this,G,W),!$)return;this.refs[W]=$}return $.validate||this._compileSchemaEnv($)}removeSchema(W){if(W instanceof RegExp)return this._removeAllSchemas(this.schemas,W),this._removeAllSchemas(this.refs,W),this;switch(typeof W){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let $=m7.call(this,W);if(typeof $=="object")this._cache.delete($.schema);return delete this.schemas[W],delete this.refs[W],this}case"object":{let $=W;this._cache.delete($);let Q=W[this.opts.schemaId];if(Q)Q=(0,B4.normalizeId)(Q),delete this.schemas[Q],delete this.refs[Q];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(W){for(let $ of W)this.addKeyword($);return this}addKeyword(W,$){let Q;if(typeof W=="string"){if(Q=W,typeof $=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),$.keyword=Q}else if(typeof W=="object"&&$===void 0){if($=W,Q=$.keyword,Array.isArray(Q)&&!Q.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(SZ.call(this,Q,$),!$)return(0,F8.eachItem)(Q,(X)=>D8.call(this,X)),this;kZ.call(this,$);let G={...$,type:(0,yW.getJSONTypes)($.type),schemaType:(0,yW.getJSONTypes)($.schemaType)};return(0,F8.eachItem)(Q,G.type.length===0?(X)=>D8.call(this,X,G):(X)=>G.type.forEach((J)=>D8.call(this,X,G,J))),this}getKeyword(W){let $=this.RULES.all[W];return typeof $=="object"?$.definition:!!$}removeKeyword(W){let{RULES:$}=this;delete $.keywords[W],delete $.all[W];for(let Q of $.rules){let G=Q.rules.findIndex((X)=>X.keyword===W);if(G>=0)Q.rules.splice(G,1)}return this}addFormat(W,$){if(typeof $=="string")$=new RegExp($);return this.formats[W]=$,this}errorsText(W=this.errors,{separator:$=", ",dataVar:Q="data"}={}){if(!W||W.length===0)return"No errors";return W.map((G)=>`${Q}${G.instancePath} ${G.message}`).reduce((G,X)=>G+$+X)}$dataMetaSchema(W,$){let Q=this.RULES.all;W=JSON.parse(JSON.stringify(W));for(let G of $){let X=G.split("/").slice(1),J=W;for(let w of X)J=J[w];for(let w in Q){let Y=Q[w];if(typeof Y!="object")continue;let{$data:b}=Y.definition,H=J[w];if(b&&H)J[w]=p7(H)}}return W}_removeAllSchemas(W,$){for(let Q in W){let G=W[Q];if(!$||$.test(Q)){if(typeof G=="string")delete W[Q];else if(G&&!G.meta)this._cache.delete(G.schema),delete W[Q]}}}_addSchema(W,$,Q,G=this.opts.validateSchema,X=this.opts.addUsedSchema){let J,{schemaId:w}=this.opts;if(typeof W=="object")J=W[w];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof W!="boolean")throw Error("schema must be object or boolean");let Y=this._cache.get(W);if(Y!==void 0)return Y;Q=(0,B4.normalizeId)(J||Q);let b=B4.getSchemaRefs.call(this,W,Q);if(Y=new L4.SchemaEnv({schema:W,schemaId:w,meta:$,baseId:Q,localRefs:b}),this._cache.set(Y.schema,Y),X&&!Q.startsWith("#")){if(Q)this._checkUnique(Q);this.refs[Q]=Y}if(G)this.validateSchema(W,!0);return Y}_checkUnique(W){if(this.schemas[W]||this.refs[W])throw Error(`schema with key or id "${W}" already exists`)}_compileSchemaEnv(W){if(W.meta)this._compileMetaSchema(W);else L4.compileSchema.call(this,W);if(!W.validate)throw Error("ajv implementation error");return W.validate}_compileMetaSchema(W){let $=this.opts;this.opts=this._metaOpts;try{L4.compileSchema.call(this,W)}finally{this.opts=$}}}fW.ValidationError=LZ.default;fW.MissingRefError=l7.default;B1.default=fW;function c7(W,$,Q,G="error"){for(let X in W){let J=X;if(J in $)this.logger[G](`${Q}: option ${X}. ${W[J]}`)}}function m7(W){return W=(0,B4.normalizeId)(W),this.schemas[W]||this.refs[W]}function MZ(){let W=this.opts.schemas;if(!W)return;if(Array.isArray(W))this.addSchema(W);else for(let $ in W)this.addSchema(W[$],$)}function qZ(){for(let W in this.opts.formats){let $=this.opts.formats[W];if($)this.addFormat(W,$)}}function IZ(W){if(Array.isArray(W)){this.addVocabulary(W);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let $ in W){let Q=W[$];if(!Q.keyword)Q.keyword=$;this.addKeyword(Q)}}function NZ(){let W={...this.opts};for(let $ of ZZ)delete W[$];return W}var EZ={log(){},warn(){},error(){}};function TZ(W){if(W===!1)return EZ;if(W===void 0)return console;if(W.log&&W.warn&&W.error)return W;throw Error("logger must implement log, warn and error methods")}var RZ=/^[a-z_$][a-z0-9_$:-]*$/i;function SZ(W,$){let{RULES:Q}=this;if((0,F8.eachItem)(W,(G)=>{if(Q.keywords[G])throw Error(`Keyword ${G} is already defined`);if(!RZ.test(G))throw Error(`Keyword ${G} has invalid name`)}),!$)return;if($.$data&&!(("code"in $)||("validate"in $)))throw Error('$data keyword must have "code" or "validate" function')}function D8(W,$,Q){var G;let X=$===null||$===void 0?void 0:$.post;if(Q&&X)throw Error('keyword with "post" flag cannot have "type"');let{RULES:J}=this,w=X?J.post:J.rules.find(({type:b})=>b===Q);if(!w)w={type:Q,rules:[]},J.rules.push(w);if(J.keywords[W]=!0,!$)return;let Y={keyword:W,definition:{...$,type:(0,yW.getJSONTypes)($.type),schemaType:(0,yW.getJSONTypes)($.schemaType)}};if($.before)CZ.call(this,w,Y,$.before);else w.rules.push(Y);J.all[W]=Y,(G=$.implements)===null||G===void 0||G.forEach((b)=>this.addKeyword(b))}function CZ(W,$,Q){let G=W.rules.findIndex((X)=>X.keyword===Q);if(G>=0)W.rules.splice(G,0,$);else W.rules.push($),this.logger.warn(`rule ${Q} is not defined`)}function kZ(W){let{metaSchema:$}=W;if($===void 0)return;if(W.$data&&this.opts.$data)$=p7($);W.validateSchema=this.compile($,!0)}var vZ={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function p7(W){return{anyOf:[W,vZ]}}});var d7=N((n7)=>{Object.defineProperty(n7,"__esModule",{value:!0});var hZ={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};n7.default=hZ});var e7=N((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});s7.callRef=s7.getValidate=void 0;var fZ=D4(),o7=m0(),T0=g(),L6=F1(),t7=kW(),uW=t(),uZ={keyword:"$ref",schemaType:"string",code(W){let{gen:$,schema:Q,it:G}=W,{baseId:X,schemaEnv:J,validateName:w,opts:Y,self:b}=G,{root:H}=J;if((Q==="#"||Q==="#/")&&X===H.baseId)return F();let z=t7.resolveRef.call(b,H,X,Q);if(z===void 0)throw new fZ.default(G.opts.uriResolver,X,Q);if(z instanceof t7.SchemaEnv)return U(z);return L(z);function F(){if(J===H)return cW(W,w,J,J.$async);let Z=$.scopeValue("root",{ref:H});return cW(W,T0._`${Z}.validate`,H,H.$async)}function U(Z){let P=r7(W,Z);cW(W,P,Z,Z.$async)}function L(Z){let P=$.scopeValue("schema",Y.code.source===!0?{ref:Z,code:(0,T0.stringify)(Z)}:{ref:Z}),q=$.name("valid"),M=W.subschema({schema:Z,dataTypes:[],schemaPath:T0.nil,topSchemaRef:P,errSchemaPath:Q},q);W.mergeEvaluated(M),W.ok(q)}}};function r7(W,$){let{gen:Q}=W;return $.validate?Q.scopeValue("validate",{ref:$.validate}):T0._`${Q.scopeValue("wrapper",{ref:$})}.validate`}s7.getValidate=r7;function cW(W,$,Q,G){let{gen:X,it:J}=W,{allErrors:w,schemaEnv:Y,opts:b}=J,H=b.passContext?L6.default.this:T0.nil;if(G)z();else F();function z(){if(!Y.$async)throw Error("async schema referenced by sync schema");let Z=X.let("valid");X.try(()=>{if(X.code(T0._`await ${(0,o7.callValidateCode)(W,$,H)}`),L($),!w)X.assign(Z,!0)},(P)=>{if(X.if(T0._`!(${P} instanceof ${J.ValidationError})`,()=>X.throw(P)),U(P),!w)X.assign(Z,!1)}),W.ok(Z)}function F(){W.result((0,o7.callValidateCode)(W,$,H),()=>L($),()=>U($))}function U(Z){let P=T0._`${Z}.errors`;X.assign(L6.default.vErrors,T0._`${L6.default.vErrors} === null ? ${P} : ${L6.default.vErrors}.concat(${P})`),X.assign(L6.default.errors,T0._`${L6.default.vErrors}.length`)}function L(Z){var P;if(!J.opts.unevaluated)return;let q=(P=Q===null||Q===void 0?void 0:Q.validate)===null||P===void 0?void 0:P.evaluated;if(J.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)J.props=uW.mergeEvaluated.props(X,q.props,J.props)}else{let M=X.var("props",T0._`${Z}.evaluated.props`);J.props=uW.mergeEvaluated.props(X,M,J.props,T0.Name)}if(J.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)J.items=uW.mergeEvaluated.items(X,q.items,J.items)}else{let M=X.var("items",T0._`${Z}.evaluated.items`);J.items=uW.mergeEvaluated.items(X,M,J.items,T0.Name)}}}s7.callRef=cW;s7.default=uZ});var $5=N((W5)=>{Object.defineProperty(W5,"__esModule",{value:!0});var lZ=d7(),gZ=e7(),pZ=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",lZ.default,gZ.default];W5.default=pZ});var G5=N((Q5)=>{Object.defineProperty(Q5,"__esModule",{value:!0});var mW=g(),x1=mW.operators,lW={maximum:{okStr:"<=",ok:x1.LTE,fail:x1.GT},minimum:{okStr:">=",ok:x1.GTE,fail:x1.LT},exclusiveMaximum:{okStr:"<",ok:x1.LT,fail:x1.GTE},exclusiveMinimum:{okStr:">",ok:x1.GT,fail:x1.LTE}},nZ={message:({keyword:W,schemaCode:$})=>mW.str`must be ${lW[W].okStr} ${$}`,params:({keyword:W,schemaCode:$})=>mW._`{comparison: ${lW[W].okStr}, limit: ${$}}`},dZ={keyword:Object.keys(lW),type:"number",schemaType:"number",$data:!0,error:nZ,code(W){let{keyword:$,data:Q,schemaCode:G}=W;W.fail$data(mW._`${Q} ${lW[$].fail} ${G} || isNaN(${Q})`)}};Q5.default=dZ});var J5=N((X5)=>{Object.defineProperty(X5,"__esModule",{value:!0});var A4=g(),tZ={message:({schemaCode:W})=>A4.str`must be multiple of ${W}`,params:({schemaCode:W})=>A4._`{multipleOf: ${W}}`},rZ={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:tZ,code(W){let{gen:$,data:Q,schemaCode:G,it:X}=W,J=X.opts.multipleOfPrecision,w=$.let("res"),Y=J?A4._`Math.abs(Math.round(${w}) - ${w}) > 1e-${J}`:A4._`${w} !== parseInt(${w})`;W.fail$data(A4._`(${G} === 0 || (${w} = ${Q}/${G}, ${Y}))`)}};X5.default=rZ});var b5=N((Y5)=>{Object.defineProperty(Y5,"__esModule",{value:!0});function w5(W){let $=W.length,Q=0,G=0,X;while(G<$)if(Q++,X=W.charCodeAt(G++),X>=55296&&X<=56319&&G<$){if(X=W.charCodeAt(G),(X&64512)===56320)G++}return Q}Y5.default=w5;w5.code='require("ajv/dist/runtime/ucs2length").default'});var z5=N((H5)=>{Object.defineProperty(H5,"__esModule",{value:!0});var i1=g(),eZ=t(),WK=b5(),$K={message({keyword:W,schemaCode:$}){let Q=W==="maxLength"?"more":"fewer";return i1.str`must NOT have ${Q} than ${$} characters`},params:({schemaCode:W})=>i1._`{limit: ${W}}`},QK={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:$K,code(W){let{keyword:$,data:Q,schemaCode:G,it:X}=W,J=$==="maxLength"?i1.operators.GT:i1.operators.LT,w=X.opts.unicode===!1?i1._`${Q}.length`:i1._`${(0,eZ.useFunc)(W.gen,WK.default)}(${Q})`;W.fail$data(i1._`${w} ${J} ${G}`)}};H5.default=QK});var F5=N((D5)=>{Object.defineProperty(D5,"__esModule",{value:!0});var XK=m0(),gW=g(),JK={message:({schemaCode:W})=>gW.str`must match pattern "${W}"`,params:({schemaCode:W})=>gW._`{pattern: ${W}}`},wK={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:JK,code(W){let{data:$,$data:Q,schema:G,schemaCode:X,it:J}=W,w=J.opts.unicodeRegExp?"u":"",Y=Q?gW._`(new RegExp(${X}, ${w}))`:(0,XK.usePattern)(W,G);W.fail$data(gW._`!${Y}.test(${$})`)}};D5.default=wK});var L5=N((U5)=>{Object.defineProperty(U5,"__esModule",{value:!0});var O4=g(),bK={message({keyword:W,schemaCode:$}){let Q=W==="maxProperties"?"more":"fewer";return O4.str`must NOT have ${Q} than ${$} properties`},params:({schemaCode:W})=>O4._`{limit: ${W}}`},HK={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bK,code(W){let{keyword:$,data:Q,schemaCode:G}=W,X=$==="maxProperties"?O4.operators.GT:O4.operators.LT;W.fail$data(O4._`Object.keys(${Q}).length ${X} ${G}`)}};U5.default=HK});var A5=N((B5)=>{Object.defineProperty(B5,"__esModule",{value:!0});var Z4=m0(),K4=g(),DK=t(),FK={message:({params:{missingProperty:W}})=>K4.str`must have required property '${W}'`,params:({params:{missingProperty:W}})=>K4._`{missingProperty: ${W}}`},UK={keyword:"required",type:"object",schemaType:"array",$data:!0,error:FK,code(W){let{gen:$,schema:Q,schemaCode:G,data:X,$data:J,it:w}=W,{opts:Y}=w;if(!J&&Q.length===0)return;let b=Q.length>=Y.loopRequired;if(w.allErrors)H();else z();if(Y.strictRequired){let L=W.parentSchema.properties,{definedProperties:Z}=W.it;for(let P of Q)if((L===null||L===void 0?void 0:L[P])===void 0&&!Z.has(P)){let q=w.schemaEnv.baseId+w.errSchemaPath,M=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,DK.checkStrictMode)(w,M,w.opts.strictRequired)}}function H(){if(b||J)W.block$data(K4.nil,F);else for(let L of Q)(0,Z4.checkReportMissingProp)(W,L)}function z(){let L=$.let("missing");if(b||J){let Z=$.let("valid",!0);W.block$data(Z,()=>U(L,Z)),W.ok(Z)}else $.if((0,Z4.checkMissingProp)(W,Q,L)),(0,Z4.reportMissingProp)(W,L),$.else()}function F(){$.forOf("prop",G,(L)=>{W.setParams({missingProperty:L}),$.if((0,Z4.noPropertyInData)($,X,L,Y.ownProperties),()=>W.error())})}function U(L,Z){W.setParams({missingProperty:L}),$.forOf(L,G,()=>{$.assign(Z,(0,Z4.propertyInData)($,X,L,Y.ownProperties)),$.if((0,K4.not)(Z),()=>{W.error(),$.break()})},K4.nil)}}};B5.default=UK});var Z5=N((O5)=>{Object.defineProperty(O5,"__esModule",{value:!0});var P4=g(),BK={message({keyword:W,schemaCode:$}){let Q=W==="maxItems"?"more":"fewer";return P4.str`must NOT have ${Q} than ${$} items`},params:({schemaCode:W})=>P4._`{limit: ${W}}`},AK={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:BK,code(W){let{keyword:$,data:Q,schemaCode:G}=W,X=$==="maxItems"?P4.operators.GT:P4.operators.LT;W.fail$data(P4._`${Q}.length ${X} ${G}`)}};O5.default=AK});var pW=N((P5)=>{Object.defineProperty(P5,"__esModule",{value:!0});var K5=s$();K5.code='require("ajv/dist/runtime/equal").default';P5.default=K5});var j5=N((V5)=>{Object.defineProperty(V5,"__esModule",{value:!0});var U8=w4(),P0=g(),KK=t(),PK=pW(),VK={message:({params:{i:W,j:$}})=>P0.str`must NOT have duplicate items (items ## ${$} and ${W} are identical)`,params:({params:{i:W,j:$}})=>P0._`{i: ${W}, j: ${$}}`},jK={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:VK,code(W){let{gen:$,data:Q,$data:G,schema:X,parentSchema:J,schemaCode:w,it:Y}=W;if(!G&&!X)return;let b=$.let("valid"),H=J.items?(0,U8.getSchemaTypes)(J.items):[];W.block$data(b,z,P0._`${w} === false`),W.ok(b);function z(){let Z=$.let("i",P0._`${Q}.length`),P=$.let("j");W.setParams({i:Z,j:P}),$.assign(b,!0),$.if(P0._`${Z} > 1`,()=>(F()?U:L)(Z,P))}function F(){return H.length>0&&!H.some((Z)=>Z==="object"||Z==="array")}function U(Z,P){let q=$.name("item"),M=(0,U8.checkDataTypes)(H,q,Y.opts.strictNumbers,U8.DataType.Wrong),S=$.const("indices",P0._`{}`);$.for(P0._`;${Z}--;`,()=>{if($.let(q,P0._`${Q}[${Z}]`),$.if(M,P0._`continue`),H.length>1)$.if(P0._`typeof ${q} == "string"`,P0._`${q} += "_"`);$.if(P0._`typeof ${S}[${q}] == "number"`,()=>{$.assign(P,P0._`${S}[${q}]`),W.error(),$.assign(b,!1).break()}).code(P0._`${S}[${q}] = ${Z}`)})}function L(Z,P){let q=(0,KK.useFunc)($,PK.default),M=$.name("outer");$.label(M).for(P0._`;${Z}--;`,()=>$.for(P0._`${P} = ${Z}; ${P}--;`,()=>$.if(P0._`${q}(${Q}[${Z}], ${Q}[${P}])`,()=>{W.error(),$.assign(b,!1).break(M)})))}}};V5.default=jK});var q5=N((M5)=>{Object.defineProperty(M5,"__esModule",{value:!0});var L8=g(),qK=t(),IK=pW(),NK={message:"must be equal to constant",params:({schemaCode:W})=>L8._`{allowedValue: ${W}}`},EK={keyword:"const",$data:!0,error:NK,code(W){let{gen:$,data:Q,$data:G,schemaCode:X,schema:J}=W;if(G||J&&typeof J=="object")W.fail$data(L8._`!${(0,qK.useFunc)($,IK.default)}(${Q}, ${X})`);else W.fail(L8._`${J} !== ${Q}`)}};M5.default=EK});var N5=N((I5)=>{Object.defineProperty(I5,"__esModule",{value:!0});var V4=g(),RK=t(),SK=pW(),CK={message:"must be equal to one of the allowed values",params:({schemaCode:W})=>V4._`{allowedValues: ${W}}`},kK={keyword:"enum",schemaType:"array",$data:!0,error:CK,code(W){let{gen:$,data:Q,$data:G,schema:X,schemaCode:J,it:w}=W;if(!G&&X.length===0)throw Error("enum must have non-empty array");let Y=X.length>=w.opts.loopEnum,b,H=()=>b!==null&&b!==void 0?b:b=(0,RK.useFunc)($,SK.default),z;if(Y||G)z=$.let("valid"),W.block$data(z,F);else{if(!Array.isArray(X))throw Error("ajv implementation error");let L=$.const("vSchema",J);z=(0,V4.or)(...X.map((Z,P)=>U(L,P)))}W.pass(z);function F(){$.assign(z,!1),$.forOf("v",J,(L)=>$.if(V4._`${H()}(${Q}, ${L})`,()=>$.assign(z,!0).break()))}function U(L,Z){let P=X[Z];return typeof P==="object"&&P!==null?V4._`${H()}(${Q}, ${L}[${Z}])`:V4._`${Q} === ${P}`}}};I5.default=kK});var T5=N((E5)=>{Object.defineProperty(E5,"__esModule",{value:!0});var _K=G5(),xK=J5(),hK=z5(),yK=F5(),fK=L5(),uK=A5(),cK=Z5(),mK=j5(),lK=q5(),gK=N5(),pK=[_K.default,xK.default,hK.default,yK.default,fK.default,uK.default,cK.default,mK.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},lK.default,gK.default];E5.default=pK});var A8=N((S5)=>{Object.defineProperty(S5,"__esModule",{value:!0});S5.validateAdditionalItems=void 0;var n1=g(),B8=t(),nK={message:({params:{len:W}})=>n1.str`must NOT have more than ${W} items`,params:({params:{len:W}})=>n1._`{limit: ${W}}`},dK={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:nK,code(W){let{parentSchema:$,it:Q}=W,{items:G}=$;if(!Array.isArray(G)){(0,B8.checkStrictMode)(Q,'"additionalItems" is ignored when "items" is not an array of schemas');return}R5(W,G)}};function R5(W,$){let{gen:Q,schema:G,data:X,keyword:J,it:w}=W;w.items=!0;let Y=Q.const("len",n1._`${X}.length`);if(G===!1)W.setParams({len:$.length}),W.pass(n1._`${Y} <= ${$.length}`);else if(typeof G=="object"&&!(0,B8.alwaysValidSchema)(w,G)){let H=Q.var("valid",n1._`${Y} <= ${$.length}`);Q.if((0,n1.not)(H),()=>b(H)),W.ok(H)}function b(H){Q.forRange("i",$.length,Y,(z)=>{if(W.subschema({keyword:J,dataProp:z,dataPropType:B8.Type.Num},H),!w.allErrors)Q.if((0,n1.not)(H),()=>Q.break())})}}S5.validateAdditionalItems=R5;S5.default=dK});var O8=N((_5)=>{Object.defineProperty(_5,"__esModule",{value:!0});_5.validateTuple=void 0;var k5=g(),iW=t(),tK=m0(),rK={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(W){let{schema:$,it:Q}=W;if(Array.isArray($))return v5(W,"additionalItems",$);if(Q.items=!0,(0,iW.alwaysValidSchema)(Q,$))return;W.ok((0,tK.validateArray)(W))}};function v5(W,$,Q=W.schema){let{gen:G,parentSchema:X,data:J,keyword:w,it:Y}=W;if(z(X),Y.opts.unevaluated&&Q.length&&Y.items!==!0)Y.items=iW.mergeEvaluated.items(G,Q.length,Y.items);let b=G.name("valid"),H=G.const("len",k5._`${J}.length`);Q.forEach((F,U)=>{if((0,iW.alwaysValidSchema)(Y,F))return;G.if(k5._`${H} > ${U}`,()=>W.subschema({keyword:w,schemaProp:U,dataProp:U},b)),W.ok(b)});function z(F){let{opts:U,errSchemaPath:L}=Y,Z=Q.length,P=Z===F.minItems&&(Z===F.maxItems||F[$]===!1);if(U.strictTuples&&!P){let q=`"${w}" is ${Z}-tuple, but minItems or maxItems/${$} are not specified or different at path "${L}"`;(0,iW.checkStrictMode)(Y,q,U.strictTuples)}}}_5.validateTuple=v5;_5.default=rK});var y5=N((h5)=>{Object.defineProperty(h5,"__esModule",{value:!0});var aK=O8(),eK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(W)=>(0,aK.validateTuple)(W,"items")};h5.default=eK});var c5=N((u5)=>{Object.defineProperty(u5,"__esModule",{value:!0});var f5=g(),$P=t(),QP=m0(),GP=A8(),XP={message:({params:{len:W}})=>f5.str`must NOT have more than ${W} items`,params:({params:{len:W}})=>f5._`{limit: ${W}}`},JP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:XP,code(W){let{schema:$,parentSchema:Q,it:G}=W,{prefixItems:X}=Q;if(G.items=!0,(0,$P.alwaysValidSchema)(G,$))return;if(X)(0,GP.validateAdditionalItems)(W,X);else W.ok((0,QP.validateArray)(W))}};u5.default=JP});var l5=N((m5)=>{Object.defineProperty(m5,"__esModule",{value:!0});var l0=g(),nW=t(),YP={message:({params:{min:W,max:$}})=>$===void 0?l0.str`must contain at least ${W} valid item(s)`:l0.str`must contain at least ${W} and no more than ${$} valid item(s)`,params:({params:{min:W,max:$}})=>$===void 0?l0._`{minContains: ${W}}`:l0._`{minContains: ${W}, maxContains: ${$}}`},bP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:YP,code(W){let{gen:$,schema:Q,parentSchema:G,data:X,it:J}=W,w,Y,{minContains:b,maxContains:H}=G;if(J.opts.next)w=b===void 0?1:b,Y=H;else w=1;let z=$.const("len",l0._`${X}.length`);if(W.setParams({min:w,max:Y}),Y===void 0&&w===0){(0,nW.checkStrictMode)(J,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(Y!==void 0&&w>Y){(0,nW.checkStrictMode)(J,'"minContains" > "maxContains" is always invalid'),W.fail();return}if((0,nW.alwaysValidSchema)(J,Q)){let P=l0._`${z} >= ${w}`;if(Y!==void 0)P=l0._`${P} && ${z} <= ${Y}`;W.pass(P);return}J.items=!0;let F=$.name("valid");if(Y===void 0&&w===1)L(F,()=>$.if(F,()=>$.break()));else if(w===0){if($.let(F,!0),Y!==void 0)$.if(l0._`${X}.length > 0`,U)}else $.let(F,!1),U();W.result(F,()=>W.reset());function U(){let P=$.name("_valid"),q=$.let("count",0);L(P,()=>$.if(P,()=>Z(q)))}function L(P,q){$.forRange("i",0,z,(M)=>{W.subschema({keyword:"contains",dataProp:M,dataPropType:nW.Type.Num,compositeRule:!0},P),q()})}function Z(P){if($.code(l0._`${P}++`),Y===void 0)$.if(l0._`${P} >= ${w}`,()=>$.assign(F,!0).break());else if($.if(l0._`${P} > ${Y}`,()=>$.assign(F,!1).break()),w===1)$.assign(F,!0);else $.if(l0._`${P} >= ${w}`,()=>$.assign(F,!0))}}};m5.default=bP});var o5=N((i5)=>{Object.defineProperty(i5,"__esModule",{value:!0});i5.validateSchemaDeps=i5.validatePropertyDeps=i5.error=void 0;var Z8=g(),zP=t(),j4=m0();i5.error={message:({params:{property:W,depsCount:$,deps:Q}})=>{let G=$===1?"property":"properties";return Z8.str`must have ${G} ${Q} when property ${W} is present`},params:({params:{property:W,depsCount:$,deps:Q,missingProperty:G}})=>Z8._`{property: ${W},
|
|
7
|
+
missingProperty: ${G},
|
|
8
|
+
depsCount: ${$},
|
|
9
|
+
deps: ${Q}}`};var DP={keyword:"dependencies",type:"object",schemaType:"object",error:i5.error,code(W){let[$,Q]=FP(W);g5(W,$),p5(W,Q)}};function FP({schema:W}){let $={},Q={};for(let G in W){if(G==="__proto__")continue;let X=Array.isArray(W[G])?$:Q;X[G]=W[G]}return[$,Q]}function g5(W,$=W.schema){let{gen:Q,data:G,it:X}=W;if(Object.keys($).length===0)return;let J=Q.let("missing");for(let w in $){let Y=$[w];if(Y.length===0)continue;let b=(0,j4.propertyInData)(Q,G,w,X.opts.ownProperties);if(W.setParams({property:w,depsCount:Y.length,deps:Y.join(", ")}),X.allErrors)Q.if(b,()=>{for(let H of Y)(0,j4.checkReportMissingProp)(W,H)});else Q.if(Z8._`${b} && (${(0,j4.checkMissingProp)(W,Y,J)})`),(0,j4.reportMissingProp)(W,J),Q.else()}}i5.validatePropertyDeps=g5;function p5(W,$=W.schema){let{gen:Q,data:G,keyword:X,it:J}=W,w=Q.name("valid");for(let Y in $){if((0,zP.alwaysValidSchema)(J,$[Y]))continue;Q.if((0,j4.propertyInData)(Q,G,Y,J.opts.ownProperties),()=>{let b=W.subschema({keyword:X,schemaProp:Y},w);W.mergeValidEvaluated(b,w)},()=>Q.var(w,!0)),W.ok(w)}}i5.validateSchemaDeps=p5;i5.default=DP});var s5=N((r5)=>{Object.defineProperty(r5,"__esModule",{value:!0});var t5=g(),BP=t(),AP={message:"property name must be valid",params:({params:W})=>t5._`{propertyName: ${W.propertyName}}`},OP={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:AP,code(W){let{gen:$,schema:Q,data:G,it:X}=W;if((0,BP.alwaysValidSchema)(X,Q))return;let J=$.name("valid");$.forIn("key",G,(w)=>{W.setParams({propertyName:w}),W.subschema({keyword:"propertyNames",data:w,dataTypes:["string"],propertyName:w,compositeRule:!0},J),$.if((0,t5.not)(J),()=>{if(W.error(!0),!X.allErrors)$.break()})}),W.ok(J)}};r5.default=OP});var K8=N((a5)=>{Object.defineProperty(a5,"__esModule",{value:!0});var dW=m0(),s0=g(),KP=F1(),oW=t(),PP={message:"must NOT have additional properties",params:({params:W})=>s0._`{additionalProperty: ${W.additionalProperty}}`},VP={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PP,code(W){let{gen:$,schema:Q,parentSchema:G,data:X,errsCount:J,it:w}=W;if(!J)throw Error("ajv implementation error");let{allErrors:Y,opts:b}=w;if(w.props=!0,b.removeAdditional!=="all"&&(0,oW.alwaysValidSchema)(w,Q))return;let H=(0,dW.allSchemaProperties)(G.properties),z=(0,dW.allSchemaProperties)(G.patternProperties);F(),W.ok(s0._`${J} === ${KP.default.errors}`);function F(){$.forIn("key",X,(q)=>{if(!H.length&&!z.length)Z(q);else $.if(U(q),()=>Z(q))})}function U(q){let M;if(H.length>8){let S=(0,oW.schemaRefOrVal)(w,G.properties,"properties");M=(0,dW.isOwnProperty)($,S,q)}else if(H.length)M=(0,s0.or)(...H.map((S)=>s0._`${q} === ${S}`));else M=s0.nil;if(z.length)M=(0,s0.or)(M,...z.map((S)=>s0._`${(0,dW.usePattern)(W,S)}.test(${q})`));return(0,s0.not)(M)}function L(q){$.code(s0._`delete ${X}[${q}]`)}function Z(q){if(b.removeAdditional==="all"||b.removeAdditional&&Q===!1){L(q);return}if(Q===!1){if(W.setParams({additionalProperty:q}),W.error(),!Y)$.break();return}if(typeof Q=="object"&&!(0,oW.alwaysValidSchema)(w,Q)){let M=$.name("valid");if(b.removeAdditional==="failing")P(q,M,!1),$.if((0,s0.not)(M),()=>{W.reset(),L(q)});else if(P(q,M),!Y)$.if((0,s0.not)(M),()=>$.break())}}function P(q,M,S){let C={keyword:"additionalProperties",dataProp:q,dataPropType:oW.Type.Str};if(S===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});W.subschema(C,M)}}};a5.default=VP});var Qb=N(($b)=>{Object.defineProperty($b,"__esModule",{value:!0});var MP=z4(),e5=m0(),P8=t(),Wb=K8(),qP={keyword:"properties",type:"object",schemaType:"object",code(W){let{gen:$,schema:Q,parentSchema:G,data:X,it:J}=W;if(J.opts.removeAdditional==="all"&&G.additionalProperties===void 0)Wb.default.code(new MP.KeywordCxt(J,Wb.default,"additionalProperties"));let w=(0,e5.allSchemaProperties)(Q);for(let F of w)J.definedProperties.add(F);if(J.opts.unevaluated&&w.length&&J.props!==!0)J.props=P8.mergeEvaluated.props($,(0,P8.toHash)(w),J.props);let Y=w.filter((F)=>!(0,P8.alwaysValidSchema)(J,Q[F]));if(Y.length===0)return;let b=$.name("valid");for(let F of Y){if(H(F))z(F);else{if($.if((0,e5.propertyInData)($,X,F,J.opts.ownProperties)),z(F),!J.allErrors)$.else().var(b,!0);$.endIf()}W.it.definedProperties.add(F),W.ok(b)}function H(F){return J.opts.useDefaults&&!J.compositeRule&&Q[F].default!==void 0}function z(F){W.subschema({keyword:"properties",schemaProp:F,dataProp:F},b)}}};$b.default=qP});var Yb=N((wb)=>{Object.defineProperty(wb,"__esModule",{value:!0});var Gb=m0(),tW=g(),Xb=t(),Jb=t(),NP={keyword:"patternProperties",type:"object",schemaType:"object",code(W){let{gen:$,schema:Q,data:G,parentSchema:X,it:J}=W,{opts:w}=J,Y=(0,Gb.allSchemaProperties)(Q),b=Y.filter((P)=>(0,Xb.alwaysValidSchema)(J,Q[P]));if(Y.length===0||b.length===Y.length&&(!J.opts.unevaluated||J.props===!0))return;let H=w.strictSchema&&!w.allowMatchingProperties&&X.properties,z=$.name("valid");if(J.props!==!0&&!(J.props instanceof tW.Name))J.props=(0,Jb.evaluatedPropsToName)($,J.props);let{props:F}=J;U();function U(){for(let P of Y){if(H)L(P);if(J.allErrors)Z(P);else $.var(z,!0),Z(P),$.if(z)}}function L(P){for(let q in H)if(new RegExp(P).test(q))(0,Xb.checkStrictMode)(J,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function Z(P){$.forIn("key",G,(q)=>{$.if(tW._`${(0,Gb.usePattern)(W,P)}.test(${q})`,()=>{let M=b.includes(P);if(!M)W.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:Jb.Type.Str},z);if(J.opts.unevaluated&&F!==!0)$.assign(tW._`${F}[${q}]`,!0);else if(!M&&!J.allErrors)$.if((0,tW.not)(z),()=>$.break())})})}}};wb.default=NP});var Hb=N((bb)=>{Object.defineProperty(bb,"__esModule",{value:!0});var TP=t(),RP={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(W){let{gen:$,schema:Q,it:G}=W;if((0,TP.alwaysValidSchema)(G,Q)){W.fail();return}let X=$.name("valid");W.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},X),W.failResult(X,()=>W.reset(),()=>W.error())},error:{message:"must NOT be valid"}};bb.default=RP});var Db=N((zb)=>{Object.defineProperty(zb,"__esModule",{value:!0});var CP=m0(),kP={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:CP.validateUnion,error:{message:"must match a schema in anyOf"}};zb.default=kP});var Ub=N((Fb)=>{Object.defineProperty(Fb,"__esModule",{value:!0});var rW=g(),_P=t(),xP={message:"must match exactly one schema in oneOf",params:({params:W})=>rW._`{passingSchemas: ${W.passing}}`},hP={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:xP,code(W){let{gen:$,schema:Q,parentSchema:G,it:X}=W;if(!Array.isArray(Q))throw Error("ajv implementation error");if(X.opts.discriminator&&G.discriminator)return;let J=Q,w=$.let("valid",!1),Y=$.let("passing",null),b=$.name("_valid");W.setParams({passing:Y}),$.block(H),W.result(w,()=>W.reset(),()=>W.error(!0));function H(){J.forEach((z,F)=>{let U;if((0,_P.alwaysValidSchema)(X,z))$.var(b,!0);else U=W.subschema({keyword:"oneOf",schemaProp:F,compositeRule:!0},b);if(F>0)$.if(rW._`${b} && ${w}`).assign(w,!1).assign(Y,rW._`[${Y}, ${F}]`).else();$.if(b,()=>{if($.assign(w,!0),$.assign(Y,F),U)W.mergeEvaluated(U,rW.Name)})})}}};Fb.default=hP});var Bb=N((Lb)=>{Object.defineProperty(Lb,"__esModule",{value:!0});var fP=t(),uP={keyword:"allOf",schemaType:"array",code(W){let{gen:$,schema:Q,it:G}=W;if(!Array.isArray(Q))throw Error("ajv implementation error");let X=$.name("valid");Q.forEach((J,w)=>{if((0,fP.alwaysValidSchema)(G,J))return;let Y=W.subschema({keyword:"allOf",schemaProp:w},X);W.ok(X),W.mergeEvaluated(Y)})}};Lb.default=uP});var Kb=N((Zb)=>{Object.defineProperty(Zb,"__esModule",{value:!0});var sW=g(),Ob=t(),mP={message:({params:W})=>sW.str`must match "${W.ifClause}" schema`,params:({params:W})=>sW._`{failingKeyword: ${W.ifClause}}`},lP={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mP,code(W){let{gen:$,parentSchema:Q,it:G}=W;if(Q.then===void 0&&Q.else===void 0)(0,Ob.checkStrictMode)(G,'"if" without "then" and "else" is ignored');let X=Ab(G,"then"),J=Ab(G,"else");if(!X&&!J)return;let w=$.let("valid",!0),Y=$.name("_valid");if(b(),W.reset(),X&&J){let z=$.let("ifClause");W.setParams({ifClause:z}),$.if(Y,H("then",z),H("else",z))}else if(X)$.if(Y,H("then"));else $.if((0,sW.not)(Y),H("else"));W.pass(w,()=>W.error(!0));function b(){let z=W.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},Y);W.mergeEvaluated(z)}function H(z,F){return()=>{let U=W.subschema({keyword:z},Y);if($.assign(w,Y),W.mergeValidEvaluated(U,w),F)$.assign(F,sW._`${z}`);else W.setParams({ifClause:z})}}}};function Ab(W,$){let Q=W.schema[$];return Q!==void 0&&!(0,Ob.alwaysValidSchema)(W,Q)}Zb.default=lP});var Vb=N((Pb)=>{Object.defineProperty(Pb,"__esModule",{value:!0});var pP=t(),iP={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:W,parentSchema:$,it:Q}){if($.if===void 0)(0,pP.checkStrictMode)(Q,`"${W}" without "if" is ignored`)}};Pb.default=iP});var Mb=N((jb)=>{Object.defineProperty(jb,"__esModule",{value:!0});var dP=A8(),oP=y5(),tP=O8(),rP=c5(),sP=l5(),aP=o5(),eP=s5(),WV=K8(),$V=Qb(),QV=Yb(),GV=Hb(),XV=Db(),JV=Ub(),wV=Bb(),YV=Kb(),bV=Vb();function HV(W=!1){let $=[GV.default,XV.default,JV.default,wV.default,YV.default,bV.default,eP.default,WV.default,aP.default,$V.default,QV.default];if(W)$.push(oP.default,rP.default);else $.push(dP.default,tP.default);return $.push(sP.default),$}jb.default=HV});var Ib=N((qb)=>{Object.defineProperty(qb,"__esModule",{value:!0});var z0=g(),DV={message:({schemaCode:W})=>z0.str`must match format "${W}"`,params:({schemaCode:W})=>z0._`{format: ${W}}`},FV={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:DV,code(W,$){let{gen:Q,data:G,$data:X,schema:J,schemaCode:w,it:Y}=W,{opts:b,errSchemaPath:H,schemaEnv:z,self:F}=Y;if(!b.validateFormats)return;if(X)U();else L();function U(){let Z=Q.scopeValue("formats",{ref:F.formats,code:b.code.formats}),P=Q.const("fDef",z0._`${Z}[${w}]`),q=Q.let("fType"),M=Q.let("format");Q.if(z0._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>Q.assign(q,z0._`${P}.type || "string"`).assign(M,z0._`${P}.validate`),()=>Q.assign(q,z0._`"string"`).assign(M,P)),W.fail$data((0,z0.or)(S(),C()));function S(){if(b.strictSchema===!1)return z0.nil;return z0._`${w} && !${M}`}function C(){let _=z.$async?z0._`(${P}.async ? await ${M}(${G}) : ${M}(${G}))`:z0._`${M}(${G})`,k=z0._`(typeof ${M} == "function" ? ${_} : ${M}.test(${G}))`;return z0._`${M} && ${M} !== true && ${q} === ${$} && !${k}`}}function L(){let Z=F.formats[J];if(!Z){S();return}if(Z===!0)return;let[P,q,M]=C(Z);if(P===$)W.pass(_());function S(){if(b.strictSchema===!1){F.logger.warn(k());return}throw Error(k());function k(){return`unknown format "${J}" ignored in schema at path "${H}"`}}function C(k){let S0=k instanceof RegExp?(0,z0.regexpCode)(k):b.code.formats?z0._`${b.code.formats}${(0,z0.getProperty)(J)}`:void 0,g0=Q.scopeValue("formats",{key:J,ref:k,code:S0});if(typeof k=="object"&&!(k instanceof RegExp))return[k.type||"string",k.validate,z0._`${g0}.validate`];return["string",k,g0]}function _(){if(typeof Z=="object"&&!(Z instanceof RegExp)&&Z.async){if(!z.$async)throw Error("async format in sync schema");return z0._`await ${M}(${G})`}return typeof q=="function"?z0._`${M}(${G})`:z0._`${M}.test(${G})`}}}};qb.default=FV});var Eb=N((Nb)=>{Object.defineProperty(Nb,"__esModule",{value:!0});var LV=Ib(),BV=[LV.default];Nb.default=BV});var Sb=N((Tb)=>{Object.defineProperty(Tb,"__esModule",{value:!0});Tb.contentVocabulary=Tb.metadataVocabulary=void 0;Tb.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Tb.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var vb=N((kb)=>{Object.defineProperty(kb,"__esModule",{value:!0});var ZV=$5(),KV=T5(),PV=Mb(),VV=Eb(),Cb=Sb(),jV=[ZV.default,KV.default,(0,PV.default)(),VV.default,Cb.metadataVocabulary,Cb.contentVocabulary];kb.default=jV});var yb=N((xb)=>{Object.defineProperty(xb,"__esModule",{value:!0});xb.DiscrError=void 0;var _b;(function(W){W.Tag="tag",W.Mapping="mapping"})(_b||(xb.DiscrError=_b={}))});var cb=N((ub)=>{Object.defineProperty(ub,"__esModule",{value:!0});var B6=g(),V8=yb(),fb=kW(),qV=D4(),IV=t(),NV={message:({params:{discrError:W,tagName:$}})=>W===V8.DiscrError.Tag?`tag "${$}" must be string`:`value of tag "${$}" must be in oneOf`,params:({params:{discrError:W,tag:$,tagName:Q}})=>B6._`{error: ${W}, tag: ${Q}, tagValue: ${$}}`},EV={keyword:"discriminator",type:"object",schemaType:"object",error:NV,code(W){let{gen:$,data:Q,schema:G,parentSchema:X,it:J}=W,{oneOf:w}=X;if(!J.opts.discriminator)throw Error("discriminator: requires discriminator option");let Y=G.propertyName;if(typeof Y!="string")throw Error("discriminator: requires propertyName");if(G.mapping)throw Error("discriminator: mapping is not supported");if(!w)throw Error("discriminator: requires oneOf keyword");let b=$.let("valid",!1),H=$.const("tag",B6._`${Q}${(0,B6.getProperty)(Y)}`);$.if(B6._`typeof ${H} == "string"`,()=>z(),()=>W.error(!1,{discrError:V8.DiscrError.Tag,tag:H,tagName:Y})),W.ok(b);function z(){let L=U();$.if(!1);for(let Z in L)$.elseIf(B6._`${H} === ${Z}`),$.assign(b,F(L[Z]));$.else(),W.error(!1,{discrError:V8.DiscrError.Mapping,tag:H,tagName:Y}),$.endIf()}function F(L){let Z=$.name("valid"),P=W.subschema({keyword:"oneOf",schemaProp:L},Z);return W.mergeEvaluated(P,B6.Name),Z}function U(){var L;let Z={},P=M(X),q=!0;for(let _=0;_<w.length;_++){let k=w[_];if((k===null||k===void 0?void 0:k.$ref)&&!(0,IV.schemaHasRulesButRef)(k,J.self.RULES)){let g0=k.$ref;if(k=fb.resolveRef.call(J.self,J.schemaEnv.root,J.baseId,g0),k instanceof fb.SchemaEnv)k=k.schema;if(k===void 0)throw new qV.default(J.opts.uriResolver,J.baseId,g0)}let S0=(L=k===null||k===void 0?void 0:k.properties)===null||L===void 0?void 0:L[Y];if(typeof S0!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${Y}"`);q=q&&(P||M(k)),S(S0,_)}if(!q)throw Error(`discriminator: "${Y}" must be required`);return Z;function M({required:_}){return Array.isArray(_)&&_.includes(Y)}function S(_,k){if(_.const)C(_.const,k);else if(_.enum)for(let S0 of _.enum)C(S0,k);else throw Error(`discriminator: "properties/${Y}" must have "const" or "enum"`)}function C(_,k){if(typeof _!="string"||_ in Z)throw Error(`discriminator: "${Y}" values must be unique strings`);Z[_]=k}}}};ub.default=EV});var mb=N((pS,RV)=>{RV.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var M8=N((R0,j8)=>{Object.defineProperty(R0,"__esModule",{value:!0});R0.MissingRefError=R0.ValidationError=R0.CodeGen=R0.Name=R0.nil=R0.stringify=R0.str=R0._=R0.KeywordCxt=R0.Ajv=void 0;var SV=i7(),CV=vb(),kV=cb(),lb=mb(),vV=["/properties"],aW="http://json-schema.org/draft-07/schema";class M4 extends SV.default{_addVocabularies(){if(super._addVocabularies(),CV.default.forEach((W)=>this.addVocabulary(W)),this.opts.discriminator)this.addKeyword(kV.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let W=this.opts.$data?this.$dataMetaSchema(lb,vV):lb;this.addMetaSchema(W,aW,!1),this.refs["http://json-schema.org/schema"]=aW}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(aW)?aW:void 0)}}R0.Ajv=M4;j8.exports=R0=M4;j8.exports.Ajv=M4;Object.defineProperty(R0,"__esModule",{value:!0});R0.default=M4;var _V=z4();Object.defineProperty(R0,"KeywordCxt",{enumerable:!0,get:function(){return _V.KeywordCxt}});var A6=g();Object.defineProperty(R0,"_",{enumerable:!0,get:function(){return A6._}});Object.defineProperty(R0,"str",{enumerable:!0,get:function(){return A6.str}});Object.defineProperty(R0,"stringify",{enumerable:!0,get:function(){return A6.stringify}});Object.defineProperty(R0,"nil",{enumerable:!0,get:function(){return A6.nil}});Object.defineProperty(R0,"Name",{enumerable:!0,get:function(){return A6.Name}});Object.defineProperty(R0,"CodeGen",{enumerable:!0,get:function(){return A6.CodeGen}});var xV=SW();Object.defineProperty(R0,"ValidationError",{enumerable:!0,get:function(){return xV.default}});var hV=D4();Object.defineProperty(R0,"MissingRefError",{enumerable:!0,get:function(){return hV.default}})});var ab=N((rb)=>{Object.defineProperty(rb,"__esModule",{value:!0});rb.formatNames=rb.fastFormats=rb.fullFormats=void 0;function X1(W,$){return{validate:W,compare:$}}rb.fullFormats={date:X1(nb,E8),time:X1(I8(!0),T8),"date-time":X1(gb(!0),ob),"iso-time":X1(I8(),db),"iso-date-time":X1(gb(),tb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pV,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:sV,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:iV,int32:{type:"number",validate:oV},int64:{type:"number",validate:tV},float:{type:"number",validate:ib},double:{type:"number",validate:ib},password:!0,binary:!0};rb.fastFormats={...rb.fullFormats,date:X1(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,E8),time:X1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,T8),"date-time":X1(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ob),"iso-time":X1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,db),"iso-date-time":X1(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,tb),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};rb.formatNames=Object.keys(rb.fullFormats);function uV(W){return W%4===0&&(W%100!==0||W%400===0)}var cV=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,mV=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nb(W){let $=cV.exec(W);if(!$)return!1;let Q=+$[1],G=+$[2],X=+$[3];return G>=1&&G<=12&&X>=1&&X<=(G===2&&uV(Q)?29:mV[G])}function E8(W,$){if(!(W&&$))return;if(W>$)return 1;if(W<$)return-1;return 0}var q8=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function I8(W){return function(Q){let G=q8.exec(Q);if(!G)return!1;let X=+G[1],J=+G[2],w=+G[3],Y=G[4],b=G[5]==="-"?-1:1,H=+(G[6]||0),z=+(G[7]||0);if(H>23||z>59||W&&!Y)return!1;if(X<=23&&J<=59&&w<60)return!0;let F=J-z*b,U=X-H*b-(F<0?1:0);return(U===23||U===-1)&&(F===59||F===-1)&&w<61}}function T8(W,$){if(!(W&&$))return;let Q=new Date("2020-01-01T"+W).valueOf(),G=new Date("2020-01-01T"+$).valueOf();if(!(Q&&G))return;return Q-G}function db(W,$){if(!(W&&$))return;let Q=q8.exec(W),G=q8.exec($);if(!(Q&&G))return;if(W=Q[1]+Q[2]+Q[3],$=G[1]+G[2]+G[3],W>$)return 1;if(W<$)return-1;return 0}var N8=/t|\s/i;function gb(W){let $=I8(W);return function(G){let X=G.split(N8);return X.length===2&&nb(X[0])&&$(X[1])}}function ob(W,$){if(!(W&&$))return;let Q=new Date(W).valueOf(),G=new Date($).valueOf();if(!(Q&&G))return;return Q-G}function tb(W,$){if(!(W&&$))return;let[Q,G]=W.split(N8),[X,J]=$.split(N8),w=E8(Q,X);if(w===void 0)return;return w||T8(G,J)}var lV=/\/|:/,gV=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function pV(W){return lV.test(W)&&gV.test(W)}var pb=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iV(W){return pb.lastIndex=0,pb.test(W)}var nV=-2147483648,dV=2147483647;function oV(W){return Number.isInteger(W)&&W<=dV&&W>=nV}function tV(W){return Number.isInteger(W)}function ib(){return!0}var rV=/[^\\]\\Z/;function sV(W){if(rV.test(W))return!1;try{return new RegExp(W),!0}catch($){return!1}}});var WH=N((eb)=>{Object.defineProperty(eb,"__esModule",{value:!0});eb.formatLimitDefinition=void 0;var eV=M8(),a0=g(),h1=a0.operators,eW={formatMaximum:{okStr:"<=",ok:h1.LTE,fail:h1.GT},formatMinimum:{okStr:">=",ok:h1.GTE,fail:h1.LT},formatExclusiveMaximum:{okStr:"<",ok:h1.LT,fail:h1.GTE},formatExclusiveMinimum:{okStr:">",ok:h1.GT,fail:h1.LTE}},Wj={message:({keyword:W,schemaCode:$})=>a0.str`should be ${eW[W].okStr} ${$}`,params:({keyword:W,schemaCode:$})=>a0._`{comparison: ${eW[W].okStr}, limit: ${$}}`};eb.formatLimitDefinition={keyword:Object.keys(eW),type:"string",schemaType:"string",$data:!0,error:Wj,code(W){let{gen:$,data:Q,schemaCode:G,keyword:X,it:J}=W,{opts:w,self:Y}=J;if(!w.validateFormats)return;let b=new eV.KeywordCxt(J,Y.RULES.all.format.definition,"format");if(b.$data)H();else z();function H(){let U=$.scopeValue("formats",{ref:Y.formats,code:w.code.formats}),L=$.const("fmt",a0._`${U}[${b.schemaCode}]`);W.fail$data((0,a0.or)(a0._`typeof ${L} != "object"`,a0._`${L} instanceof RegExp`,a0._`typeof ${L}.compare != "function"`,F(L)))}function z(){let U=b.schema,L=Y.formats[U];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${X}": format "${U}" does not define "compare" function`);let Z=$.scopeValue("formats",{key:U,ref:L,code:w.code.formats?a0._`${w.code.formats}${(0,a0.getProperty)(U)}`:void 0});W.fail$data(F(Z))}function F(U){return a0._`${U}.compare(${Q}, ${G}) ${eW[X].fail} 0`}},dependencies:["format"]};var $j=(W)=>{return W.addKeyword(eb.formatLimitDefinition),W};eb.default=$j});var XH=N((q4,GH)=>{Object.defineProperty(q4,"__esModule",{value:!0});var O6=ab(),Gj=WH(),C8=g(),$H=new C8.Name("fullFormats"),Xj=new C8.Name("fastFormats"),k8=(W,$={keywords:!0})=>{if(Array.isArray($))return QH(W,$,O6.fullFormats,$H),W;let[Q,G]=$.mode==="fast"?[O6.fastFormats,Xj]:[O6.fullFormats,$H],X=$.formats||O6.formatNames;if(QH(W,X,Q,G),$.keywords)(0,Gj.default)(W);return W};k8.get=(W,$="full")=>{let G=($==="fast"?O6.fastFormats:O6.fullFormats)[W];if(!G)throw Error(`Unknown format "${W}"`);return G};function QH(W,$,Q,G){var X,J;(X=(J=W.opts.code).formats)!==null&&X!==void 0||(J.formats=C8._`require("ajv-formats/dist/formats").${G}`);for(let w of $)W.addFormat(w,Q[w])}GH.exports=q4=k8;Object.defineProperty(q4,"__esModule",{value:!0});q4.default=k8});import{AsyncLocalStorage as kz}from"node:async_hooks";class $1 extends Error{statusCode;rawDetails;code;context;constructor(W,$,Q,G,X){super(W);this.statusCode=$;this.rawDetails=Q;this.code=G;this.context=X;this.name="McpApiError"}}function Rz(W){if(W instanceof $1)return{message:W.message,statusCode:W.statusCode,code:W.code,rawDetails:W.rawDetails,context:W.context};if(W instanceof Error)return{message:W.message};return{message:String(W)}}function Sz(W){let $=W.match(/api key is missing required scopes?:\s*(.+)$/i);if(!$?.[1])return[];return[...new Set($[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function Cz(W){let $=Rz(W),Q=$.message.trim()||"Unknown error",G=Q.toLowerCase(),X=$.rawDetails?.trim()||Q;if($.context?.title||$.context?.description||$.context?.howToFix||$.context?.docsUrl)return{title:$.context.title??($.statusCode===409?"Request conflict":"API request failed"),description:$.context.description??Q,howToFix:$.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:$.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:X};if($.code==="MCP_AUTH_REQUIRED"||G.includes("sequenzy_api_key environment variable is required"))return{title:"Missing MCP API key",description:"The MCP server started without a Sequenzy API key, so it cannot authenticate any tool or resource request.",howToFix:"Add `SEQUENZY_API_KEY` to the MCP server environment, or run `npx @sequenzy/setup` to configure the integration automatically.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if($.statusCode===401||$.code==="UNAUTHORIZED")return{title:"Authentication failed",description:"The MCP server reached Sequenzy, but the current API key was rejected.",howToFix:"Replace `SEQUENZY_API_KEY` with a valid personal API key, then restart the MCP client so it reconnects with fresh credentials.",docsUrl:"https://docs.sequenzy.com/authentication",details:X};if($.code==="COMPANY_CREATE_REQUIRES_PERSONAL_KEY")return{title:"Personal account key required",description:"Company creation is account-level and cannot be performed with a company/workspace-scoped API key.",howToFix:"Create or use a personal account key beginning with `seq_user_` from Account → API Keys, replace `SEQUENZY_API_KEY`, reconnect the MCP client, and retry `create_company`; alternatively, create the company in the Sequenzy dashboard. Widening the current company key or selecting another company will not fix this restriction.",docsUrl:"https://docs.sequenzy.com/authentication",details:X};let J=Sz(Q);if(J.length>0){let w=J.map((H)=>`\`${H}\``).join(", "),Y=J.every((H)=>H.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions",b=J.includes("api_keys:manage")?' This operation manages API keys, so the missing scope cannot be granted through the API by the key that is missing it. If the active key has `account:read`, call `request_api_key_handoff` to get a dashboard link that opens the create-key form prefilled with the name and permissions you need, pass `replaceApiKeyId: "current"` when rotating, and hand the URL to the workspace owner. It creates nothing and never returns a key. If the handoff tool is also denied because `account:read` is missing, open https://sequenzy.com/dashboard directly and choose the matching API Keys page.':"";return{title:"API key permission required",description:`The current API key is valid, but this operation requires the missing ${J.length===1?"scope":"scopes"}: ${w}.`,howToFix:`Permissions can be widened on the key you are already using - no replacement key and no client restart. Call \`get_account\` to read \`apiKeyPermissions\`, then have the key owner open \`apiKeyPermissions.manageUrl\`, edit the key identified by \`apiKeyPermissions.activeKey\`, and enable ${w}. The URL opens Account → API Keys for a \`personal\` key and workspace Settings → API Keys for a \`company\` key. If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and choose the matching API Keys page. When \`apiKeyPermissions.activeKey.type\` is \`company\` and the key holds \`api_keys:manage\`, the agent can instead call \`update_api_key\` with \`apiKeyId\` from \`apiKeyPermissions.activeKey.id\`. Personal keys cannot be changed through \`update_api_key\`. \`scopes\` and \`preset\` REPLACE the whole selection, so pass every scope in \`apiKeyPermissions.scopes\` plus ${w}, or a preset covering all of them (${Y}). Then retry the same tool call - the API reloads the key's permissions on a denied request, so the retry succeeds without reconnecting. Issuing a replacement key and swapping \`SEQUENZY_API_KEY\`, or reauthorizing a hosted OAuth connection with wider permissions, also works but is not required.${b}`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X}}if($.statusCode===403||G.includes("access denied"))return{title:"Access denied",description:"The current API key is valid, but it does not have permission to access the requested company or action.",howToFix:"Use an API key that belongs to the right account, or select a company the key can access before retrying the tool call.",docsUrl:"https://docs.sequenzy.com/authentication",details:X};if(G.includes("no company available")||G.includes("company not found"))return{title:"Company selection required",description:"The MCP server could not resolve a company for this request.",howToFix:"Call `get_account` to inspect available companies, then call `select_company`, or pass `companyId` explicitly in the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if($.statusCode===404||G.includes("not found"))return{title:"Requested resource not found",description:"Sequenzy could not find the requested campaign, template, sequence, company, or subscriber.",howToFix:"List or fetch the resource collection first, then retry the tool with a confirmed ID or email value.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if(G.includes("already exists"))return{title:"Resource already exists",description:"Sequenzy rejected this MCP request because it would create a duplicate resource.",howToFix:"List the existing resources first, reuse the matching resource when appropriate, or retry with a unique name or domain.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if($.statusCode===409)return{title:"Request conflict",description:"Sequenzy rejected this request because the resource changed or an operation is already in progress.",howToFix:"Refresh the resource state, choose the lifecycle action allowed by its current status, and retry at most once.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if($.statusCode===429||G.includes("rate limit"))return{title:"Rate limited",description:"Sequenzy temporarily slowed this MCP request because too many requests were sent too quickly.",howToFix:"Wait briefly before retrying. If the client is looping, reduce retries or add backoff before the next tool call.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if($.code==="NETWORK_ERROR"||G.includes("fetch failed"))return{title:"Network or configuration error",description:"The MCP server could not reach the Sequenzy API from this environment.",howToFix:"Check connectivity and verify `SEQUENZY_API_URL` if you override it in the MCP environment.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if(G.includes("unknown tool")||G.includes("unknown resource"))return{title:"Unsupported MCP request",description:"The client asked for a tool or resource name that this Sequenzy MCP server does not expose.",howToFix:"Refresh the client's tool list and call only the names returned by `list_tools` or `list_resources`.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if(G.includes("is required")||G.includes("invalid"))return{title:"Invalid MCP input",description:"The tool call was missing a required field or included an invalid value.",howToFix:"Review the tool schema, supply the missing argument, and retry the request with corrected input.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};if($.statusCode&&$.statusCode>=500)return{title:"Sequenzy server error",description:"The request reached Sequenzy, but the server could not complete it successfully.",howToFix:"Retry once. If it still fails, keep the details below and consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the details below, adjust the tool input or credentials, and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:X}}function V1(W){let $=Cz(W);return[`Sequenzy MCP error: ${$.title}`,`Description: ${$.description}`,`How to fix: ${$.howToFix}`,`Docs: ${$.docsUrl}`,`Details: ${$.details}`].join(`
|
|
10
|
+
`)}var vz="https://api.sequenzy.com",_z=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),S6=new kz,CQ=!1;function kQ(){CQ=!0}function k4(){return CQ}var vQ=null;function j1(){let W=S6.getStore();if(W)return W.selectedCompanyId??null;return vQ}function v4(W){let $=S6.getStore();if($){$.selectedCompanyId=W;return}vQ=W}function M9(W,$){return S6.run(W,$)}function _Q(){return S6.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??vz}function xQ(){return S6.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function hQ(W,$){let Q=xQ();if(!Q)throw new $1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let G={"Content-Type":W,Authorization:`Bearer ${Q}`},X=$??j1();if(X)G["x-company-id"]=X;return G}function yQ(){if(xQ())return;console.error(V1(new $1("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function k0(W,$){let Q=W[$];return typeof Q==="string"&&Q.trim()!==""?Q.trim():void 0}function xz(W){if(W===void 0)return;if(typeof W==="string")return W.trim()||void 0;return JSON.stringify(W)}function fQ(W){if(!W.trim())return{message:"Request failed"};try{let $=JSON.parse(W);if(typeof $==="string")return{message:$};let Q=typeof $.error==="object"&&$.error!==null?$.error:void 0,G=k0($,"code")??(Q?k0(Q,"code"):void 0),X=(typeof $.error==="string"?$.error:void 0)??(Q?k0(Q,"message"):void 0)??k0($,"message")??k0($,"error")??W,J=k0($,"howToFix")??k0($,"resolution"),w={...k0($,"title")?{title:k0($,"title")}:{},...k0($,"description")?{description:k0($,"description")}:{},...J?{howToFix:J}:{},...k0($,"docsUrl")?{docsUrl:k0($,"docsUrl")}:{}},Y=xz($.details);if(Object.keys(w).length>0||Y)return{message:X,...G?{code:G}:{},...Y?{details:Y}:{},...Object.keys(w).length>0?{context:w}:{}};if(typeof $.error==="string")return{message:$.error,...G?{code:G}:{}};if(Q)return{message:X,...G?{code:G}:{}};return{message:X,...G?{code:G}:{}}}catch{return{message:W}}}async function D(W,$,Q,G){let X=hQ("application/json",G),J;try{J=await fetch(`${_Q()}${$}`,{method:W,headers:X,body:Q?JSON.stringify(Q):void 0})}catch(w){throw new $1(w instanceof Error?w.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!J.ok){let w=await J.text(),Y=fQ(w);throw new $1(Y.message,J.status,Y.details??w,Y.code,Y.context)}return J.json()}async function uQ(W,$,Q,G){let X=new URL(_Q()).origin,J=new URL(W,`${X}/`);if(J.origin!==X){if(!_z.has(J.pathname))throw new $1("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");J=new URL(`${J.pathname}${J.search}`,`${X}/`)}let w;try{w=await fetch(J,{method:"PUT",headers:hQ(Q,G),body:$})}catch(Y){throw new $1(Y instanceof Error?Y.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!w.ok){let Y=await w.text(),b=fQ(Y);throw new $1(b.message,w.status,b.details??Y,b.code,b.context)}}var CM=Object.freeze({status:"aborted"});function V(W,$,Q){function G(Y,b){var H;Object.defineProperty(Y,"_zod",{value:Y._zod??{},enumerable:!1}),(H=Y._zod).traits??(H.traits=new Set),Y._zod.traits.add(W),$(Y,b);for(let z in w.prototype)if(!(z in Y))Object.defineProperty(Y,z,{value:w.prototype[z].bind(Y)});Y._zod.constr=w,Y._zod.def=b}let X=Q?.Parent??Object;class J extends X{}Object.defineProperty(J,"name",{value:W});function w(Y){var b;let H=Q?.Parent?new J:this;G(H,Y),(b=H._zod).deferred??(b.deferred=[]);for(let z of H._zod.deferred)z();return H}return Object.defineProperty(w,"init",{value:G}),Object.defineProperty(w,Symbol.hasInstance,{value:(Y)=>{if(Q?.Parent&&Y instanceof Q.Parent)return!0;return Y?._zod?.traits?.has(W)}}),Object.defineProperty(w,"name",{value:W}),w}var kM=Symbol("zod_brand");class Y1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class C6 extends Error{constructor(W){super(`Encountered unidirectional transform during encode: ${W}`);this.name="ZodEncodeError"}}var _4={};function f0(W){if(W)Object.assign(_4,W);return _4}var o={};SQ(o,{unwrapMessage:()=>k6,uint8ArrayToHex:()=>wD,uint8ArrayToBase64url:()=>XD,uint8ArrayToBase64:()=>nQ,stringifyPrimitive:()=>f4,shallowClone:()=>mQ,safeExtend:()=>az,required:()=>$D,randomString:()=>iz,propertyKeyTypes:()=>T9,promiseAllObject:()=>pz,primitiveTypes:()=>lQ,prefixIssues:()=>H1,pick:()=>tz,partial:()=>WD,optionalKeys:()=>R9,omit:()=>rz,objectClone:()=>mz,numKeys:()=>nz,nullish:()=>v6,normalizeParams:()=>x,mergeDefs:()=>q1,merge:()=>ez,jsonStringifyReplacer:()=>e1,joinValues:()=>x4,issue:()=>$6,isPlainObject:()=>I1,isObject:()=>u1,hexToUint8Array:()=>JD,getSizableOrigin:()=>pQ,getParsedType:()=>dz,getLengthableOrigin:()=>x6,getEnumValues:()=>I9,getElementAtPath:()=>gz,floatSafeRemainder:()=>N9,finalizeIssue:()=>n0,extend:()=>sz,escapeRegex:()=>b1,esc:()=>h4,defineLazy:()=>s,createTransparentProxy:()=>oz,cloneDef:()=>lz,clone:()=>i0,cleanRegex:()=>_6,cleanEnum:()=>QD,captureStackTrace:()=>y4,cached:()=>W6,base64urlToUint8Array:()=>GD,base64ToUint8Array:()=>iQ,assignProp:()=>M1,assertNotEqual:()=>yz,assertNever:()=>uz,assertIs:()=>fz,assertEqual:()=>hz,assert:()=>cz,allowsEval:()=>E9,aborted:()=>N1,NUMBER_FORMAT_RANGES:()=>S9,Class:()=>dQ,BIGINT_FORMAT_RANGES:()=>gQ});function hz(W){return W}function yz(W){return W}function fz(W){}function uz(W){throw Error()}function cz(W){}function I9(W){let $=Object.values(W).filter((G)=>typeof G==="number");return Object.entries(W).filter(([G,X])=>$.indexOf(+G)===-1).map(([G,X])=>X)}function x4(W,$="|"){return W.map((Q)=>f4(Q)).join($)}function e1(W,$){if(typeof $==="bigint")return $.toString();return $}function W6(W){return{get value(){{let Q=W();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function v6(W){return W===null||W===void 0}function _6(W){let $=W.startsWith("^")?1:0,Q=W.endsWith("$")?W.length-1:W.length;return W.slice($,Q)}function N9(W,$){let Q=(W.toString().split(".")[1]||"").length,G=$.toString(),X=(G.split(".")[1]||"").length;if(X===0&&/\d?e-\d?/.test(G)){let b=G.match(/\d?e-(\d?)/);if(b?.[1])X=Number.parseInt(b[1])}let J=Q>X?Q:X,w=Number.parseInt(W.toFixed(J).replace(".","")),Y=Number.parseInt($.toFixed(J).replace(".",""));return w%Y/10**J}var cQ=Symbol("evaluating");function s(W,$,Q){let G=void 0;Object.defineProperty(W,$,{get(){if(G===cQ)return;if(G===void 0)G=cQ,G=Q();return G},set(X){Object.defineProperty(W,$,{value:X})},configurable:!0})}function mz(W){return Object.create(Object.getPrototypeOf(W),Object.getOwnPropertyDescriptors(W))}function M1(W,$,Q){Object.defineProperty(W,$,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function q1(...W){let $={};for(let Q of W){let G=Object.getOwnPropertyDescriptors(Q);Object.assign($,G)}return Object.defineProperties({},$)}function lz(W){return q1(W._zod.def)}function gz(W,$){if(!$)return W;return $.reduce((Q,G)=>Q?.[G],W)}function pz(W){let $=Object.keys(W),Q=$.map((G)=>W[G]);return Promise.all(Q).then((G)=>{let X={};for(let J=0;J<$.length;J++)X[$[J]]=G[J];return X})}function iz(W=10){let Q="";for(let G=0;G<W;G++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function h4(W){return JSON.stringify(W)}var y4="captureStackTrace"in Error?Error.captureStackTrace:(...W)=>{};function u1(W){return typeof W==="object"&&W!==null&&!Array.isArray(W)}var E9=W6(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(W){return!1}});function I1(W){if(u1(W)===!1)return!1;let $=W.constructor;if($===void 0)return!0;let Q=$.prototype;if(u1(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function mQ(W){if(I1(W))return{...W};if(Array.isArray(W))return[...W];return W}function nz(W){let $=0;for(let Q in W)if(Object.prototype.hasOwnProperty.call(W,Q))$++;return $}var dz=(W)=>{let $=typeof W;switch($){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(W)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(W))return"array";if(W===null)return"null";if(W.then&&typeof W.then==="function"&&W.catch&&typeof W.catch==="function")return"promise";if(typeof Map<"u"&&W instanceof Map)return"map";if(typeof Set<"u"&&W instanceof Set)return"set";if(typeof Date<"u"&&W instanceof Date)return"date";if(typeof File<"u"&&W instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${$}`)}},T9=new Set(["string","number","symbol"]),lQ=new Set(["string","number","bigint","boolean","symbol","undefined"]);function b1(W){return W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i0(W,$,Q){let G=new W._zod.constr($??W._zod.def);if(!$||Q?.parent)G._zod.parent=W;return G}function x(W){let $=W;if(!$)return{};if(typeof $==="string")return{error:()=>$};if($?.message!==void 0){if($?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");$.error=$.message}if(delete $.message,typeof $.error==="string")return{...$,error:()=>$.error};return $}function oz(W){let $;return new Proxy({},{get(Q,G,X){return $??($=W()),Reflect.get($,G,X)},set(Q,G,X,J){return $??($=W()),Reflect.set($,G,X,J)},has(Q,G){return $??($=W()),Reflect.has($,G)},deleteProperty(Q,G){return $??($=W()),Reflect.deleteProperty($,G)},ownKeys(Q){return $??($=W()),Reflect.ownKeys($)},getOwnPropertyDescriptor(Q,G){return $??($=W()),Reflect.getOwnPropertyDescriptor($,G)},defineProperty(Q,G,X){return $??($=W()),Reflect.defineProperty($,G,X)}})}function f4(W){if(typeof W==="bigint")return W.toString()+"n";if(typeof W==="string")return`"${W}"`;return`${W}`}function R9(W){return Object.keys(W).filter(($)=>{return W[$]._zod.optin==="optional"&&W[$]._zod.optout==="optional"})}var S9={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},gQ={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function tz(W,$){let Q=W._zod.def,G=q1(W._zod.def,{get shape(){let X={};for(let J in $){if(!(J in Q.shape))throw Error(`Unrecognized key: "${J}"`);if(!$[J])continue;X[J]=Q.shape[J]}return M1(this,"shape",X),X},checks:[]});return i0(W,G)}function rz(W,$){let Q=W._zod.def,G=q1(W._zod.def,{get shape(){let X={...W._zod.def.shape};for(let J in $){if(!(J in Q.shape))throw Error(`Unrecognized key: "${J}"`);if(!$[J])continue;delete X[J]}return M1(this,"shape",X),X},checks:[]});return i0(W,G)}function sz(W,$){if(!I1($))throw Error("Invalid input to extend: expected a plain object");let Q=W._zod.def.checks;if(Q&&Q.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let X=q1(W._zod.def,{get shape(){let J={...W._zod.def.shape,...$};return M1(this,"shape",J),J},checks:[]});return i0(W,X)}function az(W,$){if(!I1($))throw Error("Invalid input to safeExtend: expected a plain object");let Q={...W._zod.def,get shape(){let G={...W._zod.def.shape,...$};return M1(this,"shape",G),G},checks:W._zod.def.checks};return i0(W,Q)}function ez(W,$){let Q=q1(W._zod.def,{get shape(){let G={...W._zod.def.shape,...$._zod.def.shape};return M1(this,"shape",G),G},get catchall(){return $._zod.def.catchall},checks:[]});return i0(W,Q)}function WD(W,$,Q){let G=q1($._zod.def,{get shape(){let X=$._zod.def.shape,J={...X};if(Q)for(let w in Q){if(!(w in X))throw Error(`Unrecognized key: "${w}"`);if(!Q[w])continue;J[w]=W?new W({type:"optional",innerType:X[w]}):X[w]}else for(let w in X)J[w]=W?new W({type:"optional",innerType:X[w]}):X[w];return M1(this,"shape",J),J},checks:[]});return i0($,G)}function $D(W,$,Q){let G=q1($._zod.def,{get shape(){let X=$._zod.def.shape,J={...X};if(Q)for(let w in Q){if(!(w in J))throw Error(`Unrecognized key: "${w}"`);if(!Q[w])continue;J[w]=new W({type:"nonoptional",innerType:X[w]})}else for(let w in X)J[w]=new W({type:"nonoptional",innerType:X[w]});return M1(this,"shape",J),J},checks:[]});return i0($,G)}function N1(W,$=0){if(W.aborted===!0)return!0;for(let Q=$;Q<W.issues.length;Q++)if(W.issues[Q]?.continue!==!0)return!0;return!1}function H1(W,$){return $.map((Q)=>{var G;return(G=Q).path??(G.path=[]),Q.path.unshift(W),Q})}function k6(W){return typeof W==="string"?W:W?.message}function n0(W,$,Q){let G={...W,path:W.path??[]};if(!W.message){let X=k6(W.inst?._zod.def?.error?.(W))??k6($?.error?.(W))??k6(Q.customError?.(W))??k6(Q.localeError?.(W))??"Invalid input";G.message=X}if(delete G.inst,delete G.continue,!$?.reportInput)delete G.input;return G}function pQ(W){if(W instanceof Set)return"set";if(W instanceof Map)return"map";if(W instanceof File)return"file";return"unknown"}function x6(W){if(Array.isArray(W))return"array";if(typeof W==="string")return"string";return"unknown"}function $6(...W){let[$,Q,G]=W;if(typeof $==="string")return{message:$,code:"custom",input:Q,inst:G};return{...$}}function QD(W){return Object.entries(W).filter(([$,Q])=>{return Number.isNaN(Number.parseInt($,10))}).map(($)=>$[1])}function iQ(W){let $=atob(W),Q=new Uint8Array($.length);for(let G=0;G<$.length;G++)Q[G]=$.charCodeAt(G);return Q}function nQ(W){let $="";for(let Q=0;Q<W.length;Q++)$+=String.fromCharCode(W[Q]);return btoa($)}function GD(W){let $=W.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-$.length%4)%4);return iQ($+Q)}function XD(W){return nQ(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function JD(W){let $=W.replace(/^0x/,"");if($.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array($.length/2);for(let G=0;G<$.length;G+=2)Q[G/2]=Number.parseInt($.slice(G,G+2),16);return Q}function wD(W){return Array.from(W).map(($)=>$.toString(16).padStart(2,"0")).join("")}class dQ{constructor(...W){}}var oQ=(W,$)=>{W.name="$ZodError",Object.defineProperty(W,"_zod",{value:W._zod,enumerable:!1}),Object.defineProperty(W,"issues",{value:$,enumerable:!1}),W.message=JSON.stringify($,e1,2),Object.defineProperty(W,"toString",{value:()=>W.message,enumerable:!1})},u4=V("$ZodError",oQ),C9=V("$ZodError",oQ,{Parent:Error});function tQ(W,$=(Q)=>Q.message){let Q={},G=[];for(let X of W.issues)if(X.path.length>0)Q[X.path[0]]=Q[X.path[0]]||[],Q[X.path[0]].push($(X));else G.push($(X));return{formErrors:G,fieldErrors:Q}}function rQ(W,$=(Q)=>Q.message){let Q={_errors:[]},G=(X)=>{for(let J of X.issues)if(J.code==="invalid_union"&&J.errors.length)J.errors.map((w)=>G({issues:w}));else if(J.code==="invalid_key")G({issues:J.issues});else if(J.code==="invalid_element")G({issues:J.issues});else if(J.path.length===0)Q._errors.push($(J));else{let w=Q,Y=0;while(Y<J.path.length){let b=J.path[Y];if(Y!==J.path.length-1)w[b]=w[b]||{_errors:[]};else w[b]=w[b]||{_errors:[]},w[b]._errors.push($(J));w=w[b],Y++}}};return G(W),Q}var c4=(W)=>($,Q,G,X)=>{let J=G?Object.assign(G,{async:!1}):{async:!1},w=$._zod.run({value:Q,issues:[]},J);if(w instanceof Promise)throw new Y1;if(w.issues.length){let Y=new(X?.Err??W)(w.issues.map((b)=>n0(b,J,f0())));throw y4(Y,X?.callee),Y}return w.value};var m4=(W)=>async($,Q,G,X)=>{let J=G?Object.assign(G,{async:!0}):{async:!0},w=$._zod.run({value:Q,issues:[]},J);if(w instanceof Promise)w=await w;if(w.issues.length){let Y=new(X?.Err??W)(w.issues.map((b)=>n0(b,J,f0())));throw y4(Y,X?.callee),Y}return w.value};var h6=(W)=>($,Q,G)=>{let X=G?{...G,async:!1}:{async:!1},J=$._zod.run({value:Q,issues:[]},X);if(J instanceof Promise)throw new Y1;return J.issues.length?{success:!1,error:new(W??u4)(J.issues.map((w)=>n0(w,X,f0())))}:{success:!0,data:J.value}},y6=h6(C9),f6=(W)=>async($,Q,G)=>{let X=G?Object.assign(G,{async:!0}):{async:!0},J=$._zod.run({value:Q,issues:[]},X);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new W(J.issues.map((w)=>n0(w,X,f0())))}:{success:!0,data:J.value}},l4=f6(C9),sQ=(W)=>($,Q,G)=>{let X=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return c4(W)($,Q,X)};var aQ=(W)=>($,Q,G)=>{return c4(W)($,Q,G)};var eQ=(W)=>async($,Q,G)=>{let X=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return m4(W)($,Q,X)};var WG=(W)=>async($,Q,G)=>{return m4(W)($,Q,G)};var $G=(W)=>($,Q,G)=>{let X=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return h6(W)($,Q,X)};var QG=(W)=>($,Q,G)=>{return h6(W)($,Q,G)};var GG=(W)=>async($,Q,G)=>{let X=G?Object.assign(G,{direction:"backward"}):{direction:"backward"};return f6(W)($,Q,X)};var XG=(W)=>async($,Q,G)=>{return f6(W)($,Q,G)};var JG=/^[cC][^\s-]{8,}$/,wG=/^[0-9a-z]+$/,YG=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bG=/^[0-9a-vA-V]{20}$/,HG=/^[A-Za-z0-9]{27}$/,zG=/^[a-zA-Z0-9_-]{21}$/,DG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var FG=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,k9=(W)=>{if(!W)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${W}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var UG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function LG(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}var BG=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,AG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,OG=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ZG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,KG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,v9=/^[A-Za-z0-9_-]*$/,PG=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;var VG=/^\+(?:[0-9]){6,14}[0-9]$/,jG="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",MG=new RegExp(`^${jG}$`);function qG(W){return typeof W.precision==="number"?W.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":W.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${W.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IG(W){return new RegExp(`^${qG(W)}$`)}function NG(W){let $=qG({precision:W.precision}),Q=["Z"];if(W.local)Q.push("");if(W.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let G=`${$}(?:${Q.join("|")})`;return new RegExp(`^${jG}T(?:${G})$`)}var EG=(W)=>{let $=W?`[\\s\\S]{${W?.minimum??0},${W?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${$}$`)};var TG=/^-?\d+$/,RG=/^-?\d+(?:\.\d+)?/,SG=/^(?:true|false)$/i,CG=/^null$/i;var kG=/^[^A-Z]*$/,vG=/^[^a-z]*$/;var B0=V("$ZodCheck",(W,$)=>{var Q;W._zod??(W._zod={}),W._zod.def=$,(Q=W._zod).onattach??(Q.onattach=[])}),_G={number:"number",bigint:"bigint",object:"date"},_9=V("$ZodCheckLessThan",(W,$)=>{B0.init(W,$);let Q=_G[typeof $.value];W._zod.onattach.push((G)=>{let X=G._zod.bag,J=($.inclusive?X.maximum:X.exclusiveMaximum)??Number.POSITIVE_INFINITY;if($.value<J)if($.inclusive)X.maximum=$.value;else X.exclusiveMaximum=$.value}),W._zod.check=(G)=>{if($.inclusive?G.value<=$.value:G.value<$.value)return;G.issues.push({origin:Q,code:"too_big",maximum:$.value,input:G.value,inclusive:$.inclusive,inst:W,continue:!$.abort})}}),x9=V("$ZodCheckGreaterThan",(W,$)=>{B0.init(W,$);let Q=_G[typeof $.value];W._zod.onattach.push((G)=>{let X=G._zod.bag,J=($.inclusive?X.minimum:X.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if($.value>J)if($.inclusive)X.minimum=$.value;else X.exclusiveMinimum=$.value}),W._zod.check=(G)=>{if($.inclusive?G.value>=$.value:G.value>$.value)return;G.issues.push({origin:Q,code:"too_small",minimum:$.value,input:G.value,inclusive:$.inclusive,inst:W,continue:!$.abort})}}),xG=V("$ZodCheckMultipleOf",(W,$)=>{B0.init(W,$),W._zod.onattach.push((Q)=>{var G;(G=Q._zod.bag).multipleOf??(G.multipleOf=$.value)}),W._zod.check=(Q)=>{if(typeof Q.value!==typeof $.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%$.value===BigInt(0):N9(Q.value,$.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:$.value,input:Q.value,inst:W,continue:!$.abort})}}),hG=V("$ZodCheckNumberFormat",(W,$)=>{B0.init(W,$),$.format=$.format||"float64";let Q=$.format?.includes("int"),G=Q?"int":"number",[X,J]=S9[$.format];W._zod.onattach.push((w)=>{let Y=w._zod.bag;if(Y.format=$.format,Y.minimum=X,Y.maximum=J,Q)Y.pattern=TG}),W._zod.check=(w)=>{let Y=w.value;if(Q){if(!Number.isInteger(Y)){w.issues.push({expected:G,format:$.format,code:"invalid_type",continue:!1,input:Y,inst:W});return}if(!Number.isSafeInteger(Y)){if(Y>0)w.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:W,origin:G,continue:!$.abort});else w.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:W,origin:G,continue:!$.abort});return}}if(Y<X)w.issues.push({origin:"number",input:Y,code:"too_small",minimum:X,inclusive:!0,inst:W,continue:!$.abort});if(Y>J)w.issues.push({origin:"number",input:Y,code:"too_big",maximum:J,inst:W})}});var yG=V("$ZodCheckMaxLength",(W,$)=>{var Q;B0.init(W,$),(Q=W._zod.def).when??(Q.when=(G)=>{let X=G.value;return!v6(X)&&X.length!==void 0}),W._zod.onattach.push((G)=>{let X=G._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum<X)G._zod.bag.maximum=$.maximum}),W._zod.check=(G)=>{let X=G.value;if(X.length<=$.maximum)return;let w=x6(X);G.issues.push({origin:w,code:"too_big",maximum:$.maximum,inclusive:!0,input:X,inst:W,continue:!$.abort})}}),fG=V("$ZodCheckMinLength",(W,$)=>{var Q;B0.init(W,$),(Q=W._zod.def).when??(Q.when=(G)=>{let X=G.value;return!v6(X)&&X.length!==void 0}),W._zod.onattach.push((G)=>{let X=G._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>X)G._zod.bag.minimum=$.minimum}),W._zod.check=(G)=>{let X=G.value;if(X.length>=$.minimum)return;let w=x6(X);G.issues.push({origin:w,code:"too_small",minimum:$.minimum,inclusive:!0,input:X,inst:W,continue:!$.abort})}}),uG=V("$ZodCheckLengthEquals",(W,$)=>{var Q;B0.init(W,$),(Q=W._zod.def).when??(Q.when=(G)=>{let X=G.value;return!v6(X)&&X.length!==void 0}),W._zod.onattach.push((G)=>{let X=G._zod.bag;X.minimum=$.length,X.maximum=$.length,X.length=$.length}),W._zod.check=(G)=>{let X=G.value,J=X.length;if(J===$.length)return;let w=x6(X),Y=J>$.length;G.issues.push({origin:w,...Y?{code:"too_big",maximum:$.length}:{code:"too_small",minimum:$.length},inclusive:!0,exact:!0,input:G.value,inst:W,continue:!$.abort})}}),u6=V("$ZodCheckStringFormat",(W,$)=>{var Q,G;if(B0.init(W,$),W._zod.onattach.push((X)=>{let J=X._zod.bag;if(J.format=$.format,$.pattern)J.patterns??(J.patterns=new Set),J.patterns.add($.pattern)}),$.pattern)(Q=W._zod).check??(Q.check=(X)=>{if($.pattern.lastIndex=0,$.pattern.test(X.value))return;X.issues.push({origin:"string",code:"invalid_format",format:$.format,input:X.value,...$.pattern?{pattern:$.pattern.toString()}:{},inst:W,continue:!$.abort})});else(G=W._zod).check??(G.check=()=>{})}),cG=V("$ZodCheckRegex",(W,$)=>{u6.init(W,$),W._zod.check=(Q)=>{if($.pattern.lastIndex=0,$.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:$.pattern.toString(),inst:W,continue:!$.abort})}}),mG=V("$ZodCheckLowerCase",(W,$)=>{$.pattern??($.pattern=kG),u6.init(W,$)}),lG=V("$ZodCheckUpperCase",(W,$)=>{$.pattern??($.pattern=vG),u6.init(W,$)}),gG=V("$ZodCheckIncludes",(W,$)=>{B0.init(W,$);let Q=b1($.includes),G=new RegExp(typeof $.position==="number"?`^.{${$.position}}${Q}`:Q);$.pattern=G,W._zod.onattach.push((X)=>{let J=X._zod.bag;J.patterns??(J.patterns=new Set),J.patterns.add(G)}),W._zod.check=(X)=>{if(X.value.includes($.includes,$.position))return;X.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:$.includes,input:X.value,inst:W,continue:!$.abort})}}),pG=V("$ZodCheckStartsWith",(W,$)=>{B0.init(W,$);let Q=new RegExp(`^${b1($.prefix)}.*`);$.pattern??($.pattern=Q),W._zod.onattach.push((G)=>{let X=G._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(Q)}),W._zod.check=(G)=>{if(G.value.startsWith($.prefix))return;G.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:$.prefix,input:G.value,inst:W,continue:!$.abort})}}),iG=V("$ZodCheckEndsWith",(W,$)=>{B0.init(W,$);let Q=new RegExp(`.*${b1($.suffix)}$`);$.pattern??($.pattern=Q),W._zod.onattach.push((G)=>{let X=G._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(Q)}),W._zod.check=(G)=>{if(G.value.endsWith($.suffix))return;G.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:$.suffix,input:G.value,inst:W,continue:!$.abort})}});var nG=V("$ZodCheckOverwrite",(W,$)=>{B0.init(W,$),W._zod.check=(Q)=>{Q.value=$.tx(Q.value)}});class h9{constructor(W=[]){if(this.content=[],this.indent=0,this)this.args=W}indented(W){this.indent+=1,W(this),this.indent-=1}write(W){if(typeof W==="function"){W(this,{execution:"sync"}),W(this,{execution:"async"});return}let Q=W.split(`
|
|
11
|
+
`).filter((J)=>J),G=Math.min(...Q.map((J)=>J.length-J.trimStart().length)),X=Q.map((J)=>J.slice(G)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of X)this.content.push(J)}compile(){let W=Function,$=this?.args,G=[...(this?.content??[""]).map((X)=>` ${X}`)];return new W(...$,G.join(`
|
|
12
|
+
`))}}var oG={major:4,minor:1,patch:12};var W0=V("$ZodType",(W,$)=>{var Q;W??(W={}),W._zod.def=$,W._zod.bag=W._zod.bag||{},W._zod.version=oG;let G=[...W._zod.def.checks??[]];if(W._zod.traits.has("$ZodCheck"))G.unshift(W);for(let X of G)for(let J of X._zod.onattach)J(W);if(G.length===0)(Q=W._zod).deferred??(Q.deferred=[]),W._zod.deferred?.push(()=>{W._zod.run=W._zod.parse});else{let X=(w,Y,b)=>{let H=N1(w),z;for(let F of Y){if(F._zod.def.when){if(!F._zod.def.when(w))continue}else if(H)continue;let U=w.issues.length,L=F._zod.check(w);if(L instanceof Promise&&b?.async===!1)throw new Y1;if(z||L instanceof Promise)z=(z??Promise.resolve()).then(async()=>{if(await L,w.issues.length===U)return;if(!H)H=N1(w,U)});else{if(w.issues.length===U)continue;if(!H)H=N1(w,U)}}if(z)return z.then(()=>{return w});return w},J=(w,Y,b)=>{if(N1(w))return w.aborted=!0,w;let H=X(Y,G,b);if(H instanceof Promise){if(b.async===!1)throw new Y1;return H.then((z)=>W._zod.parse(z,b))}return W._zod.parse(H,b)};W._zod.run=(w,Y)=>{if(Y.skipChecks)return W._zod.parse(w,Y);if(Y.direction==="backward"){let H=W._zod.parse({value:w.value,issues:[]},{...Y,skipChecks:!0});if(H instanceof Promise)return H.then((z)=>{return J(z,w,Y)});return J(H,w,Y)}let b=W._zod.parse(w,Y);if(b instanceof Promise){if(Y.async===!1)throw new Y1;return b.then((H)=>X(H,G,Y))}return X(b,G,Y)}}W["~standard"]={validate:(X)=>{try{let J=y6(W,X);return J.success?{value:J.data}:{issues:J.error?.issues}}catch(J){return l4(W,X).then((w)=>w.success?{value:w.data}:{issues:w.error?.issues})}},vendor:"zod",version:1}}),n4=V("$ZodString",(W,$)=>{W0.init(W,$),W._zod.pattern=[...W?._zod.bag?.patterns??[]].pop()??EG(W._zod.bag),W._zod.parse=(Q,G)=>{if($.coerce)try{Q.value=String(Q.value)}catch(X){}if(typeof Q.value==="string")return Q;return Q.issues.push({expected:"string",code:"invalid_type",input:Q.value,inst:W}),Q}}),$0=V("$ZodStringFormat",(W,$)=>{u6.init(W,$),n4.init(W,$)}),GX=V("$ZodGUID",(W,$)=>{$.pattern??($.pattern=FG),$0.init(W,$)}),XX=V("$ZodUUID",(W,$)=>{if($.version){let G={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[$.version];if(G===void 0)throw Error(`Invalid UUID version: "${$.version}"`);$.pattern??($.pattern=k9(G))}else $.pattern??($.pattern=k9());$0.init(W,$)}),JX=V("$ZodEmail",(W,$)=>{$.pattern??($.pattern=UG),$0.init(W,$)}),wX=V("$ZodURL",(W,$)=>{$0.init(W,$),W._zod.check=(Q)=>{try{let G=Q.value.trim(),X=new URL(G);if($.hostname){if($.hostname.lastIndex=0,!$.hostname.test(X.hostname))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:PG.source,input:Q.value,inst:W,continue:!$.abort})}if($.protocol){if($.protocol.lastIndex=0,!$.protocol.test(X.protocol.endsWith(":")?X.protocol.slice(0,-1):X.protocol))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:$.protocol.source,input:Q.value,inst:W,continue:!$.abort})}if($.normalize)Q.value=X.href;else Q.value=G;return}catch(G){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:W,continue:!$.abort})}}}),YX=V("$ZodEmoji",(W,$)=>{$.pattern??($.pattern=LG()),$0.init(W,$)}),bX=V("$ZodNanoID",(W,$)=>{$.pattern??($.pattern=zG),$0.init(W,$)}),HX=V("$ZodCUID",(W,$)=>{$.pattern??($.pattern=JG),$0.init(W,$)}),zX=V("$ZodCUID2",(W,$)=>{$.pattern??($.pattern=wG),$0.init(W,$)}),DX=V("$ZodULID",(W,$)=>{$.pattern??($.pattern=YG),$0.init(W,$)}),FX=V("$ZodXID",(W,$)=>{$.pattern??($.pattern=bG),$0.init(W,$)}),UX=V("$ZodKSUID",(W,$)=>{$.pattern??($.pattern=HG),$0.init(W,$)}),LX=V("$ZodISODateTime",(W,$)=>{$.pattern??($.pattern=NG($)),$0.init(W,$)}),BX=V("$ZodISODate",(W,$)=>{$.pattern??($.pattern=MG),$0.init(W,$)}),AX=V("$ZodISOTime",(W,$)=>{$.pattern??($.pattern=IG($)),$0.init(W,$)}),OX=V("$ZodISODuration",(W,$)=>{$.pattern??($.pattern=DG),$0.init(W,$)}),ZX=V("$ZodIPv4",(W,$)=>{$.pattern??($.pattern=BG),$0.init(W,$),W._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.format="ipv4"})}),KX=V("$ZodIPv6",(W,$)=>{$.pattern??($.pattern=AG),$0.init(W,$),W._zod.onattach.push((Q)=>{let G=Q._zod.bag;G.format="ipv6"}),W._zod.check=(Q)=>{try{new URL(`http://[${Q.value}]`)}catch{Q.issues.push({code:"invalid_format",format:"ipv6",input:Q.value,inst:W,continue:!$.abort})}}}),PX=V("$ZodCIDRv4",(W,$)=>{$.pattern??($.pattern=OG),$0.init(W,$)}),VX=V("$ZodCIDRv6",(W,$)=>{$.pattern??($.pattern=ZG),$0.init(W,$),W._zod.check=(Q)=>{let G=Q.value.split("/");try{if(G.length!==2)throw Error();let[X,J]=G;if(!J)throw Error();let w=Number(J);if(`${w}`!==J)throw Error();if(w<0||w>128)throw Error();new URL(`http://[${X}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:W,continue:!$.abort})}}});function jX(W){if(W==="")return!0;if(W.length%4!==0)return!1;try{return atob(W),!0}catch{return!1}}var MX=V("$ZodBase64",(W,$)=>{$.pattern??($.pattern=KG),$0.init(W,$),W._zod.onattach.push((Q)=>{Q._zod.bag.contentEncoding="base64"}),W._zod.check=(Q)=>{if(jX(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:W,continue:!$.abort})}});function zD(W){if(!v9.test(W))return!1;let $=W.replace(/[-_]/g,(G)=>G==="-"?"+":"/"),Q=$.padEnd(Math.ceil($.length/4)*4,"=");return jX(Q)}var qX=V("$ZodBase64URL",(W,$)=>{$.pattern??($.pattern=v9),$0.init(W,$),W._zod.onattach.push((Q)=>{Q._zod.bag.contentEncoding="base64url"}),W._zod.check=(Q)=>{if(zD(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:W,continue:!$.abort})}}),IX=V("$ZodE164",(W,$)=>{$.pattern??($.pattern=VG),$0.init(W,$)});function DD(W,$=null){try{let Q=W.split(".");if(Q.length!==3)return!1;let[G]=Q;if(!G)return!1;let X=JSON.parse(atob(G));if("typ"in X&&X?.typ!=="JWT")return!1;if(!X.alg)return!1;if($&&(!("alg"in X)||X.alg!==$))return!1;return!0}catch{return!1}}var NX=V("$ZodJWT",(W,$)=>{$0.init(W,$),W._zod.check=(Q)=>{if(DD(Q.value,$.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:W,continue:!$.abort})}});var f9=V("$ZodNumber",(W,$)=>{W0.init(W,$),W._zod.pattern=W._zod.bag.pattern??RG,W._zod.parse=(Q,G)=>{if($.coerce)try{Q.value=Number(Q.value)}catch(w){}let X=Q.value;if(typeof X==="number"&&!Number.isNaN(X)&&Number.isFinite(X))return Q;let J=typeof X==="number"?Number.isNaN(X)?"NaN":!Number.isFinite(X)?"Infinity":void 0:void 0;return Q.issues.push({expected:"number",code:"invalid_type",input:X,inst:W,...J?{received:J}:{}}),Q}}),EX=V("$ZodNumber",(W,$)=>{hG.init(W,$),f9.init(W,$)}),TX=V("$ZodBoolean",(W,$)=>{W0.init(W,$),W._zod.pattern=SG,W._zod.parse=(Q,G)=>{if($.coerce)try{Q.value=Boolean(Q.value)}catch(J){}let X=Q.value;if(typeof X==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:X,inst:W}),Q}});var RX=V("$ZodNull",(W,$)=>{W0.init(W,$),W._zod.pattern=CG,W._zod.values=new Set([null]),W._zod.parse=(Q,G)=>{let X=Q.value;if(X===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:X,inst:W}),Q}});var SX=V("$ZodUnknown",(W,$)=>{W0.init(W,$),W._zod.parse=(Q)=>Q}),CX=V("$ZodNever",(W,$)=>{W0.init(W,$),W._zod.parse=(Q,G)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:W}),Q}});function tG(W,$,Q){if(W.issues.length)$.issues.push(...H1(Q,W.issues));$.value[Q]=W.value}var kX=V("$ZodArray",(W,$)=>{W0.init(W,$),W._zod.parse=(Q,G)=>{let X=Q.value;if(!Array.isArray(X))return Q.issues.push({expected:"array",code:"invalid_type",input:X,inst:W}),Q;Q.value=Array(X.length);let J=[];for(let w=0;w<X.length;w++){let Y=X[w],b=$.element._zod.run({value:Y,issues:[]},G);if(b instanceof Promise)J.push(b.then((H)=>tG(H,Q,w)));else tG(b,Q,w)}if(J.length)return Promise.all(J).then(()=>Q);return Q}});function i4(W,$,Q,G){if(W.issues.length)$.issues.push(...H1(Q,W.issues));if(W.value===void 0){if(Q in G)$.value[Q]=void 0}else $.value[Q]=W.value}function vX(W){let $=Object.keys(W.shape);for(let G of $)if(!W.shape?.[G]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${G}": expected a Zod schema`);let Q=R9(W.shape);return{...W,keys:$,keySet:new Set($),numKeys:$.length,optionalKeys:new Set(Q)}}function _X(W,$,Q,G,X,J){let w=[],Y=X.keySet,b=X.catchall._zod,H=b.def.type;for(let z of Object.keys($)){if(Y.has(z))continue;if(H==="never"){w.push(z);continue}let F=b.run({value:$[z],issues:[]},G);if(F instanceof Promise)W.push(F.then((U)=>i4(U,Q,z,$)));else i4(F,Q,z,$)}if(w.length)Q.issues.push({code:"unrecognized_keys",keys:w,input:$,inst:J});if(!W.length)return Q;return Promise.all(W).then(()=>{return Q})}var FD=V("$ZodObject",(W,$)=>{if(W0.init(W,$),!Object.getOwnPropertyDescriptor($,"shape")?.get){let Y=$.shape;Object.defineProperty($,"shape",{get:()=>{let b={...Y};return Object.defineProperty($,"shape",{value:b}),b}})}let G=W6(()=>vX($));s(W._zod,"propValues",()=>{let Y=$.shape,b={};for(let H in Y){let z=Y[H]._zod;if(z.values){b[H]??(b[H]=new Set);for(let F of z.values)b[H].add(F)}}return b});let X=u1,J=$.catchall,w;W._zod.parse=(Y,b)=>{w??(w=G.value);let H=Y.value;if(!X(H))return Y.issues.push({expected:"object",code:"invalid_type",input:H,inst:W}),Y;Y.value={};let z=[],F=w.shape;for(let U of w.keys){let Z=F[U]._zod.run({value:H[U],issues:[]},b);if(Z instanceof Promise)z.push(Z.then((P)=>i4(P,Y,U,H)));else i4(Z,Y,U,H)}if(!J)return z.length?Promise.all(z).then(()=>Y):Y;return _X(z,H,Y,b,G.value,W)}}),xX=V("$ZodObjectJIT",(W,$)=>{FD.init(W,$);let Q=W._zod.parse,G=W6(()=>vX($)),X=(U)=>{let L=new h9(["shape","payload","ctx"]),Z=G.value,P=(C)=>{let _=h4(C);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};L.write("const input = payload.value;");let q=Object.create(null),M=0;for(let C of Z.keys)q[C]=`key_${M++}`;L.write("const newResult = {};");for(let C of Z.keys){let _=q[C],k=h4(C);L.write(`const ${_} = ${P(C)};`),L.write(`
|
|
13
|
+
if (${_}.issues.length) {
|
|
14
|
+
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
|
|
15
15
|
...iss,
|
|
16
16
|
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
17
17
|
})));
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
|
|
21
|
-
if (${
|
|
21
|
+
if (${_}.value === undefined) {
|
|
22
22
|
if (${k} in input) {
|
|
23
23
|
newResult[${k}] = undefined;
|
|
24
24
|
}
|
|
25
25
|
} else {
|
|
26
|
-
newResult[${k}] = ${
|
|
26
|
+
newResult[${k}] = ${_}.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
|
+
`)}L.write("payload.value = newResult;"),L.write("return payload;");let S=L.compile();return(C,_)=>S(U,C,_)},J,w=u1,Y=!_4.jitless,H=Y&&E9.value,z=$.catchall,F;W._zod.parse=(U,L)=>{F??(F=G.value);let Z=U.value;if(!w(Z))return U.issues.push({expected:"object",code:"invalid_type",input:Z,inst:W}),U;if(Y&&H&&L?.async===!1&&L.jitless!==!0){if(!J)J=X($.shape);if(U=J(U,L),!z)return U;return _X([],Z,U,L,F,W)}return Q(U,L)}});function rG(W,$,Q,G){for(let J of W)if(J.issues.length===0)return $.value=J.value,$;let X=W.filter((J)=>!N1(J));if(X.length===1)return $.value=X[0].value,X[0];return $.issues.push({code:"invalid_union",input:$.value,inst:Q,errors:W.map((J)=>J.issues.map((w)=>n0(w,G,f0())))}),$}var u9=V("$ZodUnion",(W,$)=>{W0.init(W,$),s(W._zod,"optin",()=>$.options.some((X)=>X._zod.optin==="optional")?"optional":void 0),s(W._zod,"optout",()=>$.options.some((X)=>X._zod.optout==="optional")?"optional":void 0),s(W._zod,"values",()=>{if($.options.every((X)=>X._zod.values))return new Set($.options.flatMap((X)=>Array.from(X._zod.values)));return}),s(W._zod,"pattern",()=>{if($.options.every((X)=>X._zod.pattern)){let X=$.options.map((J)=>J._zod.pattern);return new RegExp(`^(${X.map((J)=>_6(J.source)).join("|")})$`)}return});let Q=$.options.length===1,G=$.options[0]._zod.run;W._zod.parse=(X,J)=>{if(Q)return G(X,J);let w=!1,Y=[];for(let b of $.options){let H=b._zod.run({value:X.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 rG(Y,X,W,J);return Promise.all(Y).then((b)=>{return rG(b,X,W,J)})}}),hX=V("$ZodDiscriminatedUnion",(W,$)=>{u9.init(W,$);let Q=W._zod.parse;s(W._zod,"propValues",()=>{let X={};for(let J of $.options){let w=J._zod.propValues;if(!w||Object.keys(w).length===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(J)}"`);for(let[Y,b]of Object.entries(w)){if(!X[Y])X[Y]=new Set;for(let H of b)X[Y].add(H)}}return X});let G=W6(()=>{let X=$.options,J=new Map;for(let w of X){let Y=w._zod.propValues?.[$.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${$.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});W._zod.parse=(X,J)=>{let w=X.value;if(!u1(w))return X.issues.push({code:"invalid_type",expected:"object",input:w,inst:W}),X;let Y=G.value.get(w?.[$.discriminator]);if(Y)return Y._zod.run(X,J);if($.unionFallback)return Q(X,J);return X.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:$.discriminator,input:w,path:[$.discriminator],inst:W}),X}}),yX=V("$ZodIntersection",(W,$)=>{W0.init(W,$),W._zod.parse=(Q,G)=>{let X=Q.value,J=$.left._zod.run({value:X,issues:[]},G),w=$.right._zod.run({value:X,issues:[]},G);if(J instanceof Promise||w instanceof Promise)return Promise.all([J,w]).then(([b,H])=>{return sG(Q,b,H)});return sG(Q,J,w)}});function y9(W,$){if(W===$)return{valid:!0,data:W};if(W instanceof Date&&$ instanceof Date&&+W===+$)return{valid:!0,data:W};if(I1(W)&&I1($)){let Q=Object.keys($),G=Object.keys(W).filter((J)=>Q.indexOf(J)!==-1),X={...W,...$};for(let J of G){let w=y9(W[J],$[J]);if(!w.valid)return{valid:!1,mergeErrorPath:[J,...w.mergeErrorPath]};X[J]=w.data}return{valid:!0,data:X}}if(Array.isArray(W)&&Array.isArray($)){if(W.length!==$.length)return{valid:!1,mergeErrorPath:[]};let Q=[];for(let G=0;G<W.length;G++){let X=W[G],J=$[G],w=y9(X,J);if(!w.valid)return{valid:!1,mergeErrorPath:[G,...w.mergeErrorPath]};Q.push(w.data)}return{valid:!0,data:Q}}return{valid:!1,mergeErrorPath:[]}}function sG(W,$,Q){if($.issues.length)W.issues.push(...$.issues);if(Q.issues.length)W.issues.push(...Q.issues);if(N1(W))return W;let G=y9($.value,Q.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return W.value=G.data,W}var fX=V("$ZodRecord",(W,$)=>{W0.init(W,$),W._zod.parse=(Q,G)=>{let X=Q.value;if(!I1(X))return Q.issues.push({expected:"record",code:"invalid_type",input:X,inst:W}),Q;let J=[];if($.keyType._zod.values){let w=$.keyType._zod.values;Q.value={};for(let b of w)if(typeof b==="string"||typeof b==="number"||typeof b==="symbol"){let H=$.valueType._zod.run({value:X[b],issues:[]},G);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 X)if(!w.has(b))Y=Y??[],Y.push(b);if(Y&&Y.length>0)Q.issues.push({code:"unrecognized_keys",input:X,inst:W,keys:Y})}else{Q.value={};for(let w of Reflect.ownKeys(X)){if(w==="__proto__")continue;let Y=$.keyType._zod.run({value:w,issues:[]},G);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,G,f0())),input:w,path:[w],inst:W}),Q.value[Y.value]=Y.value;continue}let b=$.valueType._zod.run({value:X[w],issues:[]},G);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 uX=V("$ZodEnum",(W,$)=>{W0.init(W,$);let Q=I9($.entries),G=new Set(Q);W._zod.values=G,W._zod.pattern=new RegExp(`^(${Q.filter((X)=>T9.has(typeof X)).map((X)=>typeof X==="string"?b1(X):X.toString()).join("|")})$`),W._zod.parse=(X,J)=>{let w=X.value;if(G.has(w))return X;return X.issues.push({code:"invalid_value",values:Q,input:w,inst:W}),X}}),cX=V("$ZodLiteral",(W,$)=>{if(W0.init(W,$),$.values.length===0)throw Error("Cannot create literal schema with no valid values");W._zod.values=new Set($.values),W._zod.pattern=new RegExp(`^(${$.values.map((Q)=>typeof Q==="string"?b1(Q):Q?b1(Q.toString()):String(Q)).join("|")})$`),W._zod.parse=(Q,G)=>{let X=Q.value;if(W._zod.values.has(X))return Q;return Q.issues.push({code:"invalid_value",values:$.values,input:X,inst:W}),Q}});var mX=V("$ZodTransform",(W,$)=>{W0.init(W,$),W._zod.parse=(Q,G)=>{if(G.direction==="backward")throw new C6(W.constructor.name);let X=$.transform(Q.value,Q);if(G.async)return(X instanceof Promise?X:Promise.resolve(X)).then((w)=>{return Q.value=w,Q});if(X instanceof Promise)throw new Y1;return Q.value=X,Q}});function aG(W,$){if(W.issues.length&&$===void 0)return{issues:[],value:void 0};return W}var lX=V("$ZodOptional",(W,$)=>{W0.init(W,$),W._zod.optin="optional",W._zod.optout="optional",s(W._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,void 0]):void 0}),s(W._zod,"pattern",()=>{let Q=$.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)})?$`):void 0}),W._zod.parse=(Q,G)=>{if($.innerType._zod.optin==="optional"){let X=$.innerType._zod.run(Q,G);if(X instanceof Promise)return X.then((J)=>aG(J,Q.value));return aG(X,Q.value)}if(Q.value===void 0)return Q;return $.innerType._zod.run(Q,G)}}),gX=V("$ZodNullable",(W,$)=>{W0.init(W,$),s(W._zod,"optin",()=>$.innerType._zod.optin),s(W._zod,"optout",()=>$.innerType._zod.optout),s(W._zod,"pattern",()=>{let Q=$.innerType._zod.pattern;return Q?new RegExp(`^(${_6(Q.source)}|null)$`):void 0}),s(W._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,null]):void 0}),W._zod.parse=(Q,G)=>{if(Q.value===null)return Q;return $.innerType._zod.run(Q,G)}}),pX=V("$ZodDefault",(W,$)=>{W0.init(W,$),W._zod.optin="optional",s(W._zod,"values",()=>$.innerType._zod.values),W._zod.parse=(Q,G)=>{if(G.direction==="backward")return $.innerType._zod.run(Q,G);if(Q.value===void 0)return Q.value=$.defaultValue,Q;let X=$.innerType._zod.run(Q,G);if(X instanceof Promise)return X.then((J)=>eG(J,$));return eG(X,$)}});function eG(W,$){if(W.value===void 0)W.value=$.defaultValue;return W}var iX=V("$ZodPrefault",(W,$)=>{W0.init(W,$),W._zod.optin="optional",s(W._zod,"values",()=>$.innerType._zod.values),W._zod.parse=(Q,G)=>{if(G.direction==="backward")return $.innerType._zod.run(Q,G);if(Q.value===void 0)Q.value=$.defaultValue;return $.innerType._zod.run(Q,G)}}),nX=V("$ZodNonOptional",(W,$)=>{W0.init(W,$),s(W._zod,"values",()=>{let Q=$.innerType._zod.values;return Q?new Set([...Q].filter((G)=>G!==void 0)):void 0}),W._zod.parse=(Q,G)=>{let X=$.innerType._zod.run(Q,G);if(X instanceof Promise)return X.then((J)=>WX(J,W));return WX(X,W)}});function WX(W,$){if(!W.issues.length&&W.value===void 0)W.issues.push({code:"invalid_type",expected:"nonoptional",input:W.value,inst:$});return W}var dX=V("$ZodCatch",(W,$)=>{W0.init(W,$),s(W._zod,"optin",()=>$.innerType._zod.optin),s(W._zod,"optout",()=>$.innerType._zod.optout),s(W._zod,"values",()=>$.innerType._zod.values),W._zod.parse=(Q,G)=>{if(G.direction==="backward")return $.innerType._zod.run(Q,G);let X=$.innerType._zod.run(Q,G);if(X instanceof Promise)return X.then((J)=>{if(Q.value=J.value,J.issues.length)Q.value=$.catchValue({...Q,error:{issues:J.issues.map((w)=>n0(w,G,f0()))},input:Q.value}),Q.issues=[];return Q});if(Q.value=X.value,X.issues.length)Q.value=$.catchValue({...Q,error:{issues:X.issues.map((J)=>n0(J,G,f0()))},input:Q.value}),Q.issues=[];return Q}});var oX=V("$ZodPipe",(W,$)=>{W0.init(W,$),s(W._zod,"values",()=>$.in._zod.values),s(W._zod,"optin",()=>$.in._zod.optin),s(W._zod,"optout",()=>$.out._zod.optout),s(W._zod,"propValues",()=>$.in._zod.propValues),W._zod.parse=(Q,G)=>{if(G.direction==="backward"){let J=$.out._zod.run(Q,G);if(J instanceof Promise)return J.then((w)=>p4(w,$.in,G));return p4(J,$.in,G)}let X=$.in._zod.run(Q,G);if(X instanceof Promise)return X.then((J)=>p4(J,$.out,G));return p4(X,$.out,G)}});function p4(W,$,Q){if(W.issues.length)return W.aborted=!0,W;return $._zod.run({value:W.value,issues:W.issues},Q)}var tX=V("$ZodReadonly",(W,$)=>{W0.init(W,$),s(W._zod,"propValues",()=>$.innerType._zod.propValues),s(W._zod,"values",()=>$.innerType._zod.values),s(W._zod,"optin",()=>$.innerType._zod.optin),s(W._zod,"optout",()=>$.innerType._zod.optout),W._zod.parse=(Q,G)=>{if(G.direction==="backward")return $.innerType._zod.run(Q,G);let X=$.innerType._zod.run(Q,G);if(X instanceof Promise)return X.then($X);return $X(X)}});function $X(W){return W.value=Object.freeze(W.value),W}var rX=V("$ZodCustom",(W,$)=>{B0.init(W,$),W0.init(W,$),W._zod.parse=(Q,G)=>{return Q},W._zod.check=(Q)=>{let G=Q.value,X=$.fn(G);if(X instanceof Promise)return X.then((J)=>QX(J,Q,G,W));QX(X,Q,G,W);return}});function QX(W,$,Q,G){if(!W){let X={code:"custom",input:Q,inst:G,path:[...G._zod.def.path??[]],continue:!G._zod.def.abort};if(G._zod.def.params)X.params=G._zod.def.params;$.issues.push($6(X))}}var UD=(W)=>{let $=typeof W;switch($){case"number":return Number.isNaN(W)?"NaN":"number";case"object":{if(Array.isArray(W))return"array";if(W===null)return"null";if(Object.getPrototypeOf(W)!==Object.prototype&&W.constructor)return W.constructor.name}}return $},LD=()=>{let W={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 $(G){return W[G]??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(G)=>{switch(G.code){case"invalid_type":return`Invalid input: expected ${G.expected}, received ${UD(G.input)}`;case"invalid_value":if(G.values.length===1)return`Invalid input: expected ${f4(G.values[0])}`;return`Invalid option: expected one of ${x4(G.values,"|")}`;case"too_big":{let X=G.inclusive?"<=":"<",J=$(G.origin);if(J)return`Too big: expected ${G.origin??"value"} to have ${X}${G.maximum.toString()} ${J.unit??"elements"}`;return`Too big: expected ${G.origin??"value"} to be ${X}${G.maximum.toString()}`}case"too_small":{let X=G.inclusive?">=":">",J=$(G.origin);if(J)return`Too small: expected ${G.origin} to have ${X}${G.minimum.toString()} ${J.unit}`;return`Too small: expected ${G.origin} to be ${X}${G.minimum.toString()}`}case"invalid_format":{let X=G;if(X.format==="starts_with")return`Invalid string: must start with "${X.prefix}"`;if(X.format==="ends_with")return`Invalid string: must end with "${X.suffix}"`;if(X.format==="includes")return`Invalid string: must include "${X.includes}"`;if(X.format==="regex")return`Invalid string: must match pattern ${X.pattern}`;return`Invalid ${Q[X.format]??G.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${G.divisor}`;case"unrecognized_keys":return`Unrecognized key${G.keys.length>1?"s":""}: ${x4(G.keys,", ")}`;case"invalid_key":return`Invalid key in ${G.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${G.origin}`;default:return"Invalid input"}}};function c9(){return{localeError:LD()}}var nM=Symbol("ZodOutput"),dM=Symbol("ZodInput");class sX{constructor(){this._map=new WeakMap,this._idmap=new Map}add(W,...$){let Q=$[0];if(this._map.set(W,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,W)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(W){let $=this._map.get(W);if($&&typeof $==="object"&&"id"in $)this._idmap.delete($.id);return this._map.delete(W),this}get(W){let $=W._zod.parent;if($){let Q={...this.get($)??{}};delete Q.id;let G={...Q,...this._map.get(W)};return Object.keys(G).length?G:void 0}return this._map.get(W)}has(W){return this._map.has(W)}}function BD(){return new sX}var c6=BD();function aX(W,$){return new W({type:"string",...x($)})}function eX(W,$){return new W({type:"string",format:"email",check:"string_format",abort:!1,...x($)})}function m9(W,$){return new W({type:"string",format:"guid",check:"string_format",abort:!1,...x($)})}function WJ(W,$){return new W({type:"string",format:"uuid",check:"string_format",abort:!1,...x($)})}function $J(W,$){return new W({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...x($)})}function QJ(W,$){return new W({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...x($)})}function GJ(W,$){return new W({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...x($)})}function XJ(W,$){return new W({type:"string",format:"url",check:"string_format",abort:!1,...x($)})}function JJ(W,$){return new W({type:"string",format:"emoji",check:"string_format",abort:!1,...x($)})}function wJ(W,$){return new W({type:"string",format:"nanoid",check:"string_format",abort:!1,...x($)})}function YJ(W,$){return new W({type:"string",format:"cuid",check:"string_format",abort:!1,...x($)})}function bJ(W,$){return new W({type:"string",format:"cuid2",check:"string_format",abort:!1,...x($)})}function HJ(W,$){return new W({type:"string",format:"ulid",check:"string_format",abort:!1,...x($)})}function zJ(W,$){return new W({type:"string",format:"xid",check:"string_format",abort:!1,...x($)})}function DJ(W,$){return new W({type:"string",format:"ksuid",check:"string_format",abort:!1,...x($)})}function FJ(W,$){return new W({type:"string",format:"ipv4",check:"string_format",abort:!1,...x($)})}function UJ(W,$){return new W({type:"string",format:"ipv6",check:"string_format",abort:!1,...x($)})}function LJ(W,$){return new W({type:"string",format:"cidrv4",check:"string_format",abort:!1,...x($)})}function BJ(W,$){return new W({type:"string",format:"cidrv6",check:"string_format",abort:!1,...x($)})}function AJ(W,$){return new W({type:"string",format:"base64",check:"string_format",abort:!1,...x($)})}function OJ(W,$){return new W({type:"string",format:"base64url",check:"string_format",abort:!1,...x($)})}function ZJ(W,$){return new W({type:"string",format:"e164",check:"string_format",abort:!1,...x($)})}function KJ(W,$){return new W({type:"string",format:"jwt",check:"string_format",abort:!1,...x($)})}function PJ(W,$){return new W({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...x($)})}function VJ(W,$){return new W({type:"string",format:"date",check:"string_format",...x($)})}function jJ(W,$){return new W({type:"string",format:"time",check:"string_format",precision:null,...x($)})}function MJ(W,$){return new W({type:"string",format:"duration",check:"string_format",...x($)})}function qJ(W,$){return new W({type:"number",checks:[],...x($)})}function IJ(W,$){return new W({type:"number",check:"number_format",abort:!1,format:"safeint",...x($)})}function NJ(W,$){return new W({type:"boolean",...x($)})}function EJ(W,$){return new W({type:"null",...x($)})}function TJ(W){return new W({type:"unknown"})}function RJ(W,$){return new W({type:"never",...x($)})}function d4(W,$){return new _9({check:"less_than",...x($),value:W,inclusive:!1})}function m6(W,$){return new _9({check:"less_than",...x($),value:W,inclusive:!0})}function o4(W,$){return new x9({check:"greater_than",...x($),value:W,inclusive:!1})}function l6(W,$){return new x9({check:"greater_than",...x($),value:W,inclusive:!0})}function t4(W,$){return new xG({check:"multiple_of",...x($),value:W})}function r4(W,$){return new yG({check:"max_length",...x($),maximum:W})}function Q6(W,$){return new fG({check:"min_length",...x($),minimum:W})}function s4(W,$){return new uG({check:"length_equals",...x($),length:W})}function l9(W,$){return new cG({check:"string_format",format:"regex",...x($),pattern:W})}function g9(W){return new mG({check:"string_format",format:"lowercase",...x(W)})}function p9(W){return new lG({check:"string_format",format:"uppercase",...x(W)})}function i9(W,$){return new gG({check:"string_format",format:"includes",...x($),includes:W})}function n9(W,$){return new pG({check:"string_format",format:"starts_with",...x($),prefix:W})}function d9(W,$){return new iG({check:"string_format",format:"ends_with",...x($),suffix:W})}function c1(W){return new nG({check:"overwrite",tx:W})}function o9(W){return c1(($)=>$.normalize(W))}function t9(){return c1((W)=>W.trim())}function r9(){return c1((W)=>W.toLowerCase())}function s9(){return c1((W)=>W.toUpperCase())}function SJ(W,$,Q){return new W({type:"array",element:$,...x(Q)})}function CJ(W,$,Q){let G=x(Q);return G.abort??(G.abort=!0),new W({type:"custom",check:"custom",fn:$,...G})}function kJ(W,$,Q){return new W({type:"custom",check:"custom",fn:$,...x(Q)})}function vJ(W){let $=AD((Q)=>{return Q.addIssue=(G)=>{if(typeof G==="string")Q.issues.push($6(G,Q.value,$._zod.def));else{let X=G;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=Q.value),X.inst??(X.inst=$),X.continue??(X.continue=!$._zod.def.abort),Q.issues.push($6(X))}},W(Q.value,Q)});return $}function AD(W,$){let Q=new B0({check:"custom",...x($)});return Q._zod.check=W,Q}function G6(W){return!!W._zod}function E1(W,$){if(G6(W))return y6(W,$);return W.safeParse($)}function a4(W){if(!W)return;let $;if(G6(W))$=W._zod?.def?.shape;else $=W.shape;if(!$)return;if(typeof $==="function")try{return $()}catch{return}return $}function _J(W){if(G6(W)){let J=W._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=W._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 G=W.value;if(G!==void 0)return G;return}var p6={};SQ(p6,{time:()=>W$,duration:()=>$$,datetime:()=>a9,date:()=>e9,ZodISOTime:()=>yJ,ZodISODuration:()=>fJ,ZodISODateTime:()=>xJ,ZodISODate:()=>hJ});var xJ=V("ZodISODateTime",(W,$)=>{LX.init(W,$),X0.init(W,$)});function a9(W){return PJ(xJ,W)}var hJ=V("ZodISODate",(W,$)=>{BX.init(W,$),X0.init(W,$)});function e9(W){return VJ(hJ,W)}var yJ=V("ZodISOTime",(W,$)=>{AX.init(W,$),X0.init(W,$)});function W$(W){return jJ(yJ,W)}var fJ=V("ZodISODuration",(W,$)=>{OX.init(W,$),X0.init(W,$)});function $$(W){return MJ(fJ,W)}var uJ=(W,$)=>{u4.init(W,$),W.name="ZodError",Object.defineProperties(W,{format:{value:(Q)=>rQ(W,Q)},flatten:{value:(Q)=>tQ(W,Q)},addIssue:{value:(Q)=>{W.issues.push(Q),W.message=JSON.stringify(W.issues,e1,2)}},addIssues:{value:(Q)=>{W.issues.push(...Q),W.message=JSON.stringify(W.issues,e1,2)}},isEmpty:{get(){return W.issues.length===0}}})},kq=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=WG(v0),oJ=$G(v0),tJ=QG(v0),rJ=GG(v0),sJ=XG(v0);var b0=V("ZodType",(W,$)=>{return W0.init(W,$),W.def=$,W.type=$.type,Object.defineProperty(W,"_def",{value:$}),W.check=(...Q)=>{return W.clone(o.mergeDefs($,{checks:[...$.checks??[],...Q.map((G)=>typeof G==="function"?{_zod:{check:G,def:{check:"custom"},onattach:[]}}:G)]}))},W.clone=(Q,G)=>i0(W,Q,G),W.brand=()=>W,W.register=(Q,G)=>{return Q.add(W,G),W},W.parse=(Q,G)=>cJ(W,Q,G,{callee:W.parse}),W.safeParse=(Q,G)=>lJ(W,Q,G),W.parseAsync=async(Q,G)=>mJ(W,Q,G,{callee:W.parseAsync}),W.safeParseAsync=async(Q,G)=>gJ(W,Q,G),W.spa=W.safeParseAsync,W.encode=(Q,G)=>pJ(W,Q,G),W.decode=(Q,G)=>iJ(W,Q,G),W.encodeAsync=async(Q,G)=>nJ(W,Q,G),W.decodeAsync=async(Q,G)=>dJ(W,Q,G),W.safeEncode=(Q,G)=>oJ(W,Q,G),W.safeDecode=(Q,G)=>tJ(W,Q,G),W.safeEncodeAsync=async(Q,G)=>rJ(W,Q,G),W.safeDecodeAsync=async(Q,G)=>sJ(W,Q,G),W.refine=(Q,G)=>W.check(FF(Q,G)),W.superRefine=(Q)=>W.check(UF(Q)),W.overwrite=(Q)=>W.check(c1(Q)),W.optional=()=>Y0(W),W.nullable=()=>Ww(W),W.nullish=()=>Y0(Ww(W)),W.nonoptional=(Q)=>wF(W,Q),W.array=()=>p(W),W.or=(Q)=>e([W,Q]),W.and=(Q)=>WW(W,Q),W.transform=(Q)=>G$(W,Jw(Q)),W.default=(Q)=>GF(W,Q),W.prefault=(Q)=>JF(W,Q),W.catch=(Q)=>bF(W,Q),W.pipe=(Q)=>G$(W,Q),W.readonly=()=>DF(W),W.describe=(Q)=>{let G=W.clone();return c6.add(G,{description:Q}),G},Object.defineProperty(W,"description",{get(){return c6.get(W)?.description},configurable:!0}),W.meta=(...Q)=>{if(Q.length===0)return c6.get(W);let G=W.clone();return c6.add(G,Q[0]),G},W.isOptional=()=>W.safeParse(void 0).success,W.isNullable=()=>W.safeParse(null).success,W}),$w=V("_ZodString",(W,$)=>{n4.init(W,$),b0.init(W,$);let Q=W._zod.bag;W.format=Q.format??null,W.minLength=Q.minimum??null,W.maxLength=Q.maximum??null,W.regex=(...G)=>W.check(l9(...G)),W.includes=(...G)=>W.check(i9(...G)),W.startsWith=(...G)=>W.check(n9(...G)),W.endsWith=(...G)=>W.check(d9(...G)),W.min=(...G)=>W.check(Q6(...G)),W.max=(...G)=>W.check(r4(...G)),W.length=(...G)=>W.check(s4(...G)),W.nonempty=(...G)=>W.check(Q6(1,...G)),W.lowercase=(G)=>W.check(g9(G)),W.uppercase=(G)=>W.check(p9(G)),W.trim=()=>W.check(t9()),W.normalize=(...G)=>W.check(o9(...G)),W.toLowerCase=()=>W.check(r9()),W.toUpperCase=()=>W.check(s9())}),ID=V("ZodString",(W,$)=>{n4.init(W,$),$w.init(W,$),W.email=(Q)=>W.check(eX(ND,Q)),W.url=(Q)=>W.check(XJ(ED,Q)),W.jwt=(Q)=>W.check(KJ(lD,Q)),W.emoji=(Q)=>W.check(JJ(TD,Q)),W.guid=(Q)=>W.check(m9(aJ,Q)),W.uuid=(Q)=>W.check(WJ(e4,Q)),W.uuidv4=(Q)=>W.check($J(e4,Q)),W.uuidv6=(Q)=>W.check(QJ(e4,Q)),W.uuidv7=(Q)=>W.check(GJ(e4,Q)),W.nanoid=(Q)=>W.check(wJ(RD,Q)),W.guid=(Q)=>W.check(m9(aJ,Q)),W.cuid=(Q)=>W.check(YJ(SD,Q)),W.cuid2=(Q)=>W.check(bJ(CD,Q)),W.ulid=(Q)=>W.check(HJ(kD,Q)),W.base64=(Q)=>W.check(AJ(uD,Q)),W.base64url=(Q)=>W.check(OJ(cD,Q)),W.xid=(Q)=>W.check(zJ(vD,Q)),W.ksuid=(Q)=>W.check(DJ(_D,Q)),W.ipv4=(Q)=>W.check(FJ(xD,Q)),W.ipv6=(Q)=>W.check(UJ(hD,Q)),W.cidrv4=(Q)=>W.check(LJ(yD,Q)),W.cidrv6=(Q)=>W.check(BJ(fD,Q)),W.e164=(Q)=>W.check(ZJ(mD,Q)),W.datetime=(Q)=>W.check(a9(Q)),W.date=(Q)=>W.check(e9(Q)),W.time=(Q)=>W.check(W$(Q)),W.duration=(Q)=>W.check($$(Q))});function K(W){return aX(ID,W)}var X0=V("ZodStringFormat",(W,$)=>{$0.init(W,$),$w.init(W,$)}),ND=V("ZodEmail",(W,$)=>{JX.init(W,$),X0.init(W,$)});var aJ=V("ZodGUID",(W,$)=>{GX.init(W,$),X0.init(W,$)});var e4=V("ZodUUID",(W,$)=>{XX.init(W,$),X0.init(W,$)});var ED=V("ZodURL",(W,$)=>{wX.init(W,$),X0.init(W,$)});var TD=V("ZodEmoji",(W,$)=>{YX.init(W,$),X0.init(W,$)});var RD=V("ZodNanoID",(W,$)=>{bX.init(W,$),X0.init(W,$)});var SD=V("ZodCUID",(W,$)=>{HX.init(W,$),X0.init(W,$)});var CD=V("ZodCUID2",(W,$)=>{zX.init(W,$),X0.init(W,$)});var kD=V("ZodULID",(W,$)=>{DX.init(W,$),X0.init(W,$)});var vD=V("ZodXID",(W,$)=>{FX.init(W,$),X0.init(W,$)});var _D=V("ZodKSUID",(W,$)=>{UX.init(W,$),X0.init(W,$)});var xD=V("ZodIPv4",(W,$)=>{ZX.init(W,$),X0.init(W,$)});var hD=V("ZodIPv6",(W,$)=>{KX.init(W,$),X0.init(W,$)});var yD=V("ZodCIDRv4",(W,$)=>{PX.init(W,$),X0.init(W,$)});var fD=V("ZodCIDRv6",(W,$)=>{VX.init(W,$),X0.init(W,$)});var uD=V("ZodBase64",(W,$)=>{MX.init(W,$),X0.init(W,$)});var cD=V("ZodBase64URL",(W,$)=>{qX.init(W,$),X0.init(W,$)});var mD=V("ZodE164",(W,$)=>{IX.init(W,$),X0.init(W,$)});var lD=V("ZodJWT",(W,$)=>{NX.init(W,$),X0.init(W,$)});var Qw=V("ZodNumber",(W,$)=>{f9.init(W,$),b0.init(W,$),W.gt=(G,X)=>W.check(o4(G,X)),W.gte=(G,X)=>W.check(l6(G,X)),W.min=(G,X)=>W.check(l6(G,X)),W.lt=(G,X)=>W.check(d4(G,X)),W.lte=(G,X)=>W.check(m6(G,X)),W.max=(G,X)=>W.check(m6(G,X)),W.int=(G)=>W.check(eJ(G)),W.safe=(G)=>W.check(eJ(G)),W.positive=(G)=>W.check(o4(0,G)),W.nonnegative=(G)=>W.check(l6(0,G)),W.negative=(G)=>W.check(d4(0,G)),W.nonpositive=(G)=>W.check(m6(0,G)),W.multipleOf=(G,X)=>W.check(t4(G,X)),W.step=(G,X)=>W.check(t4(G,X)),W.finite=()=>W;let Q=W._zod.bag;W.minValue=Math.max(Q.minimum??Number.NEGATIVE_INFINITY,Q.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,W.maxValue=Math.min(Q.maximum??Number.POSITIVE_INFINITY,Q.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,W.isInt=(Q.format??"").includes("int")||Number.isSafeInteger(Q.multipleOf??0.5),W.isFinite=!0,W.format=Q.format??null});function r(W){return qJ(Qw,W)}var gD=V("ZodNumberFormat",(W,$)=>{EX.init(W,$),Qw.init(W,$)});function eJ(W){return IJ(gD,W)}var pD=V("ZodBoolean",(W,$)=>{TX.init(W,$),b0.init(W,$)});function L0(W){return NJ(pD,W)}var iD=V("ZodNull",(W,$)=>{RX.init(W,$),b0.init(W,$)});function X$(W){return EJ(iD,W)}var nD=V("ZodUnknown",(W,$)=>{SX.init(W,$),b0.init(W,$)});function J0(){return TJ(nD)}var dD=V("ZodNever",(W,$)=>{CX.init(W,$),b0.init(W,$)});function oD(W){return RJ(dD,W)}var tD=V("ZodArray",(W,$)=>{kX.init(W,$),b0.init(W,$),W.element=$.element,W.min=(Q,G)=>W.check(Q6(Q,G)),W.nonempty=(Q)=>W.check(Q6(1,Q)),W.max=(Q,G)=>W.check(r4(Q,G)),W.length=(Q,G)=>W.check(s4(Q,G)),W.unwrap=()=>W.element});function p(W,$){return SJ(tD,W,$)}var Gw=V("ZodObject",(W,$)=>{xX.init(W,$),b0.init(W,$),o.defineLazy(W,"shape",()=>{return $.shape}),W.keyof=()=>I0(Object.keys(W._zod.def.shape)),W.catchall=(Q)=>W.clone({...W._zod.def,catchall:Q}),W.passthrough=()=>W.clone({...W._zod.def,catchall:J0()}),W.loose=()=>W.clone({...W._zod.def,catchall:J0()}),W.strict=()=>W.clone({...W._zod.def,catchall:oD()}),W.strip=()=>W.clone({...W._zod.def,catchall:void 0}),W.extend=(Q)=>{return o.extend(W,Q)},W.safeExtend=(Q)=>{return o.safeExtend(W,Q)},W.merge=(Q)=>o.merge(W,Q),W.pick=(Q)=>o.pick(W,Q),W.omit=(Q)=>o.omit(W,Q),W.partial=(...Q)=>o.partial(ww,W,Q[0]),W.required=(...Q)=>o.required(Yw,W,Q[0])});function E(W,$){let Q={type:"object",shape:W??{},...o.normalizeParams($)};return new Gw(Q)}function j0(W,$){return new Gw({type:"object",shape:W,catchall:J0(),...o.normalizeParams($)})}var Xw=V("ZodUnion",(W,$)=>{u9.init(W,$),b0.init(W,$),W.options=$.options});function e(W,$){return new Xw({type:"union",options:W,...o.normalizeParams($)})}var rD=V("ZodDiscriminatedUnion",(W,$)=>{Xw.init(W,$),hX.init(W,$)});function J$(W,$,Q){return new rD({type:"union",options:$,discriminator:W,...o.normalizeParams(Q)})}var sD=V("ZodIntersection",(W,$)=>{yX.init(W,$),b0.init(W,$)});function WW(W,$){return new sD({type:"intersection",left:W,right:$})}var aD=V("ZodRecord",(W,$)=>{fX.init(W,$),b0.init(W,$),W.keyType=$.keyType,W.valueType=$.valueType});function w0(W,$,Q){return new aD({type:"record",keyType:W,valueType:$,...o.normalizeParams(Q)})}var Q$=V("ZodEnum",(W,$)=>{uX.init(W,$),b0.init(W,$),W.enum=$.entries,W.options=Object.values($.entries);let Q=new Set(Object.keys($.entries));W.extract=(G,X)=>{let J={};for(let w of G)if(Q.has(w))J[w]=$.entries[w];else throw Error(`Key ${w} not found in enum`);return new Q$({...$,checks:[],...o.normalizeParams(X),entries:J})},W.exclude=(G,X)=>{let J={...$.entries};for(let w of G)if(Q.has(w))delete J[w];else throw Error(`Key ${w} not found in enum`);return new Q$({...$,checks:[],...o.normalizeParams(X),entries:J})}});function I0(W,$){let Q=Array.isArray(W)?Object.fromEntries(W.map((G)=>[G,G])):W;return new Q$({type:"enum",entries:Q,...o.normalizeParams($)})}var eD=V("ZodLiteral",(W,$)=>{cX.init(W,$),b0.init(W,$),W.values=new Set($.values),Object.defineProperty(W,"value",{get(){if($.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return $.values[0]}})});function T(W,$){return new eD({type:"literal",values:Array.isArray(W)?W:[W],...o.normalizeParams($)})}var WF=V("ZodTransform",(W,$)=>{mX.init(W,$),b0.init(W,$),W._zod.parse=(Q,G)=>{if(G.direction==="backward")throw new C6(W.constructor.name);Q.addIssue=(J)=>{if(typeof J==="string")Q.issues.push(o.issue(J,Q.value,$));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=W),Q.issues.push(o.issue(w))}};let X=$.transform(Q.value,Q);if(X instanceof Promise)return X.then((J)=>{return Q.value=J,Q});return Q.value=X,Q}});function Jw(W){return new WF({type:"transform",transform:W})}var ww=V("ZodOptional",(W,$)=>{lX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType});function Y0(W){return new ww({type:"optional",innerType:W})}var $F=V("ZodNullable",(W,$)=>{gX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType});function Ww(W){return new $F({type:"nullable",innerType:W})}var QF=V("ZodDefault",(W,$)=>{pX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType,W.removeDefault=W.unwrap});function GF(W,$){return new QF({type:"default",innerType:W,get defaultValue(){return typeof $==="function"?$():o.shallowClone($)}})}var XF=V("ZodPrefault",(W,$)=>{iX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType});function JF(W,$){return new XF({type:"prefault",innerType:W,get defaultValue(){return typeof $==="function"?$():o.shallowClone($)}})}var Yw=V("ZodNonOptional",(W,$)=>{nX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType});function wF(W,$){return new Yw({type:"nonoptional",innerType:W,...o.normalizeParams($)})}var YF=V("ZodCatch",(W,$)=>{dX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType,W.removeCatch=W.unwrap});function bF(W,$){return new YF({type:"catch",innerType:W,catchValue:typeof $==="function"?$:()=>$})}var HF=V("ZodPipe",(W,$)=>{oX.init(W,$),b0.init(W,$),W.in=$.in,W.out=$.out});function G$(W,$){return new HF({type:"pipe",in:W,out:$})}var zF=V("ZodReadonly",(W,$)=>{tX.init(W,$),b0.init(W,$),W.unwrap=()=>W._zod.def.innerType});function DF(W){return new zF({type:"readonly",innerType:W})}var bw=V("ZodCustom",(W,$)=>{rX.init(W,$),b0.init(W,$)});function Hw(W,$){return CJ(bw,W??(()=>!0),$)}function FF(W,$={}){return kJ(bw,W,$)}function UF(W){return vJ(W)}function w$(W,$){return G$(Jw(W),$)}f0(c9());var Y$="2025-11-25";var zw=[Y$,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],T1="io.modelcontextprotocol/related-task",QW="2.0",A0=Hw((W)=>W!==null&&(typeof W==="object"||typeof W==="function")),Dw=e([K(),r().int()]),Fw=K(),EI=j0({ttl:e([r(),X$()]).optional(),pollInterval:r().optional()}),LF=E({ttl:r().optional()}),BF=E({taskId:K()}),b$=j0({progressToken:Dw.optional(),[T1]:BF.optional()}),_0=E({_meta:b$.optional()}),i6=_0.extend({task:LF.optional()}),Uw=(W)=>i6.safeParse(W).success,O0=E({method:K(),params:_0.loose().optional()}),u0=E({_meta:b$.optional()}),c0=E({method:K(),params:u0.loose().optional()}),Z0=j0({_meta:b$.optional()}),GW=e([K(),r().int()]),Lw=E({jsonrpc:T(QW),id:GW,...O0.shape}).strict(),H$=(W)=>Lw.safeParse(W).success,Bw=E({jsonrpc:T(QW),...c0.shape}).strict(),Aw=(W)=>Bw.safeParse(W).success,z$=E({jsonrpc:T(QW),id:GW,result:Z0}).strict(),n6=(W)=>z$.safeParse(W).success;var i;(function(W){W[W.ConnectionClosed=-32000]="ConnectionClosed",W[W.RequestTimeout=-32001]="RequestTimeout",W[W.ParseError=-32700]="ParseError",W[W.InvalidRequest=-32600]="InvalidRequest",W[W.MethodNotFound=-32601]="MethodNotFound",W[W.InvalidParams=-32602]="InvalidParams",W[W.InternalError=-32603]="InternalError",W[W.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(i||(i={}));var D$=E({jsonrpc:T(QW),id:GW.optional(),error:E({code:r().int(),message:K(),data:J0().optional()})}).strict();var Ow=(W)=>D$.safeParse(W).success;var Zw=e([Lw,Bw,z$,D$]),TI=e([z$,D$]),XW=Z0.strict(),AF=u0.extend({requestId:GW.optional(),reason:K().optional()}),JW=c0.extend({method:T("notifications/cancelled"),params:AF}),OF=E({src:K(),mimeType:K().optional(),sizes:p(K()).optional(),theme:I0(["light","dark"]).optional()}),d6=E({icons:p(OF).optional()}),X6=E({name:K(),title:K().optional()}),Kw=X6.extend({...X6.shape,...d6.shape,version:K(),websiteUrl:K().optional(),description:K().optional()}),ZF=WW(E({applyDefaults:L0().optional()}),w0(K(),J0())),KF=w$((W)=>{if(W&&typeof W==="object"&&!Array.isArray(W)){if(Object.keys(W).length===0)return{form:{}}}return W},WW(E({form:ZF.optional(),url:A0.optional()}),w0(K(),J0()).optional())),PF=j0({list:A0.optional(),cancel:A0.optional(),requests:j0({sampling:j0({createMessage:A0.optional()}).optional(),elicitation:j0({create:A0.optional()}).optional()}).optional()}),VF=j0({list:A0.optional(),cancel:A0.optional(),requests:j0({tools:j0({call:A0.optional()}).optional()}).optional()}),jF=E({experimental:w0(K(),A0).optional(),sampling:E({context:A0.optional(),tools:A0.optional()}).optional(),elicitation:KF.optional(),roots:E({listChanged:L0().optional()}).optional(),tasks:PF.optional()}),MF=_0.extend({protocolVersion:K(),capabilities:jF,clientInfo:Kw}),F$=O0.extend({method:T("initialize"),params:MF});var qF=E({experimental:w0(K(),A0).optional(),logging:A0.optional(),completions:A0.optional(),prompts:E({listChanged:L0().optional()}).optional(),resources:E({subscribe:L0().optional(),listChanged:L0().optional()}).optional(),tools:E({listChanged:L0().optional()}).optional(),tasks:VF.optional()}),IF=Z0.extend({protocolVersion:K(),capabilities:qF,serverInfo:Kw,instructions:K().optional()}),U$=c0.extend({method:T("notifications/initialized"),params:u0.optional()});var wW=O0.extend({method:T("ping"),params:_0.optional()}),NF=E({progress:r(),total:Y0(r()),message:Y0(K())}),EF=E({...u0.shape,...NF.shape,progressToken:Dw}),YW=c0.extend({method:T("notifications/progress"),params:EF}),TF=_0.extend({cursor:Fw.optional()}),o6=O0.extend({params:TF.optional()}),t6=Z0.extend({nextCursor:Fw.optional()}),RF=I0(["working","input_required","completed","failed","cancelled"]),r6=E({taskId:K(),status:RF,ttl:e([r(),X$()]),createdAt:K(),lastUpdatedAt:K(),pollInterval:Y0(r()),statusMessage:Y0(K())}),J6=Z0.extend({task:r6}),SF=u0.merge(r6),s6=c0.extend({method:T("notifications/tasks/status"),params:SF}),bW=O0.extend({method:T("tasks/get"),params:_0.extend({taskId:K()})}),HW=Z0.merge(r6),zW=O0.extend({method:T("tasks/result"),params:_0.extend({taskId:K()})}),RI=Z0.loose(),DW=o6.extend({method:T("tasks/list")}),FW=t6.extend({tasks:p(r6)}),UW=O0.extend({method:T("tasks/cancel"),params:_0.extend({taskId:K()})}),Pw=Z0.merge(r6),Vw=E({uri:K(),mimeType:Y0(K()),_meta:w0(K(),J0()).optional()}),jw=Vw.extend({text:K()}),L$=K().refine((W)=>{try{return atob(W),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mw=Vw.extend({blob:L$}),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({...X6.shape,...d6.shape,uri:K(),description:Y0(K()),mimeType:Y0(K()),annotations:w6.optional(),_meta:Y0(j0({}))}),CF=E({...X6.shape,...d6.shape,uriTemplate:K(),description:Y0(K()),mimeType:Y0(K()),annotations:w6.optional(),_meta:Y0(j0({}))}),B$=o6.extend({method:T("resources/list")}),kF=t6.extend({resources:p(qw)}),vF=o6.extend({method:T("resources/templates/list")}),_F=t6.extend({resourceTemplates:p(CF)}),A$=_0.extend({uri:K()}),xF=A$,O$=O0.extend({method:T("resources/read"),params:xF}),hF=Z0.extend({contents:p(e([jw,Mw]))}),yF=c0.extend({method:T("notifications/resources/list_changed"),params:u0.optional()}),fF=A$,uF=O0.extend({method:T("resources/subscribe"),params:fF}),cF=A$,mF=O0.extend({method:T("resources/unsubscribe"),params:cF}),lF=u0.extend({uri:K()}),gF=c0.extend({method:T("notifications/resources/updated"),params:lF}),pF=E({name:K(),description:Y0(K()),required:Y0(L0())}),iF=E({...X6.shape,...d6.shape,description:Y0(K()),arguments:Y0(p(pF)),_meta:Y0(j0({}))}),nF=o6.extend({method:T("prompts/list")}),dF=t6.extend({prompts:p(iF)}),oF=_0.extend({name:K(),arguments:w0(K(),K()).optional()}),tF=O0.extend({method:T("prompts/get"),params:oF}),Z$=E({type:T("text"),text:K(),annotations:w6.optional(),_meta:w0(K(),J0()).optional()}),K$=E({type:T("image"),data:L$,mimeType:K(),annotations:w6.optional(),_meta:w0(K(),J0()).optional()}),P$=E({type:T("audio"),data:L$,mimeType:K(),annotations:w6.optional(),_meta:w0(K(),J0()).optional()}),rF=E({type:T("tool_use"),name:K(),id:K(),input:w0(K(),J0()),_meta:w0(K(),J0()).optional()}),sF=E({type:T("resource"),resource:e([jw,Mw]),annotations:w6.optional(),_meta:w0(K(),J0()).optional()}),aF=qw.extend({type:T("resource_link")}),V$=e([Z$,K$,P$,aF,sF]),eF=E({role:a6,content:V$}),WU=Z0.extend({description:K().optional(),messages:p(eF)}),$U=c0.extend({method:T("notifications/prompts/list_changed"),params:u0.optional()}),QU=E({title:K().optional(),readOnlyHint:L0().optional(),destructiveHint:L0().optional(),idempotentHint:L0().optional(),openWorldHint:L0().optional()}),GU=E({taskSupport:I0(["required","optional","forbidden"]).optional()}),Iw=E({...X6.shape,...d6.shape,description:K().optional(),inputSchema:E({type:T("object"),properties:w0(K(),A0).optional(),required:p(K()).optional()}).catchall(J0()),outputSchema:E({type:T("object"),properties:w0(K(),A0).optional(),required:p(K()).optional()}).catchall(J0()).optional(),annotations:QU.optional(),execution:GU.optional(),_meta:w0(K(),J0()).optional()}),j$=o6.extend({method:T("tools/list")}),XU=t6.extend({tools:p(Iw)}),LW=Z0.extend({content:p(V$).default([]),structuredContent:w0(K(),J0()).optional(),isError:L0().optional()}),SI=LW.or(Z0.extend({toolResult:J0()})),JU=i6.extend({name:K(),arguments:w0(K(),J0()).optional()}),e6=O0.extend({method:T("tools/call"),params:JU}),wU=c0.extend({method:T("notifications/tools/list_changed"),params:u0.optional()}),CI=E({autoRefresh:L0().default(!0),debounceMs:r().int().nonnegative().default(300)}),W4=I0(["debug","info","notice","warning","error","critical","alert","emergency"]),YU=_0.extend({level:W4}),M$=O0.extend({method:T("logging/setLevel"),params:YU}),bU=u0.extend({level:W4,logger:K().optional(),data:J0()}),HU=c0.extend({method:T("notifications/message"),params:bU}),zU=E({name:K().optional()}),DU=E({hints:p(zU).optional(),costPriority:r().min(0).max(1).optional(),speedPriority:r().min(0).max(1).optional(),intelligencePriority:r().min(0).max(1).optional()}),FU=E({mode:I0(["auto","required","none"]).optional()}),UU=E({type:T("tool_result"),toolUseId:K().describe("The unique identifier for the corresponding tool call."),content:p(V$).default([]),structuredContent:E({}).loose().optional(),isError:L0().optional(),_meta:w0(K(),J0()).optional()}),LU=J$("type",[Z$,K$,P$]),$W=J$("type",[Z$,K$,P$,rF,UU]),BU=E({role:a6,content:e([$W,p($W)]),_meta:w0(K(),J0()).optional()}),AU=i6.extend({messages:p(BU),modelPreferences:DU.optional(),systemPrompt:K().optional(),includeContext:I0(["none","thisServer","allServers"]).optional(),temperature:r().optional(),maxTokens:r().int(),stopSequences:p(K()).optional(),metadata:A0.optional(),tools:p(Iw).optional(),toolChoice:FU.optional()}),OU=O0.extend({method:T("sampling/createMessage"),params:AU}),q$=Z0.extend({model:K(),stopReason:Y0(I0(["endTurn","stopSequence","maxTokens"]).or(K())),role:a6,content:LU}),I$=Z0.extend({model:K(),stopReason:Y0(I0(["endTurn","stopSequence","maxTokens","toolUse"]).or(K())),role:a6,content:e([$W,p($W)])}),ZU=E({type:T("boolean"),title:K().optional(),description:K().optional(),default:L0().optional()}),KU=E({type:T("string"),title:K().optional(),description:K().optional(),minLength:r().optional(),maxLength:r().optional(),format:I0(["email","uri","date","date-time"]).optional(),default:K().optional()}),PU=E({type:I0(["number","integer"]),title:K().optional(),description:K().optional(),minimum:r().optional(),maximum:r().optional(),default:r().optional()}),VU=E({type:T("string"),title:K().optional(),description:K().optional(),enum:p(K()),default:K().optional()}),jU=E({type:T("string"),title:K().optional(),description:K().optional(),oneOf:p(E({const:K(),title:K()})),default:K().optional()}),MU=E({type:T("string"),title:K().optional(),description:K().optional(),enum:p(K()),enumNames:p(K()).optional(),default:K().optional()}),qU=e([VU,jU]),IU=E({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({type:T("string"),enum:p(K())}),default:p(K()).optional()}),NU=E({type:T("array"),title:K().optional(),description:K().optional(),minItems:r().optional(),maxItems:r().optional(),items:E({anyOf:p(E({const:K(),title:K()}))}),default:p(K()).optional()}),EU=e([IU,NU]),TU=e([MU,qU,EU]),RU=e([TU,ZU,KU,PU]),SU=i6.extend({mode:T("form").optional(),message:K(),requestedSchema:E({type:T("object"),properties:w0(K(),RU),required:p(K()).optional()})}),CU=i6.extend({mode:T("url"),message:K(),elicitationId:K(),url:K().url()}),kU=e([SU,CU]),vU=O0.extend({method:T("elicitation/create"),params:kU}),_U=u0.extend({elicitationId:K()}),xU=c0.extend({method:T("notifications/elicitation/complete"),params:_U}),BW=Z0.extend({action:I0(["accept","decline","cancel"]),content:w$((W)=>W===null?void 0:W,w0(K(),e([K(),r(),L0(),p(K())])).optional())}),hU=E({type:T("ref/resource"),uri:K()});var yU=E({type:T("ref/prompt"),name:K()}),fU=_0.extend({ref:e([yU,hU]),argument:E({name:K(),value:K()}),context:E({arguments:w0(K(),K()).optional()}).optional()}),uU=O0.extend({method:T("completion/complete"),params:fU});var cU=Z0.extend({completion:j0({values:p(K()).max(100),total:Y0(r().int()),hasMore:Y0(L0())})}),mU=E({uri:K().startsWith("file://"),name:K().optional(),_meta:w0(K(),J0()).optional()}),lU=O0.extend({method:T("roots/list"),params:_0.optional()}),N$=Z0.extend({roots:p(mU)}),gU=c0.extend({method:T("notifications/roots/list_changed"),params:u0.optional()}),kI=e([wW,F$,uU,M$,tF,nF,B$,vF,O$,uF,mF,e6,j$,bW,zW,DW,UW]),vI=e([JW,YW,U$,gU,s6]),_I=e([XW,q$,I$,BW,N$,HW,FW,J6]),xI=e([wW,OU,vU,lU,bW,zW,DW,UW]),hI=e([JW,YW,HU,gF,yF,wU,$U,s6,xU]),yI=e([XW,IF,cU,WU,dF,kF,_F,hF,LW,XU,HW,FW,J6]);class l extends Error{constructor(W,$,Q){super(`MCP error ${W}: ${$}`);this.code=W,this.data=Q,this.name="McpError"}static fromError(W,$,Q){if(W===i.UrlElicitationRequired&&Q){let G=Q;if(G.elicitations)return new Nw(G.elicitations,$)}return new l(W,$,Q)}}class Nw extends l{constructor(W,$=`URL elicitation${W.length>1?"s":""} required`){super(i.UrlElicitationRequired,$,{elicitations:W})}get elicitations(){return this.data?.elicitations??[]}}function R1(W){return W==="completed"||W==="failed"||W==="cancelled"}var pU=Symbol("Let zodToJsonSchema decide on which parser to use");var AN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function E$(W){let Q=a4(W)?.method;if(!Q)throw Error("Schema is missing a method literal");let G=_J(Q);if(typeof G!=="string")throw Error("Schema method literal must be a string");return G}function T$(W,$){let Q=E1(W,$);if(!Q.success)throw Q.error;return Q.data}var rU=60000;class R${constructor(W){if(this._options=W,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(JW,($)=>{this._oncancel($)}),this.setNotificationHandler(YW,($)=>{this._onprogress($)}),this.setRequestHandler(wW,($)=>({})),this._taskStore=W?.taskStore,this._taskMessageQueue=W?.taskMessageQueue,this._taskStore)this.setRequestHandler(bW,async($,Q)=>{let G=await this._taskStore.getTask($.params.taskId,Q.sessionId);if(!G)throw new l(i.InvalidParams,"Failed to retrieve task: Task not found");return{...G}}),this.setRequestHandler(zW,async($,Q)=>{let G=async()=>{let X=$.params.taskId;if(this._taskMessageQueue){let w;while(w=await this._taskMessageQueue.dequeue(X,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(X,Q.sessionId);if(!J)throw new l(i.InvalidParams,`Task not found: ${X}`);if(!R1(J.status))return await this._waitForTaskUpdate(X,Q.signal),await G();if(R1(J.status)){let w=await this._taskStore.getTaskResult(X,Q.sessionId);return this._clearTaskQueue(X),{...w,_meta:{...w._meta,[T1]:{taskId:X}}}}return await G()};return await G()}),this.setRequestHandler(DW,async($,Q)=>{try{let{tasks:G,nextCursor:X}=await this._taskStore.listTasks($.params?.cursor,Q.sessionId);return{tasks:G,nextCursor:X,_meta:{}}}catch(G){throw new l(i.InvalidParams,`Failed to list tasks: ${G instanceof Error?G.message:String(G)}`)}}),this.setRequestHandler(UW,async($,Q)=>{try{let G=await this._taskStore.getTask($.params.taskId,Q.sessionId);if(!G)throw new l(i.InvalidParams,`Task not found: ${$.params.taskId}`);if(R1(G.status))throw new l(i.InvalidParams,`Cannot cancel task in terminal status: ${G.status}`);await this._taskStore.updateTaskStatus($.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue($.params.taskId);let X=await this._taskStore.getTask($.params.taskId,Q.sessionId);if(!X)throw new l(i.InvalidParams,`Task not found after cancellation: ${$.params.taskId}`);return{_meta:{},...X}}catch(G){if(G instanceof l)throw G;throw new l(i.InvalidRequest,`Failed to cancel task: ${G instanceof Error?G.message:String(G)}`)}})}async _oncancel(W){if(!W.params.requestId)return;this._requestHandlerAbortControllers.get(W.params.requestId)?.abort(W.params.reason)}_setupTimeout(W,$,Q,G,X=!1){this._timeoutInfo.set(W,{timeoutId:setTimeout(G,$),startTime:Date.now(),timeout:$,maxTotalTimeout:Q,resetTimeoutOnProgress:X,onTimeout:G})}_resetTimeout(W){let $=this._timeoutInfo.get(W);if(!$)return!1;let Q=Date.now()-$.startTime;if($.maxTotalTimeout&&Q>=$.maxTotalTimeout)throw this._timeoutInfo.delete(W),l.fromError(i.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:$.maxTotalTimeout,totalElapsed:Q});return clearTimeout($.timeoutId),$.timeoutId=setTimeout($.onTimeout,$.timeout),!0}_cleanupTimeout(W){let $=this._timeoutInfo.get(W);if($)clearTimeout($.timeoutId),this._timeoutInfo.delete(W)}async connect(W){this._transport=W;let $=this.transport?.onclose;this._transport.onclose=()=>{$?.(),this._onclose()};let Q=this.transport?.onerror;this._transport.onerror=(X)=>{Q?.(X),this._onerror(X)};let G=this._transport?.onmessage;this._transport.onmessage=(X,J)=>{if(G?.(X,J),n6(X)||Ow(X))this._onresponse(X);else if(H$(X))this._onrequest(X,J);else if(Aw(X))this._onnotification(X);else this._onerror(Error(`Unknown message type: ${JSON.stringify(X)}`))},await this._transport.start()}_onclose(){let W=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let $=l.fromError(i.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Q of W.values())Q($)}_onerror(W){this.onerror?.(W)}_onnotification(W){let $=this._notificationHandlers.get(W.method)??this.fallbackNotificationHandler;if($===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(W.method)??this.fallbackRequestHandler,G=this._transport,X=W.params?._meta?.[T1]?.taskId;if(Q===void 0){let H={jsonrpc:"2.0",id:W.id,error:{code:i.MethodNotFound,message:"Method not found"}};if(X&&this._taskMessageQueue)this._enqueueTaskMessage(X,{type:"error",message:H,timestamp:Date.now()},G?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else G?.send(H).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let J=new AbortController;this._requestHandlerAbortControllers.set(W.id,J);let w=Uw(W.params)?W.params.task:void 0,Y=this._taskStore?this.requestTaskStore(W,G?.sessionId):void 0,b={signal:J.signal,sessionId:G?.sessionId,_meta:W.params?._meta,sendNotification:async(H)=>{let z={relatedRequestId:W.id};if(X)z.relatedTask={taskId:X};await this.notification(H,z)},sendRequest:async(H,z,F)=>{let U={...F,relatedRequestId:W.id};if(X&&!U.relatedTask)U.relatedTask={taskId:X};let L=U.relatedTask?.taskId??X;if(L&&Y)await Y.updateTaskStatus(L,"input_required");return await this.request(H,z,U)},authInfo:$?.authInfo,requestId:W.id,requestInfo:$?.requestInfo,taskId:X,taskStore:Y,taskRequestedTtl:w?.ttl,closeSSEStream:$?.closeSSEStream,closeStandaloneSSEStream:$?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(w)this.assertTaskHandlerCapability(W.method)}).then(()=>Q(W,b)).then(async(H)=>{if(J.signal.aborted)return;let z={result:H,jsonrpc:"2.0",id:W.id};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"response",message:z,timestamp:Date.now()},G?.sessionId);else await G?.send(z)},async(H)=>{if(J.signal.aborted)return;let z={jsonrpc:"2.0",id:W.id,error:{code:Number.isSafeInteger(H.code)?H.code:i.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(X&&this._taskMessageQueue)await this._enqueueTaskMessage(X,{type:"error",message:z,timestamp:Date.now()},G?.sessionId);else await G?.send(z)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{this._requestHandlerAbortControllers.delete(W.id)})}_onprogress(W){let{progressToken:$,...Q}=W.params,G=Number($),X=this._progressHandlers.get(G);if(!X){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(W)}`));return}let J=this._responseHandlers.get(G),w=this._timeoutInfo.get(G);if(w&&J&&w.resetTimeoutOnProgress)try{this._resetTimeout(G)}catch(Y){this._responseHandlers.delete(G),this._progressHandlers.delete(G),this._cleanupTimeout(G),J(Y);return}X(Q)}_onresponse(W){let $=Number(W.id),Q=this._requestResolvers.get($);if(Q){if(this._requestResolvers.delete($),n6(W))Q(W);else{let J=new l(W.error.code,W.error.message,W.error.data);Q(J)}return}let G=this._responseHandlers.get($);if(G===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(W)}`));return}this._responseHandlers.delete($),this._cleanupTimeout($);let X=!1;if(n6(W)&&W.result&&typeof W.result==="object"){let J=W.result;if(J.task&&typeof J.task==="object"){let w=J.task;if(typeof w.taskId==="string")X=!0,this._taskProgressTokens.set(w.taskId,$)}}if(!X)this._progressHandlers.delete($);if(n6(W))G(W);else{let J=l.fromError(W.error.code,W.error.message,W.error.data);G(J)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(W,$,Q){let{task:G}=Q??{};if(!G){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 X;try{let J=await this.request(W,J6,Q);if(J.task)X=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:X},Q);if(yield{type:"taskStatus",task:w},R1(w.status)){if(w.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:X},$,Q)};else if(w.status==="failed")yield{type:"error",error:new l(i.InternalError,`Task ${X} failed`)};else if(w.status==="cancelled")yield{type:"error",error:new l(i.InternalError,`Task ${X} was cancelled`)};return}if(w.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:X},$,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:G,resumptionToken:X,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(W.method),w)this.assertTaskCapability(W.method)}catch(M){z(M);return}Q?.signal?.throwIfAborted();let F=this._requestMessageId++,U={...W,jsonrpc:"2.0",id:F};if(Q?.onprogress)this._progressHandlers.set(F,Q.onprogress),U.params={...W.params,_meta:{...W.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 L=(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:G,resumptionToken:X,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($,M.result);if(!S.success)H(S.error);else b(S.data)}catch(S){H(S)}}),Q?.signal?.addEventListener("abort",()=>{L(Q?.signal?.reason)});let Z=Q?.timeout??rU,P=()=>L(l.fromError(i.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(F,Z,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:G,resumptionToken:X,onresumptiontoken:J}).catch((M)=>{this._cleanupTimeout(F),H(M)})})}async getTask(W,$){return this.request({method:"tasks/get",params:W},HW,$)}async getTaskResult(W,$,Q){return this.request({method:"tasks/result",params:W},$,Q)}async listTasks(W,$){return this.request({method:"tasks/list",params:W},FW,$)}async cancelTask(W,$){return this.request({method:"tasks/cancel",params:W},Pw,$)}async notification(W,$){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(W.method);let Q=$?.relatedTask?.taskId;if(Q){let w={...W,jsonrpc:"2.0",params:{...W.params,_meta:{...W.params?._meta||{},[T1]:$.relatedTask}}};await this._enqueueTaskMessage(Q,{type:"notification",message:w,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(W.method)&&!W.params&&!$?.relatedRequestId&&!$?.relatedTask){if(this._pendingDebouncedNotifications.has(W.method))return;this._pendingDebouncedNotifications.add(W.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(W.method),!this._transport)return;let w={...W,jsonrpc:"2.0"};if($?.relatedTask)w={...w,params:{...w.params,_meta:{...w.params?._meta||{},[T1]:$.relatedTask}}};this._transport?.send(w,$).catch((Y)=>this._onerror(Y))});return}let J={...W,jsonrpc:"2.0"};if($?.relatedTask)J={...J,params:{...J.params,_meta:{...J.params?._meta||{},[T1]:$.relatedTask}}};await this._transport.send(J,$)}setRequestHandler(W,$){let Q=E$(W);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(G,X)=>{let J=T$(W,G);return Promise.resolve($(J,X))})}removeRequestHandler(W){this._requestHandlers.delete(W)}assertCanSetRequestHandler(W){if(this._requestHandlers.has(W))throw Error(`A request handler for ${W} already exists, which would be overridden`)}setNotificationHandler(W,$){let Q=E$(W);this._notificationHandlers.set(Q,(G)=>{let X=T$(W,G);return Promise.resolve($(X))})}removeNotificationHandler(W){this._notificationHandlers.delete(W)}_cleanupTaskProgressHandler(W){let $=this._taskProgressTokens.get(W);if($!==void 0)this._progressHandlers.delete($),this._taskProgressTokens.delete(W)}async _enqueueTaskMessage(W,$,Q){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let G=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(W,$,Q,G)}async _clearTaskQueue(W,$){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll(W,$);for(let G of Q)if(G.type==="request"&&H$(G.message)){let X=G.message.id,J=this._requestResolvers.get(X);if(J)J(new l(i.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(X);else this._onerror(Error(`Resolver missing for request ${X} during task ${W} cleanup`))}}}async _waitForTaskUpdate(W,$){let Q=this._options?.defaultTaskPollInterval??1000;try{let G=await this._taskStore?.getTask(W);if(G?.pollInterval)Q=G.pollInterval}catch{}return new Promise((G,X)=>{if($.aborted){X(new l(i.InvalidRequest,"Request cancelled"));return}let J=setTimeout(G,Q);$.addEventListener("abort",()=>{clearTimeout(J),X(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(G)=>{if(!W)throw Error("No request provided");return await Q.createTask(G,W.id,{method:W.method,params:W.params},$)},getTask:async(G)=>{let X=await Q.getTask(G,$);if(!X)throw new l(i.InvalidParams,"Failed to retrieve task: Task not found");return X},storeTaskResult:async(G,X,J)=>{await Q.storeTaskResult(G,X,J,$);let w=await Q.getTask(G,$);if(w){let Y=s6.parse({method:"notifications/tasks/status",params:w});if(await this.notification(Y),R1(w.status))this._cleanupTaskProgressHandler(G)}},getTaskResult:(G)=>{return Q.getTaskResult(G,$)},updateTaskStatus:async(G,X,J)=>{let w=await Q.getTask(G,$);if(!w)throw new l(i.InvalidParams,`Task "${G}" not found - it may have been cleaned up`);if(R1(w.status))throw new l(i.InvalidParams,`Cannot update task "${G}" from terminal status "${w.status}" to "${X}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(G,X,J,$);let Y=await Q.getTask(G,$);if(Y){let b=s6.parse({method:"notifications/tasks/status",params:Y});if(await this.notification(b),R1(Y.status))this._cleanupTaskProgressHandler(G)}},listTasks:(G)=>{return Q.listTasks(G,$)}}}}function Ew(W){return W!==null&&typeof W==="object"&&!Array.isArray(W)}function Tw(W,$){let Q={...W};for(let G in $){let X=G,J=$[X];if(J===void 0)continue;let w=Q[X];if(Ew(w)&&Ew(J))Q[X]={...w,...J};else Q[X]=J}return Q}var JH=RQ(M8(),1),wH=RQ(XH(),1);function Jj(){let W=new JH.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return wH.default(W),W}class v8{constructor(W){this._ajv=W??Jj()}getValidator(W){let $="$id"in W&&typeof W.$id==="string"?this._ajv.getSchema(W.$id)??this._ajv.compile(W):this._ajv.compile(W);return(Q)=>{if($(Q))return{valid:!0,data:Q,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText($.errors)}}}}class _8{constructor(W){this._server=W}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(W?{cursor:W}:void 0,$)}async cancelTask(W,$){return this._server.cancelTask({taskId:W},$)}}function YH(W,$,Q){if(!W)throw Error(`${Q} does not support task creation (required for ${$})`);switch($){case"tools/call":if(!W.tools?.call)throw Error(`${Q} does not support task creation for tools/call (required for ${$})`);break;default:break}}function bH(W,$,Q){if(!W)throw Error(`${Q} does not support task creation (required for ${$})`);switch($){case"sampling/createMessage":if(!W.sampling?.createMessage)throw Error(`${Q} does not support task creation for sampling/createMessage (required for ${$})`);break;case"elicitation/create":if(!W.elicitation?.create)throw Error(`${Q} does not support task creation for elicitation/create (required for ${$})`);break;default:break}}class x8 extends R${constructor(W,$){super($);if(this._serverInfo=W,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(W4.options.map((Q,G)=>[Q,G])),this.isMessageIgnored=(Q,G)=>{let X=this._loggingLevels.get(G);return X?this.LOG_LEVEL_SEVERITY.get(Q)<this.LOG_LEVEL_SEVERITY.get(X):!1},this._capabilities=$?.capabilities??{},this._instructions=$?.instructions,this._jsonSchemaValidator=$?.jsonSchemaValidator??new v8,this.setRequestHandler(F$,(Q)=>this._oninitialize(Q)),this.setNotificationHandler(U$,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(M$,async(Q,G)=>{let X=G.sessionId||G.requestInfo?.headers["mcp-session-id"]||void 0,{level:J}=Q.params,w=W4.safeParse(J);if(w.success)this._loggingLevels.set(X,w.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new _8(this)};return this._experimental}registerCapabilities(W){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Tw(this._capabilities,W)}setRequestHandler(W,$){let G=a4(W)?.method;if(!G)throw Error("Schema is missing a method literal");let X;if(G6(G)){let w=G;X=w._zod?.def?.value??w.value}else{let w=G;X=w._def?.value??w.value}if(typeof X!=="string")throw Error("Schema method literal must be a string");if(X==="tools/call"){let w=async(Y,b)=>{let H=E1(e6,Y);if(!H.success){let L=H.error instanceof Error?H.error.message:String(H.error);throw new l(i.InvalidParams,`Invalid tools/call request: ${L}`)}let{params:z}=H.data,F=await Promise.resolve($(Y,b));if(z.task){let L=E1(J6,F);if(!L.success){let Z=L.error instanceof Error?L.error.message:String(L.error);throw new l(i.InvalidParams,`Invalid task creation result: ${Z}`)}return L.data}let U=E1(LW,F);if(!U.success){let L=U.error instanceof Error?U.error.message:String(U.error);throw new l(i.InvalidParams,`Invalid tools/call result: ${L}`)}return U.data};return super.setRequestHandler(W,w)}return super.setRequestHandler(W,$)}assertCapabilityForMethod(W){switch(W){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${W})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${W})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${W})`);break;case"ping":break}}assertNotificationCapability(W){switch(W){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${W})`);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 ${W})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${W})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${W})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${W})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(W){if(!this._capabilities)return;switch(W){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${W})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${W})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${W})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${W})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${W})`);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 ${W})`);break;case"ping":case"initialize":break}}assertTaskCapability(W){bH(this._clientCapabilities?.tasks?.requests,W,"Client")}assertTaskHandlerCapability(W){if(!this._capabilities)return;YH(this._capabilities.tasks?.requests,W,"Server")}async _oninitialize(W){let $=W.params.protocolVersion;return this._clientCapabilities=W.params.capabilities,this._clientVersion=W.params.clientInfo,{protocolVersion:zw.includes($)?$:Y$,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"},XW)}async createMessage(W,$){if(W.tools||W.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(W.messages.length>0){let Q=W.messages[W.messages.length-1],G=Array.isArray(Q.content)?Q.content:[Q.content],X=G.some((b)=>b.type==="tool_result"),J=W.messages.length>1?W.messages[W.messages.length-2]:void 0,w=J?Array.isArray(J.content)?J.content:[J.content]:[],Y=w.some((b)=>b.type==="tool_use");if(X){if(G.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(G.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(W.tools)return this.request({method:"sampling/createMessage",params:W},I$,$);return this.request({method:"sampling/createMessage",params:W},q$,$)}async elicitInput(W,$){switch(W.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let G=W;return this.request({method:"elicitation/create",params:G},BW,$)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let G=W.mode==="form"?W:{...W,mode:"form"},X=await this.request({method:"elicitation/create",params:G},BW,$);if(X.action==="accept"&&X.content&&G.requestedSchema)try{let w=this._jsonSchemaValidator.getValidator(G.requestedSchema)(X.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 X}}}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:W},N$,$)}async sendLoggingMessage(W,$){if(this._capabilities.logging){if(!this.isMessageIgnored(W.level,$))return this.notification({method:"notifications/message",params:W})}}async sendResourceUpdated(W){return this.notification({method:"notifications/resources/updated",params:W})}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.151",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 h8=["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 Yj(W){let Q=(W??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return Q.length>0?Q:"https://sequenzy.com"}function e0(W){let $=W?.trim();return $?$:void 0}function J1(W){return encodeURIComponent(W)}function D0(W,$){return`${W}${$}`}function F0(W,$=""){return`/dashboard/company/${J1(W)}${$}`}function DH(W,$,Q){return D0(W,`${F0($,"/settings")}?tab=${encodeURIComponent(Q)}`)}function bj(W,$){let Q=h8.map((G)=>[G,$?DH(W,$,G):""]);return Object.fromEntries(Q)}function A1(W={},$){let Q=Yj($),G=e0(W.companyId),X={},J=bj(Q,G);if(!G)return{appUrl:Q,routeTemplates:zH,settingsTabValues:h8,urls:X,settingsUrls:J};X.dashboard=D0(Q,F0(G)),X.campaigns=D0(Q,F0(G,"/campaign")),X.landingPages=D0(Q,F0(G,"/landing-pages")),X.sequences=D0(Q,F0(G,"/sequences")),X.settings=D0(Q,F0(G,"/settings")),X.emails=D0(Q,F0(G,"/emails")),X.subscribers=D0(Q,F0(G,"/subscribers")),X.sentEmails=D0(Q,F0(G,"/sent-emails")),X.segments=D0(Q,F0(G,"/segments")),X.metrics=D0(Q,F0(G,"/metrics")),X.transactional=D0(Q,F0(G,"/transactional"));let w=e0(W.campaignId);if(w)X.campaign=D0(Q,F0(G,`/campaign/${J1(w)}`)),X.campaignPreview=`${X.campaign}?step=review`;let Y=e0(W.landingPageId);if(Y)X.landingPage=D0(Q,F0(G,`/landing-pages/${J1(Y)}`));let b=e0(W.sequenceId);if(b)X.sequence=D0(Q,F0(G,`/sequences/${J1(b)}`));let H=e0(W.emailId)??e0(W.templateId);if(H)X.email=D0(Q,F0(G,`/emails/${J1(H)}`)),X.template=X.email;let z=e0(W.transactionalId);if(z)X.transactionalEmail=D0(Q,F0(G,`/transactional/${J1(z)}`));let F=e0(W.emailSendId);if(F)X.emailSend=D0(Q,F0(G,`/sent-emails/${J1(F)}`));let U=e0(W.domainId);if(U)X.domain=D0(Q,F0(G,`/settings/domain/${J1(U)}`)),X.domainVerify=`${X.domain}/verify`;let L=e0(W.status);if(L)X.campaignList=D0(Q,F0(G,`/campaign/list/${J1(L)}`)),X.sequenceList=D0(Q,F0(G,`/sequences/list/${J1(L)}`));let Z=e0(W.settingsTab);if(Z)X.settingsTab=DH(Q,G,Z);return{appUrl:Q,routeTemplates:zH,settingsTabValues:h8,urls:X,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://email-blocks",name:"Email Block Reference",description:"Required and optional fields, enum values, and item shapes for every email block type accepted by the blocks parameter",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(W){try{let $;switch(W){case"sequenzy://dashboard":$=await D("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let Q=await D("GET","/api/v1/account"),G=j1()??Q.currentCompanyId;if(!G)throw Error("No company available. Create or select a company first.");$=await D("GET",`/api/v1/companies/${G}`);break}case"sequenzy://campaigns/recent":$=await D("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":$=await D("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":$=await D("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":$=await D("GET","/api/v1/sequences");break;case"sequenzy://templates":$=await D("GET","/api/v1/templates");break;case"sequenzy://segments":$=await D("GET","/api/v1/segments");break;case"sequenzy://tags":$=await D("GET","/api/v1/tags");break;case"sequenzy://health":$=await D("GET","/api/v1/health/deliverability");break;case"sequenzy://email-blocks":$=await D("GET","/api/v1/email-blocks");break;case"sequenzy://app-routes":$=A1();break;default:throw Error(`Unknown resource: ${W}`)}return{contents:[{uri:W,mimeType:"application/json",text:JSON.stringify($,null,2)}]}}catch($){return{contents:[{uri:W,mimeType:"text/plain",text:V1($)}]}}}function h(W){return typeof W==="object"&&W!==null&&!Array.isArray(W)}function B(W,$){let Q=W[$];if(typeof Q!=="string")return;let G=Q.trim();return G.length>0?G:void 0}function y8(W,$,Q){let G=$[Q];if(G===void 0||G===null)return[];if(typeof G==="string"){let J=G.trim();return J.length>0?[J]:[]}if(!Array.isArray(G))throw Error(`\`${Q}\` must be an array of strings when calling \`${W}\`.`);let X=[];return G.forEach((J,w)=>{if(typeof J!=="string")throw Error(`\`${Q}\` item ${w+1} must be a string when calling \`${W}\`.`);let Y=J.trim();if(Y.length>0&&!X.includes(Y))X.push(Y)}),X}function A(W,$,Q){let G=B($,Q);if(G===void 0)throw Error(`\`${Q}\` is required when calling \`${W}\`.`);return G}var W9=' Minimal valid core examples: {"type":"heading","content":"Title","level":1}; {"type":"text","content":"<p>Paragraph with <strong>bold</strong></p>","variant":"paragraph"}; {"type":"list","variant":"bullet","items":[{"content":"First point"},{"content":"Second point"}]}; {"type":"steps","variant":"timeline","items":[{"title":"Connect","description":"Link your account."},{"title":"Launch","description":"Send your first campaign."}]}; {"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`. Lists are their own block type, never a text variant: `text` accepts only variant paragraph, lead, or html and never accepts `items`, so a numbered list is {"type":"list","variant":"numbered","items":[{"content":"First"}]} and a visual numbered walkthrough is {"type":"steps","variant":"numbered","items":[{"title":"Step one","description":"What happens"},{"title":"Step two","description":"What happens next"}]}. List items carry `content`; steps items carry `title` plus an optional `description`. Call get_email_block_schema for the required and optional fields of any other block type.';var f8=' 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.',u8=' 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.',c8=' 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" }.',m8="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.",$9=" 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=`${m8}${$9}`,Q9=' 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`.',l8=" `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: [...] }.${$9}${f8}${l8}${d1}${u8}${c8}${W9}`,G9=" 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.",Hj=` For action_email:${G9}`,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\`.${$9}${f8}${l8}${d1}${u8}${c8}${W9}`,Z6=`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.${$9}${f8}${l8}${d1}${u8}${c8}${W9}`,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.",LH="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.",g8=500,p8=500,X9=["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(", "),J9={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},zj={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},K6={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:zj,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},i8={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.${Hj}`,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},w9={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:i8,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 Dj=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","get_email_block_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"]),Fj=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"]),Uj=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"]),Lj=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 Bj(W){let $=Dj.has(W),Q=Fj.has(W);if($===Q)throw Error(`MCP tool "${W}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:$,destructiveHint:$?!1:Lj.has(W),openWorldHint:Uj.has(W)}}function BH(W){return{...W,annotations:{...W.annotations,...Bj(W.name)}}}var n8={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"]},Aj=Object.entries(n8).map(([W,$])=>`${W}: ${$.join(", ")}`).join("; "),d8={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: ${Aj}.`},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},o8={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 Y9(W){if(!Array.isArray(W))return W;return W.map(($)=>{if(typeof $!=="object"||$===null)return $;let Q=$;if(typeof Q.id==="string"&&Q.id.trim()!=="")return Q;return{...Q,id:crypto.randomUUID()}})}function b9(W){if(typeof W!=="object"||W===null)return W;let $=W;if($.kind==="filter"||"field"in $||"operator"in $||"value"in $){let Q=Y9([$]);return Array.isArray(Q)?Q[0]:$}if($.kind!=="group")return W;return{...$,id:typeof $.id==="string"&&$.id.trim()!==""?$.id:crypto.randomUUID(),children:Array.isArray($.children)?$.children.map(b9):[]}}function Oj(W){let $=W.indexOf(":");return $!==-1&&W.substring(0,$).trim().length>0}function Zj(W){let $=W.indexOf(":");return $!==-1&&W.substring($+1).trim().length>0}function AH(W){if(W==="all")return!0;let $=W.match(/^(\d+)d$/);if(!$?.[1])return!1;let Q=Number.parseInt($[1],10);return Number.isInteger(Q)&&Q>0}function Kj(W,$){let Q=$.split(":");if(W==="at_least"||W==="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 G=Q.slice(0,-1).join(":").trim(),X=Q.at(-1);return G&&X!==void 0&&AH(X)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function Pj(W){let $=W.indexOf(":");if($===-1)return{productId:W,subfilter:null,rawValue:null};let Q=W.substring(0,$),G=W.substring($+1),X=G.indexOf(":");if(X===-1)return{productId:Q,subfilter:G,rawValue:null};return{productId:Q,subfilter:G.substring(0,X),rawValue:G.substring(X+1)}}function Vj(W){return W.trim().toLowerCase().replace(/[-\s]+/g,"_")}function jj(W){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(W)}function Mj(W,$){if($==="cancels_at"||$==="cancel_at"||$==="cancellation_at")return!0;if(W==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes($);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes($)}function qj(W){return["is","is_not","gte","lte","gt","lt"].includes(W)}function Ij(W,$,Q){if(W==="stripeProduct"){if($!=="at_least"&&$!=="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(W!=="stripeCurrentProduct"&&W!=="stripeTrialProduct")return null;let{productId:G,subfilter:X,rawValue:J}=Pj(Q);if(!G.trim())return"Stripe product filters must include a product ID.";if(!X)return $==="is"||$==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let w=Vj(X);if(jj(w))return $==="is"||$==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!Mj(W,w))return`Unsupported Stripe product subfilter "${X}".`;if(!qj($))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 Nj(W,$){let Q=$.trim(),G=Q.indexOf(":");if(G!==-1&&OH.has(Q.substring(0,G).trim()))Q=Q.substring(G+1).trim();if(!Q)return'Purchased Product filters must include a product ID, like "shopify:42".';if(W!=="at_least"&&W!=="less_than_count")return null;let X=Q.lastIndexOf(":");if(X===-1)return null;let J=Q.substring(0,X).trim(),w=Number.parseInt(Q.substring(X+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 Ej(W,$){let Q=$.trim(),G=Q.indexOf(":");if(G!==-1&&OH.has(Q.substring(0,G).trim()))Q=Q.substring(G+1).trim();if(!Q)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(W!=="at_least"&&W!=="less_than_count")return null;let X=Q.lastIndexOf(":");if(X===-1)return null;let J=Q.substring(0,X).trim(),w=Number.parseInt(Q.substring(X+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 Tj(W){let $;try{$=JSON.parse(W)}catch{return`Poll response filters must use valid JSON. ${y1}`}if(!h($)||$.v!==1||typeof $.campaignId!=="string"||!$.campaignId.trim()||typeof $.blockId!=="string"||!$.blockId.trim()||!h($.match))return`Poll response filter context is invalid. ${y1}`;let Q=$.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 H9(W){if(typeof W!=="object"||W===null)return"Segment filters must be objects.";let $=W,Q=$.field,G=$.operator,X=$.value;if(typeof Q!=="string"||!(Q in n8))return`Unsupported segment filter field "${String(Q)}".`;if(typeof G!=="string")return`Segment filter "${Q}" must include an operator.`;let J=n8[Q];if(!J.includes(G))return`Operator "${G}" is not supported for ${Q} filters. Use one of: ${J.join(", ")}.`;if(G!=="is_empty"&&G!=="is_not_empty"&&(typeof X!=="string"||X.trim().length===0))return`Segment filter "${Q}" must include a value.`;if(Q==="attribute"){if(typeof X!=="string")return'Attribute filters must include a value: "attributeName:value", or "attributeName:" for empty checks.';if(!Oj(X))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(G!=="is_empty"&&G!=="is_not_empty"&&!Zj(X))return'Attribute filters must include a value after "attributeName:".'}if(Q==="event"&&typeof X==="string"){let w=Kj(G,X);if(w)return w}if(Q==="pollResponse"&&typeof X==="string"){let w=Tj(X);if(w)return w}if((Q==="stripeProduct"||Q==="stripeCurrentProduct"||Q==="stripeTrialProduct")&&typeof X==="string"){let w=Ij(Q,G,X);if(w)return w}if(Q==="commerceProduct"&&typeof X==="string"){let w=Nj(G,X);if(w)return w}if(Q==="commerceCollection"&&typeof X==="string"){let w=Ej(G,X);if(w)return w}if(Q==="tag"&&(G==="contains"||G==="not_contains")){if(!(typeof X==="string"&&X.split(",").map((Y)=>Y.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function z9(W){if(typeof W!=="object"||W===null)return[];let $=W;if($.kind==="filter"||"field"in $||"operator"in $||"value"in $){let Q=H9($);return Q?[Q]:[]}if(Array.isArray($.children))return $.children.flatMap(z9);return[]}function y0(W,$,Q){if($.html!==void 0&&$.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${W}\`, not both.`);if($.blocks!==void 0&&!Array.isArray($.blocks))throw Error(`\`blocks\` must be an array when calling \`${W}\`.`);if(Q?.requireContent&&$.html===void 0&&$.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${W}\`.`)}function Z1(W,$){if($.labels===void 0)return;if(!Array.isArray($.labels))throw Error(`\`labels\` must be an array when calling \`${W}\`.`);if($.labels.some((Q)=>typeof Q!=="string"||Q.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${W}\`.`)}function PH(W){let $=W.filters!==void 0,Q=W.root!==void 0;if($&&Q)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!$&&!Q)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if($){if(!Array.isArray(W.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(W.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(Q&&(typeof W.root!=="object"||W.root===null))throw Error("`root` must be an object when calling `create_segment`.");let G=$?W.filters.flatMap((X)=>{let J=H9(X);return J?[J]:[]}):z9(W.root);if(G.length>0)throw Error(G[0]??"Invalid segment filter in `create_segment`.")}function VH(W){let $=W.filters!==void 0,Q=W.root!==void 0;if($&&Q)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(W.name===void 0&&W.filterJoinOperator===void 0&&!$&&!Q)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if($){if(!Array.isArray(W.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(W.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(Q&&(typeof W.root!=="object"||W.root===null))throw Error("`root` must be an object when calling `update_segment`.");let G=$?W.filters.flatMap((X)=>{let J=H9(X);return J?[J]:[]}):Q?z9(W.root):[];if(G.length>0)throw Error(G[0]??"Invalid segment filter in `update_segment`.")}var t8=["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 r8(W,$,Q){if($[Q]!==void 0&&!h($[Q]))throw Error(`\`${Q}\` must be an object when calling \`${W}\`.`)}function ZH(W,$,Q){if($[Q]!==void 0&&!Array.isArray($[Q]))throw Error(`\`${Q}\` must be an array when calling \`${W}\`.`)}function jH(W){let $=new Set(["companyId",...t8]),Q=Object.keys(W).filter((X)=>!$.has(X));if(Q.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}.`);let G={};for(let X of t8)if(W[X]!==void 0)G[X]=W[X];if(Object.keys(G).length===0)throw Error(`Provide at least one of ${t8.map((X)=>`\`${X}\``).join(", ")} when calling \`update_company\`.`);for(let X of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailDesignPrompt","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(W[X]!==void 0&&typeof W[X]!=="string")throw Error(`\`${X}\` must be a string when calling \`update_company\`.`);if(r8("update_company",W,"brandColors"),r8("update_company",W,"socialLinks"),r8("update_company",W,"pricing"),W.emailTheme!==void 0&&W.emailTheme!==null&&!h(W.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");ZH("update_company",W,"valueProps"),ZH("update_company",W,"testimonials");for(let X of["replyTrackingEnabled","forwardReplies"])if(W[X]!==void 0&&typeof W[X]!=="boolean")throw Error(`\`${X}\` must be a boolean when calling \`update_company\`.`);if(W.replyTrackingDomainMode!==void 0&&W.replyTrackingDomainMode!=="sequenzy"&&W.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof W.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(W.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let X of["fromEmail","replyTo"]){let J=W[X];if(typeof J==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(J.trim()))throw Error(`\`${X}\` must be a valid email address when calling \`update_company\`.`)}return G}var s8=["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","autoUtmEnabled","autoUtmSettings"],a8=["source","medium","campaign","content","term"];function MH(W){let $=new Set(["companyId",...s8]),Q=Object.keys(W).filter((X)=>!$.has(X));if(Q.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${Q.length===1?"":"s"}: ${Q.map((X)=>`\`${X}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let G={};for(let X of s8)if(W[X]!==void 0)G[X]=W[X];if(Object.keys(G).length===0)throw Error(`Provide at least one of ${s8.map((X)=>`\`${X}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let X of["openTrackingEnabled","clickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(W[X]!==void 0&&typeof W[X]!=="boolean")throw Error(`\`${X}\` must be a boolean when calling \`update_tracking_settings\`.`);if(W.defaultAttributionWindowHours!==void 0&&(typeof W.defaultAttributionWindowHours!=="number"||!Number.isInteger(W.defaultAttributionWindowHours)||W.defaultAttributionWindowHours<1||W.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(W.autoUtmSettings!==void 0&&W.autoUtmSettings!==null&&!h(W.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(h(W.autoUtmSettings)){let X=W.autoUtmSettings,J=Object.keys(X).filter((w)=>!a8.includes(w));if(J.length>0)throw Error(`\`autoUtmSettings\` accepts only ${a8.map((w)=>`\`${w}\``).join(", ")}. Unsupported: ${J.map((w)=>`\`${w}\``).join(", ")}.`);for(let w of a8){let Y=X[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 G}var D9={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},WQ={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function Rj(W){let{profileKey:$,emailKey:Q,nameKey:G}=W.pair;if(W.nameHasStepOverride)return`To keep \`${$}\` and still change the display name, send \`${$}\` on its own and set \`${G}\` on each email step, where it applies as a per-step display-name override. To change the address instead, omit \`${$}\` and send \`${Q}\` (optionally with \`${G}\`).`;return`To use a different address or display name, omit \`${$}\` and send \`${Q}\` (optionally with \`${G}\`) instead.`}function $Q(W){let{profileKey:$,emailKey:Q,nameKey:G,addressLabel:X}=W.pair,J=W.args[$]!==void 0,w=W.args[Q]!==void 0,Y=W.args[G]!==void 0,b=W.location?`for ${W.location} when calling \`${W.toolName}\``:`when calling \`${W.toolName}\``,H=`\`${$}\` already sets both the ${X} address and the display name, so send it without \`${Q}\`${W.nameIsOverride?"":` and \`${G}\``}.`,z=Rj({pair:W.pair,nameHasStepOverride:W.nameHasStepOverride}),F=`For a per-email display name, set \`${G}\` on the email steps instead.`;if(J&&w){let[U,L]=W.profileFirst?[$,Q]:[Q,$],Z=Y&&W.nameHasStepOverride?` ${F}`:"";throw Error(`Provide either \`${U}\` or \`${L}\` ${b}, not both. ${H}${Z}`)}if(J&&Y&&!W.nameIsOverride)throw Error(`\`${G}\` cannot be combined with \`${$}\` ${b}. ${H} ${z}`);if(Y&&!w&&!W.nameIsOverride)throw Error(`\`${G}\` requires \`${Q}\` ${b}. Send \`${G}\` with the \`${Q}\` it names, or send \`${$}\` on its own to use an existing profile's address and name.${W.nameHasStepOverride?` ${F}`:""}`)}function q6(W,$,Q){let G=Q?.replyFirst?[WQ,D9]:[D9,WQ];for(let X of G)$Q({toolName:W,args:$,pair:X,nameHasStepOverride:Q?.hasEmailSteps===!0&&X===D9})}var qH=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function Sj(W){return qH.some(($)=>W[$]!==void 0)}function Cj(W){if(typeof W.nodeType==="string")return W.nodeType==="action_email";return W.type===void 0||W.type==="email"}function F9(W,$,Q){for(let G of qH){let X=Q[G];if(X!==void 0&&typeof X!=="string")throw Error(`\`${G}\` must be a string for ${$} when calling \`${W}\`.`)}$Q({toolName:W,args:Q,pair:D9,location:$,profileFirst:!0,nameIsOverride:!0}),$Q({toolName:W,args:Q,pair:WQ,location:$,profileFirst:!0})}function QQ(W,$,Q){if(Sj(Q)&&!Cj(Q))throw Error(`Sender identity fields are only supported for email steps at ${$} when calling \`${W}\`.`);F9(W,$,Q)}function KH(W,$,Q){if(!Array.isArray(Q))return;Q.forEach((G,X)=>{if(h(G))F9(W,`${$}[${X}]`,G)})}function e8(W,$,Q){if(!Array.isArray(Q))return;Q.forEach((G,X)=>{if(h(G))QQ(W,`${$}[${X}]`,G)})}function kj(W){if(KH("update_sequence","emails",W.emails),KH("update_sequence","steps",W.steps),h(W.insertSteps))e8("update_sequence","insertSteps.steps",W.insertSteps.steps);if(!h(W.branch))return;if(Array.isArray(W.branch.branches))W.branch.branches.forEach((Q,G)=>{if(h(Q))e8("update_sequence",`branch.branches[${G}].steps`,Q.steps)});e8("update_sequence","branch.elseSteps",W.branch.elseSteps)}function IH(W){Z1("update_sequence",W);let $=["listId","tagName","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(W.trigger===void 0&&$.some((G)=>W[G]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(q6("update_sequence",W,{hasEmailSteps:!0}),W.clearEnrollmentFieldPath===!0&&W.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(W.clearSendingWindow===!0&&W.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(W.clearBccEmails===!0&&W.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(W.branch!==void 0&&W.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");kj(W);let Q={...W};if(delete Q.clearEnrollmentFieldPath,delete Q.clearSendingWindow,delete Q.clearBccEmails,W.clearEnrollmentFieldPath===!0)Q.enrollmentFieldPath=null;if(W.clearSendingWindow===!0)Q.sendingWindow=null;if(W.clearBccEmails===!0)Q.bccEmails=null;return Q}function vj(W,$){if(($.triggerType??"event")==="event"){if(typeof $.triggerEventName!=="string"||$.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${W}\` with an event goal (the default \`triggerType\`).`);return}if(typeof $.attributePath!=="string"||$.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${W}\` with \`triggerType: "attribute_change"\`.`);let G=$.attributeCondition??"changed",X=typeof $.attributeValue==="string"&&$.attributeValue.trim().length>0,J=typeof $.attributePreviousValue==="string"&&$.attributePreviousValue.trim().length>0;if((G==="changed_to"||G==="changed_from_to")&&!X)throw Error(`\`attributeValue\` is required when calling \`${W}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(G==="changed_from_to"&&!J)throw Error(`\`attributePreviousValue\` is required when calling \`${W}\` with \`attributeCondition: "changed_from_to"\`.`)}function NH(W){vj("create_sequence_goal",W)}function EH(W){if(typeof W.triggerEventName==="string"&&W.triggerEventName.trim().length===0)throw Error("`triggerEventName` must be a non-empty string when provided to `update_sequence_goal`.");if(typeof W.attributePath==="string"&&W.attributePath.trim().length===0)throw Error("`attributePath` must be a non-empty string when provided to `update_sequence_goal`.")}function vH(W,$,Q){let G=A(W,$,"nodeId");if(!h($.changes)||Object.keys($.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${Q} when calling \`${W}\`.`);let X=A(W,$,"expectedUpdatedAt");return{nodeId:G,changes:$.changes,expectedUpdatedAt:X}}function _H(W){let $=vH("update_sequence_node",W,"the node update");return{...W.confirmLiveChange!==void 0&&{confirmLiveChange:W.confirmLiveChange},nodeUpdates:[$]}}function xH(W){if(!Array.isArray(W.updates)||W.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let $=new Set,Q=W.updates.map((G,X)=>{if(!h(G))throw Error(`\`updates[${X}]\` must be an object when calling \`update_sequence_nodes\`.`);let J=vH("update_sequence_nodes",G,`updates[${X}]`),w=String(J.nodeId);if($.has(w))throw Error(`\`updates[${X}]\` targets duplicate nodeId '${w}' when calling \`update_sequence_nodes\`.`);return $.add(w),J});return{...W.confirmLiveChange!==void 0&&{confirmLiveChange:W.confirmLiveChange},nodeUpdates:Q}}function hH(W){let $=A("edit_sequence_graph",W,"action"),Q=A("edit_sequence_graph",W,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has($))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let X=B(W,"nodeId"),J=B(W,"afterNodeId"),w=B(W,"beforeNodeId"),Y=W.edges;if($!=="replace_edges"&&!X)throw Error(`\`nodeId\` is required for ${$} when calling \`edit_sequence_graph\`.`);if($==="replace_edges"&&X)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let b=$==="move_node"||$==="duplicate_node";if(b&&(J?1:0)+(w?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${$} when calling \`edit_sequence_graph\`.`);if(!b&&(J||w))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${$} when calling \`edit_sequence_graph\`.`);if(($==="replace_edges"||$==="delete_node"&&Y!==void 0)&&(!Array.isArray(Y)||Y.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${$} when calling \`edit_sequence_graph\`.`);if(($==="move_node"||$==="duplicate_node")&&Y!==void 0)throw Error(`\`edges\` is not used with ${$} 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"),L=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:L,...h(z.condition)?{condition:z.condition}:{}}}):void 0;return{...W.confirmStructuralChange!==void 0&&{confirmStructuralChange:W.confirmStructuralChange},graphEdit:{action:$,expectedRevision:Q,...X?{nodeId:X}:{},...J?{afterNodeId:J}:{},...w?{beforeNodeId:w}:{},...H?{edges:H}:{}}}}function _j(W,$,Q){if((W==="has_tag"||W==="does_not_have_tag")&&!B($,"tagId")&&!B($,"tagName"))throw Error(`\`${Q}\` must provide \`tagId\` or \`tagName\` for ${W} when calling \`insert_sequence_step\`.`);if(W==="in_list"&&!B($,"listId"))throw Error(`\`${Q}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(W==="in_segment"&&!B($,"segmentId"))throw Error(`\`${Q}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(W==="event_received"&&!B($,"eventName"))throw Error(`\`${Q}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(W.startsWith("field_")&&(!B($,"fieldName")||!B($,"fieldValue")))throw Error(`\`${Q}\` must provide \`fieldName\` and \`fieldValue\` for ${W} when calling \`insert_sequence_step\`.`)}var xj=["conditionType","tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"];function yH(W){let $=B(W,"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($))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if($==="logic_wait_for_event"){let w=A("insert_sequence_step",W,"eventName"),Y=W.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=B(W,"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:B(W,"label")??`Wait for ${w}`,eventName:w,timeoutDays:b,timeoutAction:H}}]},F=B(W,"afterNodeId");if(F)z.afterNodeId=F;return{...W.confirmStructuralChange!==void 0&&{confirmStructuralChange:W.confirmStructuralChange},insertSteps:z}}if($==="logic_branch"){let w=A("insert_sequence_step",W,"afterNodeId");if(!Array.isArray(W.branches)||W.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=B(W,"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(W.randomPercentages)||W.randomPercentages.length!==W.branches.length)throw Error("`randomPercentages` must contain one percentage per entry in `branches` when `splitMode` is `random`.");if(W.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=W.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(W.elseSteps)&&W.elseSteps.length>0||B(W,"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(W.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=W.allowEmptyPaths===!0,U=W.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 _=xj.find((k)=>P[k]!==void 0);if(_)throw Error(`\`${M}.${_}\` must be omitted when \`splitMode\` is \`random\`, because the path is chosen by percentage rather than by evaluating the subscriber.`)}else{let _=A("insert_sequence_step",P,"conditionType");if(!Y.has(_))throw Error(`\`branches[${q}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);_j(_,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=B(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((_)=>P[_]===void 0?[]:[[_,P[_]]]))});if(W.elseSteps!==void 0&&!Array.isArray(W.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let L=B(W,"elseTargetNodeId"),Z=Array.isArray(W.elseSteps)&&W.elseSteps.length>0;if(!H&&!L&&!Z&&!F)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...W.confirmStructuralChange!==void 0&&{confirmStructuralChange:W.confirmStructuralChange},branch:{afterNodeId:w,...B(W,"label")?{label:B(W,"label")}:{},...H?{splitMode:b,randomPercentages:W.randomPercentages}:{},branches:U,...Array.isArray(W.elseSteps)?{elseSteps:W.elseSteps}:{},...L?{elseTargetNodeId:L}:{},...F?{allowEmptyPaths:!0}:{}}}}if($==="delay"||$==="create_discount"||$==="update_subscriber"||$==="condition"||$==="add_tag"||$==="remove_tag"||$==="add_to_list"||$==="remove_from_list"||$==="webhook"||$==="ai"){let w;if($==="delay"){w={type:"delay"};for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if(W[H]!==void 0)w[H]=W[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($==="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(W[H]!==void 0)w[H]=W[H]}else if($==="update_subscriber"){if(!h(W.config))throw Error("`config` is required when inserting an update_subscriber step.");w={type:"update_subscriber",nodeType:"action_update_attributes",config:W.config}}else if($==="webhook"){let H=B(W,"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(W.headers!==void 0&&(!h(W.headers)||Object.values(W.headers).some((L)=>typeof L!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let z=B(W,"onError");if(z&&!["continue","exit","fail"].includes(z))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(W.body!==void 0&&typeof W.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(W.resultKey!==void 0&&typeof W.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let F=B(W,"body"),U=B(W,"resultKey");w={type:"webhook",nodeType:"action_webhook",config:{label:B(W,"label")??"Webhook",url:A("insert_sequence_step",W,"url"),method:H,...W.headers!==void 0?{headers:W.headers}:{},...F?{body:F}:{},...U?{resultKey:U}:{},...z?{onError:z}:{}}}}else if($==="ai"){let H=B(W,"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(W.outputFields)||W.outputFields.length===0)throw Error("`outputFields` is required when inserting an ai step, e.g. [{ key: 'subject_line', fallback: 'We miss you' }].");if(W.includeAttributes!==void 0){if(!Array.isArray(W.includeAttributes)||W.includeAttributes.some((z)=>typeof z!=="string"))throw Error("`includeAttributes` must be an array of attribute names when inserting an ai step.")}if(W.recentEventLimit!==void 0&&typeof W.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:B(W,"label")??"Ask AI",prompt:A("insert_sequence_step",W,"prompt"),resultKey:A("insert_sequence_step",W,"resultKey"),outputFields:W.outputFields,...W.includeTags!==void 0?{includeTags:W.includeTags===!0}:{},...W.includeEventProperties!==void 0?{includeEventProperties:W.includeEventProperties===!0}:{},...W.includeRecentEvents!==void 0?{includeRecentEvents:W.includeRecentEvents===!0}:{},...W.recentEventLimit!==void 0?{recentEventLimit:W.recentEventLimit}:{},...W.includeAttributes!==void 0?{includeAttributes:W.includeAttributes}:{},...H?{onError:H}:{}}}}else if($==="condition"){let H=A("insert_sequence_step",W,"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")&&!B(W,"tagId")&&!B(W,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(H==="in_list"&&!B(W,"listId"))throw Error("`listId` is required for an in_list condition.");if(H==="in_segment"&&!B(W,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(H==="event_received"&&!B(W,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(H.startsWith("field_")&&(!B(W,"fieldName")||!B(W,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let F={label:B(W,"label")??"Condition",conditionType:H};for(let U of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(W[U]!==void 0)F[U]=W[U];w={type:"condition",nodeType:"logic_condition",config:F}}else{let H=$==="add_tag"||$==="remove_tag",z=$==="add_tag"?"action_add_tag":$==="remove_tag"?"action_remove_tag":$==="add_to_list"?"action_add_to_list":"action_remove_from_list",F={label:B(W,"label")??($==="add_tag"?"Add Tag":$==="remove_tag"?"Remove Tag":$==="add_to_list"?"Add to List":"Remove from List")};if(H){let U=B(W,"tagId"),L=B(W,"tagName");if(!U&&!L)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(U)F.tagId=U;if(L)F.tagName=L}else{F.listId=A("insert_sequence_step",W,"listId");let U=B(W,"listName");if(U)F.listName=U}w={nodeType:z,config:F}}for(let H of["delay","delayMs","waitUntil","waitUntilWeekday"])if($!=="delay"&&W[H]!==void 0)w[H]=W[H];let Y={steps:[w]},b=B(W,"afterNodeId");if(b)Y.afterNodeId=b;return{...W.confirmStructuralChange!==void 0&&{confirmStructuralChange:W.confirmStructuralChange},insertSteps:Y}}let G=$==="sms",X;if(G){QQ("insert_sequence_step","SMS step",W);let w=B(W,"text"),Y=Array.isArray(W.blocks)&&W.blocks.length>0;if(w===void 0&&!Y)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");X={type:"sms"};for(let b of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil","waitUntilWeekday"])if(W[b]!==void 0)X[b]=W[b]}else{y0("insert_sequence_step",W,{requireContent:!0}),F9("insert_sequence_step","email step",W),X={subject:A("insert_sequence_step",W,"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[w]!==void 0)X[w]=W[w]}let J={steps:[X]};if(W.afterNodeId!==void 0)J.afterNodeId=W.afterNodeId;return{...W.confirmStructuralChange!==void 0&&{confirmStructuralChange:W.confirmStructuralChange},insertSteps:J}}function TH(W,$){let Q=W[$];if(Q===void 0)return[];if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let G=Q.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);if(Q.some((X)=>typeof X!=="string")||G.length===0)throw Error(`\`${$}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return G}function RH(W,$){let Q=W[$];if(Q===void 0)return[];if(!Array.isArray(Q))throw Error(`\`${$}\` must be an array when calling \`realign_sequence_enrollments\`.`);let G=Q.map((X)=>typeof X==="string"?X.trim():"").filter((X)=>X.length>0);if(Q.some((X)=>typeof X!=="string")||G.length===0)throw Error(`\`${$}\` must contain at least one non-empty string when calling \`realign_sequence_enrollments\`.`);return G}function fH(W){let $=RH(W,"nodeIds"),Q=RH(W,"subscriberIds"),G=B(W,"cursor");if(W.dryRun!==void 0&&typeof W.dryRun!=="boolean")throw Error("`dryRun` must be a boolean when calling `realign_sequence_enrollments`.");return{...$.length>0&&{nodeIds:$},...Q.length>0&&{subscriberIds:Q},...G!==void 0&&{cursor:G},...typeof W.dryRun==="boolean"&&{dryRun:W.dryRun}}}function uH(W){let $=B(W,"subscriberId"),Q=TH(W,"subscriberIds"),G=TH(W,"fieldValues");if(W.cancelAll!==void 0&&typeof W.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let X=W.cancelAll===!0;if(($!==void 0?1:0)+(Q.length>0?1:0)+(G.length>0?1:0)+(X?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let w=B(W,"fieldPath"),Y=B(W,"reason");return{...X&&{cancelAll:!0},...$!==void 0&&{subscriberId:$},...Q.length>0&&{subscriberIds:Q},...w!==void 0&&{fieldPath:w},...G.length>0&&{fieldValues:G},...typeof W.dryRun==="boolean"&&{dryRun:W.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 G=typeof Q==="string"?Number(Q):Q,X=$==="dailyLimit"?0:1;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<X)throw Error(`\`${$}\` must be an integer of at least ${X} when calling \`move_sequence_enrollments\`.`);return G}function kH(W,$){let Q=W[$];if(Q===void 0)return[];if(!Array.isArray(Q)||Q.some((X)=>typeof X!=="string"))throw Error(`\`${$}\` must be an array of strings when calling \`move_sequence_enrollments\`.`);let G=Q.map((X)=>X.trim()).filter((X)=>X.length>0);if(G.length===0)throw Error(`\`${$}\` must contain at least one non-empty string when calling \`move_sequence_enrollments\`.`);return G}function cH(W){let $=A("move_sequence_enrollments",W,"fromNodeId"),Q=B(W,"targetNodeId"),G=B(W,"reason"),X=B(W,"sort");if(X!==void 0&&!SH.includes(X))throw Error(`\`sort\` must be one of ${SH.join(", ")} when calling \`move_sequence_enrollments\`.`);let J=kH(W,"subscriberIds"),w=kH(W,"tags"),Y=CH(W,"limit"),b=CH(W,"dailyLimit");return{fromNodeId:$,...Q!==void 0&&{targetNodeId:Q},...Y!==void 0&&{limit:Y},...b!==void 0&&{dailyLimit:b},...X!==void 0&&{sort:X},...J.length>0&&{subscriberIds:J},...w.length>0&&{tags:w},...G!==void 0&&{reason:G},...typeof W.dryRun==="boolean"&&{dryRun:W.dryRun}}}function mH(W){y0("create_campaign",W),Z1("create_campaign",W);let $=B(W,"prompt")!==void 0,Q=W.html!==void 0,G=W.blocks!==void 0,X=W.templateId!==void 0;if(W.prompt!==void 0&&!$)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if($&&(Q||G||X))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!$&&(W.style!==void 0||W.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(!$&&B(W,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function lH(W){y0("create_template",W),Z1("create_template",W);let $=B(W,"prompt")!==void 0,Q=[$,W.html!==void 0,W.blocks!==void 0].filter(Boolean).length;if(W.prompt!==void 0&&!$)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||W.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!$&&B(W,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function gH(W){if(B(W,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(W.targetLists!==void 0&&!h(W.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(W.listIds!==void 0&&W.targetLists!==void 0)throw Error("Provide either `listIds` or `targetLists` when calling `schedule_campaign`, not both.");if(W.listIds!==void 0&&(!Array.isArray(W.listIds)||W.listIds.length===0||W.listIds.some(($)=>typeof $!=="string")))throw Error("`listIds` must be a non-empty array of list ID strings when calling `schedule_campaign`.");if(W.sendTimeOptimization!==void 0){if(typeof W.sendTimeOptimization!=="boolean")throw Error("`sendTimeOptimization` must be a boolean when calling `schedule_campaign`.")}if(W.spreadOverHours!==void 0){if(typeof W.spreadOverHours!=="number"||!Number.isInteger(W.spreadOverHours)||W.spreadOverHours<1||W.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(W.recurringInterval!==void 0&&W.recurringInterval!=="weekly"&&W.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function U9(W,$,Q){let G=new Set(["companyId","landingPageId","name","slug","content"]),X=Object.keys($).filter((J)=>!G.has(J));if(X.length>0)throw Error(`\`${W}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${X.length===1?"":"s"}: ${X.map((J)=>`\`${J}\``).join(", ")}.`);if(Q.requireUpdate&&$.name===void 0&&$.slug===void 0&&$.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${W}\`.`);return{...$.name!==void 0&&{name:$.name},...$.slug!==void 0&&{slug:$.slug},...$.content!==void 0&&{content:$.content}}}function pH(W){let $=new Set(["companyId","domain","verify"]),Q=Object.keys(W).filter((G)=>!$.has(G));if(Q.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`domain\` and \`verify\`. Unsupported field${Q.length===1?"":"s"}: ${Q.map((G)=>`\`${G}\``).join(", ")}.`);if(W.domain===void 0&&W.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...W.domain!==void 0&&{domain:W.domain},...typeof W.verify==="boolean"&&{verify:W.verify}}}function iH(W){y0("create_transactional_email",W);let $=B(W,"prompt")!==void 0,Q=W.html!==void 0,G=W.blocks!==void 0;if(W.prompt!==void 0&&!$)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if($&&(Q||G))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!$&&(W.style!==void 0||W.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!$&&!Q&&!G)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!$&&B(W,"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},hj={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:hj,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:Z6,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:K6,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.${Q9}`,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},GQ={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},XQ="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(W){if(!W||typeof W!=="object")return null;let $=W;if($.success!==!1)return null;if(typeof $.error==="string")return Error($.error);if($.error&&typeof $.error==="object"&&typeof $.error.message==="string")return Error($.error.message);if(typeof $.message==="string")return Error($.message);return Error("The tool returned an unsuccessful response.")}var YQ=1000,bQ=1000,HQ=YQ*bQ-1;function zQ(W){return W.trim().toLowerCase().replace(/\s+/g,"-")}function yj(W,$){let Q=B($,"attribute"),G=B($,"attributeValue"),X=u(W,$,"attributeOperator",X9);if(!Q){if(G!==void 0||X!==void 0)throw Error(`\`attributeValue\` and \`attributeOperator\` require \`attribute\` when calling \`${W}\`.`);return{}}let J=X??"is",w;if(G!==void 0)w=`${Q}:${G}`;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 \`${W}\`. Only \`is_not_empty\` may omit a value.`);return{attribute:w,attributeOperator:J}}function fj(W){let $=new URLSearchParams;if(typeof W.query==="string"&&W.query.trim()!=="")$.set("query",W.query.trim());if(Array.isArray(W.tags)&&W.tags.length>0)$.set("tags",W.tags.filter((Q)=>typeof Q==="string"&&Q.trim()!=="").join(","));if(typeof W.list==="string"&&W.list.trim()!=="")$.set("list",W.list.trim());if(typeof W.listId==="string"&&W.listId.trim()!=="")$.set("listId",W.listId.trim());if(typeof W.listName==="string"&&W.listName.trim()!=="")$.set("listName",W.listName.trim());if(typeof W.segmentId==="string"&&W.segmentId.trim()!=="")$.set("segmentId",W.segmentId);if(typeof W.status==="string"&&W.status.trim()!=="")$.set("status",W.status.trim());if(typeof W.unsubscribedAfter==="string"&&W.unsubscribedAfter.trim()!=="")$.set("unsubscribedAfter",W.unsubscribedAfter.trim());if(typeof W.unsubscribedBefore==="string"&&W.unsubscribedBefore.trim()!=="")$.set("unsubscribedBefore",W.unsubscribedBefore.trim());if(W.attribute){if($.set("attribute",W.attribute),W.attributeOperator)$.set("attributeOperator",W.attributeOperator)}if(W.cursor)$.set("cursor",W.cursor);else $.set("page",String(W.page));if($.set("limit",String(W.pageSize)),W.includeTotal===!1)$.set("includeTotal","false");return $}async function tH(W,$){let G=sH("search_subscribers",W,"limit"),X=B(W,"cursor"),J=X?uj("search_subscribers",W):cj("search_subscribers",W,G),w=G===void 0?void 0:J+G,Y=Math.min(YQ,Math.max(1,w??YQ)),b=yj("search_subscribers",W),H=[],z=1,F=X,U,L=null,Z=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=fj({query:W.query,tags:W.tags,list:W.list,listId:W.listId,listName:W.listName,segmentId:W.segmentId,status:W.status,unsubscribedAfter:W.unsubscribedAfter,unsubscribedBefore:W.unsubscribedBefore,attribute:b.attribute,attributeOperator:b.attributeOperator,page:z,pageSize:S0,cursor:F}),C0=await D("GET",`/api/v1/subscribers?${g0.toString()}`,void 0,$);if(Z===0)L=C0.pagination?.total??null;Z+=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(Z>=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(L===null&&P&&!X)L=H.length;let M=H.slice(J,w),S=P?!1:L!==null?J+M.length<L:!P||H.length>J+M.length,C=U!==void 0&&H.length===J+M.length,_=J+M.length;return{success:!0,subscribers:M,pagination:{page:G===void 0?1:Math.floor(J/G)+1,limit:G??Y,offset:J,total:L,totalPages:L===null?null:Math.ceil(L/(G??Y)),fetchedPages:Z,hasMore:S,nextOffset:S&&!X&&_<=HQ?_:null,nextCursor:S&&C?U??null:null},returned:M.length,truncated:S}}function uj(W,$){if($.offset!==void 0||$.page!==void 0)throw Error(`\`cursor\` cannot be combined with \`offset\` or \`page\` when calling \`${W}\`. Keep following \`pagination.nextCursor\` instead.`);return 0}function cj(W,$,Q){let G=rH(W,$,"offset"),X=sH(W,$,"page");if(G!==void 0&&X!==void 0)throw Error(`Provide either \`offset\` or \`page\` when calling \`${W}\`, not both.`);if(X!==void 0){if(Q===void 0)throw Error(`\`page\` requires \`limit\` when calling \`${W}\` so the page size is defined. Omit both to fetch every match in one call.`);return dH(W,(X-1)*Q)}return dH(W,G??0)}function dH(W,$){if($>HQ)throw Error(`\`offset\` must be ${HQ} or less when calling \`${W}\`. Use \`cursor\` to continue beyond that point.`);return $}function rH(W,$,Q){let G=$[Q];if(G===void 0||G===null)return;if(typeof G!=="number"||!Number.isInteger(G)||G<0)throw Error(`\`${Q}\` must be a non-negative integer when calling \`${W}\`.`);return G}function sH(W,$,Q){let G=rH(W,$,Q);if(G!==void 0&&G<1)throw Error(`\`${Q}\` must be 1 or greater when calling \`${W}\`.`);return G}function DQ(W){let $=typeof W.email==="string"&&W.email.trim()!==""?W.email.trim():void 0,Q=typeof W.externalId==="string"&&W.externalId.trim()!==""?W.externalId.trim():void 0;return{...$?{email:$}:{},...Q?{externalId:Q}:{}}}function W1(W,$){let Q=DQ($);if(!Q.email&&!Q.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${W}\`.`);return Q}function L9(W,$){let Q=new URLSearchParams;if($?.includeMachineEngagement)Q.set("includeMachineEngagement","true");let G=Q.toString(),X=G?`?${G}`:"";if(W.email)return`/api/v1/subscribers/${encodeURIComponent(W.email)}${X}`;return Q.set("externalId",String(W.externalId)),`/api/v1/subscribers/external?${Q.toString()}`}function FQ(W){if(W.email)return`/api/v1/subscribers/${encodeURIComponent(W.email)}/notes`;let $=new URLSearchParams;return $.set("externalId",String(W.externalId)),`/api/v1/subscribers/external/notes?${$.toString()}`}async function S4(W,$,Q){return D("GET",L9(W,Q),void 0,$)}function u(W,$,Q,G){let X=B($,Q);if(X===void 0)return;if(!G.includes(X))throw Error(`\`${Q}\` must be one of ${G.join(", ")} when calling \`${W}\`.`);return X}function C4(W,$,Q,G){let X=A(W,$,Q);if(!G.includes(X))throw Error(`\`${Q}\` must be one of ${G.join(", ")} when calling \`${W}\`.`);return X}function G0(W,$,Q,G,X){let J=$[Q];if(J===void 0)return;if(typeof J!=="number"||!Number.isInteger(J)||J<G||J>X)throw Error(`\`${Q}\` must be an integer between ${G} and ${X} when calling \`${W}\`.`);return J}function mj(W,$){let Q=[],G=u(W,$,"eventType",N4);if(G)Q.push(G);if($.eventTypes!==void 0){if(!Array.isArray($.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${W}\`.`);$.eventTypes.forEach((X,J)=>{if(typeof X!=="string")throw Error(`\`eventTypes\` item ${J+1} must be a string when calling \`${W}\`.`);let w=X.trim();if(!N4.includes(w))throw Error(`\`eventTypes\` item ${J+1} must be one of ${N4.join(", ")} when calling \`${W}\`.`);Q.push(w)})}return[...new Set(Q)]}function UQ(W,$){let Q=new URLSearchParams,G=mj(W,$);if(G.length>0)Q.set("eventTypes",G.join(","));let X=u(W,$,"period",["1h","24h","7d","30d","90d"]);if(X)Q.set("period",X);let J=B($,"start");if(J)Q.set("start",J);let w=B($,"end");if(w)Q.set("end",w);let Y=G0(W,$,"page",1,1e6);if(Y!==void 0)Q.set("page",String(Y));let b=G0(W,$,"limit",1,500);if(b!==void 0)Q.set("limit",String(b));if($.includeMachineEngagement===!0)Q.set("includeMachineEngagement","true");return Q}function LQ(W,$){if($.events===void 0)return;if(!Array.isArray($.events))throw Error(`\`events\` must be an array when calling \`${W}\`.`);let Q=$.events.map((G,X)=>{if(typeof G!=="string"||!M6.includes(G))throw Error(`\`events\` item ${X+1} must be one of ${M6.join(", ")} when calling \`${W}\`.`);return G});if(Q.length===0)throw Error(`\`events\` must include at least one event type when calling \`${W}\`.`);return Q}function BQ(W,$){if(!Array.isArray($.emails))throw Error(`\`emails\` must be an array when calling \`${W}\`.`);let Q=[];if($.emails.forEach((G,X)=>{if(typeof G!=="string")throw Error(`\`emails\` item ${X+1} must be a string when calling \`${W}\`.`);let J=G.trim();if(J.length>0)Q.push(J)}),Q.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${W}\`.`);if(Q.length>g8)throw Error(`\`emails\` must include no more than ${g8} email addresses when calling \`${W}\`. Split larger batches into multiple calls.`);return Q}function oH(W,$,Q,G){let X=$[Q];if(X===void 0)return;if(!Array.isArray(X))throw Error(`\`${Q}\` must be an array when calling \`${W}\`.`);let J=[];if(X.forEach((w,Y)=>{if(typeof w!=="string")throw Error(`\`${Q}\` item ${Y+1} must be a string when calling \`${W}\`.`);let b=w.trim();if(b.length>0)J.push(b)}),J.length===0)throw Error(`\`${Q}\` must include at least one ${G} when calling \`${W}\`.`);return J}function aH(W){let Q=oH("enroll_subscribers_in_sequence",W,"emails","email address"),G=oH("enroll_subscribers_in_sequence",W,"subscriberIds","subscriber ID"),X=(Q?.length??0)+(G?.length??0);if(X===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(X>p8)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${p8} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let J=B(W,"targetNodeId");return{...Q!==void 0&&{emails:Q},...G!==void 0&&{subscriberIds:G},...J!==void 0&&{targetNodeId:J}}}import{readFileSync as lj,statSync as gj}from"node:fs";import{basename as pj}from"node:path";var ij={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 nj(W){let $=W.split(".").pop()?.toLowerCase()??"";return ij[$]??null}var dj=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=nj(W);if(!Q)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let G=gj(W).size;if(G>dj)throw Error(`File is too large (${Math.round(G/1048576)}MB). Delivery files must be 100MB or smaller.`);let X=lj(W),J=await D("POST","/api/v1/products/delivery/upload-url",{filename:pj(W),contentType:Q,fileSizeBytes:G},$),w=await fetch(J.uploadUrl,{method:"PUT",headers:{"Content-Type":Q},body:X});if(!w.ok)throw Error(`File upload failed (${w.status})`);return{url:J.publicUrl,fileName:J.fileName,fileSizeBytes:G,mimeType:Q}}async function B9(W){let $=B(W,"companyId");if($)return $;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 B9($);if(!Q)throw Error(`A company is required when calling \`${W}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return Q}function E6(W,$){if(!h(W)||!$)return W;return{...W,url:$}}function W3(W,$){if(!h(W))return W;return{...W,...$.campaign!==void 0&&{url:$.campaign},...$.campaignPreview!==void 0&&{previewUrl:$.campaignPreview}}}function N6(W,$,Q){if(!Array.isArray(W)||!$)return W;return W.map((G)=>{if(!h(G))return G;let X=B(G,"id");if(!X)return G;let J=A1({companyId:$,...Q==="campaign"&&{campaignId:X},...Q==="landingPage"&&{landingPageId:X},...Q==="sequence"&&{sequenceId:X},...Q==="template"&&{emailId:X},...Q==="transactional"&&{transactionalId:X},...Q==="emailSend"&&{emailSendId:X}});if(Q==="campaign")return W3(G,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(G,w)})}function oj(W){if(!Array.isArray(W))return W;return W.map(($)=>{if(!h($))return $;let Q=B($,"id");if(!Q)return $;let G=A1({companyId:Q});return{...$,url:G.urls.dashboard,settingsUrl:G.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 $3(W,$,Q){if(!h(Q)||!AQ.has(W))return Q;let G=h(Q.company)?Q.company:void 0,J=B(Q,"selectedCompanyId")??B(Q,"currentCompanyId")??B(Q,"companyId")??(G?B(G,"id"):void 0)??(G?B(G,"companyId"):void 0)??await B9($);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:B($,"campaignId")??B(Q,"campaignId")??(w?B(w,"id"):void 0),landingPageId:B($,"landingPageId")??B(Q,"landingPageId")??(b?B(b,"id"):void 0),sequenceId:B($,"sequenceId")??B(Q,"sequenceId")??(Y?B(Y,"id"):void 0),emailId:B(Q,"templateId")??(H?B(H,"id"):void 0)??(z?B(z,"emailId"):void 0)??B($,"templateId"),transactionalId:B($,"transactionalId")??(z?B(z,"id"):void 0)??B($,"idOrSlug"),emailSendId:B($,"emailSendId")??B(Q,"emailSendId")??(h(Q.emailSend)?B(Q.emailSend,"id"):void 0),status:B($,"status")},U=A1(F),L=G?A1({companyId:J}):void 0;return{...Q,...Array.isArray(Q.companies)&&{companies:oj(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")},...G&&L!==void 0&&{company:{...G,url:L.urls.dashboard,settingsUrl:L.urls.settings}},...w&&U.urls.campaign!==void 0&&{campaign:W3(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 tj,statSync as rj}from"node:fs";import{basename as sj,extname as G3}from"node:path";var ZQ=5242880,aj=Math.ceil(ZQ/3)*4,ej=Math.ceil(aj*1.05)+256,X3={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},WM=new Set(Object.values(X3));function OQ(W){return W?.split(";")[0]?.trim().toLowerCase()||void 0}function $M(W){return X3[G3(W).toLowerCase()]}function QM(W){let $=G3(W);return($?W.slice(0,-$.length):W).replace(/[-_]+/g," ").trim()||"Image"}function GM(W){if(W.length>ej)throw Error("Image assets must be 5MB or smaller.")}function XM(W){let $=0,Q=0;for(let X=0;X<W.length;X+=1){let J=W.charCodeAt(X);if(J===9||J===10||J===11||J===12||J===13||J===32)continue;$+=1,Q=J===61?Q+1:0}if(Math.floor($*3/4)-Math.min(Q,2)>ZQ)throw Error("Image assets must be 5MB or smaller.")}function JM(W){GM(W);let $=W.trim(),Q=/^data:([^;,]+);base64,([\s\S]+)$/i.exec($),G=Q?.[2]??$;XM(G);let X=G.replace(/\s+/g,"");if(X.length===0||X.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(X))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(X,"base64"),...Q?.[1]?{dataUrlContentType:OQ(Q[1])}:{}}}function Q3(W){if(W<=0)throw Error("The image file is empty.");if(W>ZQ)throw Error("Image assets must be 5MB or smaller.")}function wM(W){let $=$M(W.filename)??OQ(W.explicitContentType)??OQ(W.dataUrlContentType);if(!$||!WM.has($))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return $}function YM(W){let $,Q,G;if(W.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=rj(W.filePath).size;Q3(J),$=tj(W.filePath),Q=W.filename??sj(W.filePath)}else{if(!W.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!W.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let J=JM(W.imageBase64);$=J.bytes,G=J.dataUrlContentType,Q=W.filename,Q3($.byteLength)}let X=wM({filename:Q,explicitContentType:W.contentType,dataUrlContentType:G});return{bytes:$,filename:Q,contentType:X,altText:W.altText??QM(Q)}}async function J3(W){let $=YM(W),Q=$.bytes.byteLength,G=await D("POST","/api/v1/media/upload-url",{filename:$.filename,contentType:$.contentType,fileSizeBytes:Q},W.companyId);return await uQ(G.uploadUrl,$.bytes,$.contentType,W.companyId),(await D("POST","/api/v1/media/complete-upload",{key:G.key,filename:G.fileName,contentType:$.contentType,fileSizeBytes:Q,...W.sourceWidth!==void 0&&{width:W.sourceWidth},...W.sourceHeight!==void 0&&{height:W.sourceHeight},altText:$.altText},W.companyId)).asset}var bM={type:"boolean",description:"Whether the Sequenzy operation succeeded."},r1={type:"string",description:"Human-readable status, confirmation, or next-step message."},KQ={type:"string",description:"Additional context about the result."};function I(W){return{type:"object",description:W,additionalProperties:!0}}function K1(W){return{type:"array",description:W,items:I("One item in the returned collection.")}}function O(W){return{type:"string",description:W}}function w1(W){return{type:["object","null"],description:W,additionalProperties:!0}}function H0(W){return{type:["string","null"],description:W}}function v(W){return{type:"number",description:W}}function w3(W){return{type:["number","null"],description:W}}function c(W){return{type:"boolean",description:W}}function j(W){return I(`The ${W} record returned by Sequenzy.`)}function y(W){return K1(`List of ${W} 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}`),HM=K1(`List of sequence records returned by Sequenzy. ${b3}`),A9={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:v("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:v("Recipients completed because a deleted step had no surviving successor.")}},zM={appUrls:I("Dashboard URLs for relevant Sequenzy resources."),url:O("Primary dashboard URL for this result."),settingsUrl:O("Company settings URL when available.")},DM={success:bM,message:r1,note:KQ,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.")},FM={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:K1("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:K1("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_email_block_schema:{blockTypes:{type:"array",description:"Listing mode: one entry per block type, each with `type`, `creatable`, `required`, `optional`, and a `fields` array of { name, required, type, values?, itemFields? }. `values` holds an enum field's allowed values; `itemFields` holds the shape of one entry in an array field, which is where `list` (items carry `content`) and `steps` (items carry `title`) differ.",items:I("A block type reference: type, creatable, required, optional, fields, and - when the type is one an author should hand-create - a minimal valid `example` and authoring `notes`.")},blockType:I("Single-type mode: the full reference for the requested type, including a minimal valid `example` and authoring `notes`.")},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:KQ},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:KQ},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:K1("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:K1("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("Live event with its name and whether the event definition was created. Historical responses use `events` instead."),duplicate:c("Present and true for a repeated live eventId. Nothing was written and no side effects ran; `event` is the existing event. Historical responses report skipped rows in `duplicates` instead."),historical:c("Present and true when occurredAt selected the historical import path."),events:y("Historical events, each with id, name, and occurredAt."),inserted:v("Historical event rows inserted by this request."),duplicates:v("Historical event rows skipped because their idempotency receipt already existed."),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:v("Identifiers supplied in the request."),matched:v("Existing subscribers resolved."),updated:v("Subscribers whose tags actually changed."),unchanged:v("Subscribers that already carried every tag."),failed:v("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:v("Identifiers supplied in the request."),matched:v("Existing subscribers resolved."),updated:v("Subscribers whose tags actually changed."),unchanged:v("Subscribers that did not carry any of the tags."),failed:v("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:v("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:v("Number of products created."),updated:v("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:v("Number of subscribers added to the list."),skipped:v("Number of subscribers skipped.")},remove_subscribers_from_list:{list:j("list"),removed:v("Number of subscribers removed from the list."),skipped:v("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:v("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:v("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:v("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:v("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:v("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:HM,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:K1("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:v("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."),...A9},disable_sequence:{sequenceId:O("Sequence ID."),status:O("Stored lifecycle status after the change."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...A9},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."),...A9},resume_sequence_enrollments:{sequenceId:O("Sequence ID."),enrollmentPaused:c("Whether new sequence enrollments are paused."),...A9},enroll_subscribers_in_sequence:{sequence:j("sequence"),enrollments:y("sequence enrollment"),enrolled:v("Number of subscribers enrolled."),skipped:v("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:v("Active/waiting enrollments matching the target when the request started."),cancelledCount:v("Enrollments cancelled by this call."),remainingCount:v("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:v("limit as requested."),effectiveLimit:v("How many this call was allowed to move after the daily guardrail was applied."),matchedCount:v("Movable enrollments parked on fromNodeId when the request started."),movedCount:v("Enrollments moved by this call."),remainingCount:v("Movable enrollments still on fromNodeId. Repeat the same request while this is above zero."),skippedCount:v("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:v("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:v("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:v("Waiting enrollments inspected by this call."),realignedCount:v("Waiting enrollments moved earlier (or that would move, on a dry run)."),unchangedCount:v("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:v("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:v("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:v("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:K1("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:v("Active enrollment count."),waiting:v("Waiting enrollment count."),total:v("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:v("Active enrollment count at this node."),waiting:v("Waiting enrollment count at this node."),total:v("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:v("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:v("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:v("Attributed conversions credited to this email."),revenueCents:v("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:v("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:K1(`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 UM(W){let $=FM[W];if($===void 0)throw Error(`MCP tool "${W}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${W}\` MCP tool.`,properties:{...DM,...$,...AQ.has(W)?zM:{}},additionalProperties:!0}}function H3(W){return{...W,outputSchema:UM(W.name)}}function z3(W){if(h(W))return W;if(Array.isArray(W))return{items:W};return{value:W}}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
|
|
|
@@ -54,7 +54,7 @@ Use cases:
|
|
|
54
54
|
- 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
|
|
55
55
|
- 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
|
|
56
56
|
|
|
57
|
-
Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var U3=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_sms_number_label",description:"Update one SMS number's settings: the user-facing label and/or its brand prefix override. Use get_sms_settings to find the number ID. Omitted fields keep their value; pass an empty string to clear one. Requires workspace-management permission.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},numberId:{type:"string",description:"SMS number ID returned by get_sms_settings."},label:{type:"string",description:"Label up to 100 characters, such as Marketing or Support. Pass an empty string to clear it."},brandPrefix:{type:"string",description:'Per-number brand prefix override up to 100 characters; messages go out as "{prefix}: your message". Pass an empty string to clear it back to the account-wide prefix.'}},required:["numberId"]}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var B3=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate. Counts form a funnel over the sends made inside the period: opened and clicked are unique per email send (not total open events) and include engagement that arrives after the period ends, so they never exceed sent. Rates divide by rateDenominator (delivered, falling back to sent), reported alongside rateDenominatorBasis. Set emailType to transactional for Send API and transactional SMTP open/click rates, including both direct and saved-template sends. When no emailType filter is used and a background-computed snapshot is available, the response also includes a top-level commerceForecast with predicted AOV, 12-month customer value, 90-day revenue, confidence, and data-eligibility reasons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},emailType:{type:"string",description:"Optional structural email type filter: campaign, transactional, or sequence. Use transactional for Send API and transactional SMTP traffic."},includeMachineEngagement:h0}}},{name:"get_transactional_stats",description:"Get aggregate sends, deliveries, bounces, opens, clicks, and rates for one saved transactional email selected by ID or slug. Results are all-time by default; pass period or start/end for a window. For direct-content Send API messages, use get_stats with emailType transactional and list_email_sends/get_email_send for delivery-level detail.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Saved transactional email ID or API slug."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:h0},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), product recommendation funnel metrics, a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},period:{type:"string",description:"Time period: 1h, 24h, 7d, 30d, or 90d"},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too"},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too"},includeMachineEngagement:h0},required:["campaignId"]}},{name:"list_poll_responses",description:"List individual Poll and NPS responses for a campaign, newest answer first, with each respondent's email, their answer and stored value, the subscriber attribute the answer was saved to, and the response time. get_campaign_stats reports the totals; this reports who answered what and when. Only each subscriber's latest answer per poll block is returned, so the counts match the campaign stats summary. Do not reconstruct respondents by scanning subscribers for the poll attribute - the attribute carries no response time and reflects the latest answer to any email. Multi-select answers list every selected option in answers/values. Results are paginated: read the returned pagination object and keep paging with page while page < totalPages.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID. For a sequence email step, pass the step's automation node ID."},blockId:{type:"string",description:"Restrict to one poll block. Block IDs come from the polls array of get_campaign_stats. Omit to return every poll block in the email."},page:{type:"number",description:"1-based page number. Defaults to 1."},limit:{type:"number",description:"Page size. Defaults to 100 and is capped at 500 by the server."}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence. The steps array is the per-step breakdown: one entry per email step in graph order with its step number, automation nodeId, subject, and its own sent, delivered, bounced, opened, clicked, replies, and unsubscribed counts plus rates - so this is where you read how many of Email 4 went out, without reconstructing anything from list_sequence_events. Step counts come from the retained event stream, not the 14-day delivery history behind list_email_sends, so they stay answerable for old sends. Also returns the aggregate funnel across every step, attributed conversions and revenue (revenueCents), product recommendation funnel metrics, per-step failed subscribers and failure reasons, and enrollmentSkipped counts for trigger matches where the contact could not be enrolled (unsubscribed/bounced). Pass period or start/end to use one explicit window for every historical metric; without them, step and aggregate counts are all-time and enrollmentSkipped defaults to the last 30 days. The enrollmentCounts field is a live snapshot of active and waiting enrollments grouped by current node, so it is not limited by period or start/end. To compare the same step across many sequences in one call, use list_email_metrics instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:h0},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:`Optional single event type. Supported values: ${E4}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${E4}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:h0},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence, or for one step via automationNodeId. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays. This is the per-recipient event stream - do not page it to count sends. Per-step and per-sequence totals already exist as get_sequence_stats steps[], and list_email_metrics gives the same per-step totals across many sequences at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},automationNodeId:{type:"string",description:"Optional email step to scope the stream to, taken from get_sequence_stats steps[].nodeId or get_sequence nodes. Must be an email step of this sequence. Defaults to every email step."},eventType:{type:"string",description:`Optional single event type. Supported values: ${E4}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${E4}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:h0},required:["sequenceId"]}},{name:"list_email_metrics",description:"List per-email metrics across the account: one row per campaign and per sequence email step, each with its own delivery funnel, attributed conversions, and revenueCents. This is the tool for cross-sequence questions - 'how many Email 4s went out across these sequences' is one call with step=4 plus the returned totals, instead of one get_sequence_stats per sequence. Sequence rows carry sequenceId, sequenceName, automationNodeId, and step, so you can group or compare steps yourself. Counts come from the retained event stream (not the 14-day list_email_sends history) and match get_sequence_stats steps[] for the same step. Filter by emailType, sequenceId, campaignId, and step; sort with sort/order; page with page/limit. totals covers every matching email, not just the current page.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailType:{type:"string",description:"Optional email type: campaign or sequence. Defaults to both. Implied as sequence when sequenceId or step is set."},sequenceId:{type:"array",description:"Optional sequence IDs to restrict the breakdown to. Omit for every sequence in the account. Cannot be combined with campaignId.",items:{type:"string"}},campaignId:{type:"array",description:"Optional campaign IDs to restrict the breakdown to. Cannot be combined with sequenceId, step, or emailType sequence.",items:{type:"string"}},step:{type:"number",description:"Optional 1-based email step position to keep, counted in graph order per sequence. step 4 keeps only the fourth email of each sequence. Sequence emails only."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided. Omit for all-time counts."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days. Omit start and end for all-time counts over the full retained window."},sort:{type:"string",description:"Sort field: sent, delivered, opened, clicked, openRate, clickRate, unsubscribed, conversions, revenue, step, or name. Defaults to sent."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Emails per page. Defaults to 50; maximum 500."},includeMachineEngagement:h0}}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:h0},required:[]}}];var L3=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];function PQ($,W){return{type:W?.nullable?["object","null"]:"object",description:$,properties:{type:{type:"string",enum:["all","lists","segment","filtered","rules"],description:"Audience shape. all = every active subscriber; lists = subscribers on any of listIds; segment = one saved segment; filtered = ad-hoc subscriber filters; rules = combined include/exclude rules."},listIds:{type:"array",items:{type:"string"},description:"List IDs to target. Required when type is 'lists'."},segmentId:{type:["string","null"],description:"Saved segment ID. Required when type is 'segment'."},filters:{type:"array",items:{type:"object"},description:"Subscriber filter objects {id, field, operator, value}. Required when type is 'filtered'."},filterJoinOperator:{type:"string",enum:["and","or"],description:"How 'filtered' filters combine. Optional, defaults to 'and'."},include:{type:"array",items:{type:"object"},description:"Include rules. Required when type is 'rules'; at least one is needed to schedule. Each rule is {type:'all'} | {type:'lists', listIds:[...]} | {type:'segments', segmentIds:[...]} | {type:'filtered', filters:[...]}."},exclude:{type:"array",items:{type:"object"},description:"Exclude rules for type 'rules'. Optional. Same shapes as include except {type:'all'}."}},required:["type"],additionalProperties:!0}}var A3=[{name:"list_campaigns",description:"List campaigns. Each item carries `emailPreset`, the linked email's Style > Format (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so chrome can be compared across campaigns without one get_campaign call each. Results are paginated: the default page size is 50 and limit is capped at 100. Always read the returned `pagination` object (`limit`, `offset`, `count`, `total`, `hasMore`) and keep paging with `offset` while `hasMore` is true - a single call does not necessarily return every campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent, sending, cancelled, paused, waiting_approval, or rejected). Rejected campaign results include rejectionComment feedback when provided."},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."},limit:{type:"number",description:"Page size from 1 to 100. Defaults to 50."},offset:{type:"number",description:"Zero-based result offset. Defaults to 0."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns. `emailId` is the campaign's linked email body - the same record returned by the templates tools - and can be passed as templateId to create_campaign to reuse the design; it is null for SMS campaigns. `emailPreset` reports that email's Style > Format the same way get_sequence does per step (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so campaign chrome can be compared against sequence steps and transactional templates without rendering them - minimal suppresses the company logo at render time. `targetLists` holds the raw audience targeting (IDs only); call get_campaign_audience for resolved list/segment names and a recipient count. Note that `computedLists` is email personalization (product lists rendered inside the email), not audience targeting. For native sends, `sentAt` is stamped when the last recipient is handed off, so on a paced send it is the end of the delivery window; `spreadOverHours`, `sendTimeOptimization`, and `sendTimeWindowHours` report recorded pacing. Imported campaigns may not include pacing metadata from their source provider, so absent pacing fields do not prove that delivery happened all at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_campaign_audience",description:"Resolve exactly who a campaign will reach. Returns the targeting kind, resolved list and segment names (flagging references that no longer exist), filter conditions, individual include/exclude adjustments, a plain-language summary, and a live recipient count. Critically, it reports whether targeting is unset - an unset campaign falls back to every active subscriber when scheduled. Use this to verify a scheduled campaign's audience before it sends. This is a read-only resolved view, not the write shape: to change targeting, pass `targetLists` (e.g. {type:'lists', listIds:['list_123']}) or the `segmentId`/`listIds` shorthands to update_campaign or schedule_campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"share_campaign",description:"Create (or fetch) the campaign's public view-in-browser link. The hosted page renders an anonymized copy - sample contact, inert unsubscribe link, no open/click tracking - so the URL is safe to forward to anyone, unlike a recipient's personal browser copy. Idempotent: if a link is already active, the same URL is returned with created=false rather than rotating it, so previously shared copies keep working. get_campaign reports the current link as shareUrl (null when none). Revoke with unshare_campaign. Email campaigns only - SMS campaigns have no browser view.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to share."}},required:["campaignId"],additionalProperties:!1}},{name:"unshare_campaign",description:"Revoke the campaign's public view-in-browser link. The shared URL returns 404 immediately, and sharing again later mints a different URL - previously distributed copies stay dead. Returns revoked=false if no link was active.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to stop sharing."}},required:["campaignId"],additionalProperties:!1}},{name:"list_email_sends",description:"List and filter the recent sent-email delivery history shown in the dashboard. Search subject/title or recipient, filter by delivery status, email type, bounce type, or source ID, then pass a returned emailSendId to get_email_send for exact open/click timestamps and the complete event timeline. Each row carries recipientEmail, subscriberId, automationNodeId, abTestVariantId, and sent/delivered/opened/clicked timestamps, so rows join into a recipient-level delivery matrix without re-reading the raw event stream. Pass automationNodeId to list only the recipients of one sequence step. Delivery rows are retained for 14 days, so this is the wrong tool for send totals: read get_sequence_stats steps[] or list_email_metrics, which cover the full retained event window.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across subject and recipient email."},subject:{type:"string",description:"Case-insensitive subject/title filter."},recipient:{type:"string",description:"Case-insensitive recipient email filter."},status:{type:"string",description:"Delivery status: pending, sent, delivered, opened, clicked, bounced, complained, failed, or suppressed. Opened includes clicked deliveries, matching the dashboard."},emailType:{type:"string",description:"Email type: campaign, transactional, or sequence."},bounceType:{type:"string",description:"Bounce type: Permanent or Transient."},campaignId:{type:"string",description:"Filter deliveries from one campaign."},transactionalEmailId:{type:"string",description:"Filter deliveries from one saved transactional email."},automationId:{type:"string",description:"Filter deliveries from one sequence/automation."},automationNodeId:{type:"string",description:"Filter deliveries from one email step of a sequence, using the nodeId from get_sequence_stats steps[] or get_sequence nodes."},days:{type:"number",description:"History window in days, from 1 to 14. Defaults to 14."},page:{type:"number",description:"Page number starting at 1. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."},sortField:{type:"string",description:"Sort field: recipientEmail, subject, status, eventAt, sentAt, or createdAt. Defaults to createdAt."},sortOrder:{type:"string",description:"Sort order: asc or desc. Defaults to desc."}}}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, effective Reply-To, copied-recipient identity and primary email send ID, and the ClickHouse event timeline. `type` is the legacy source category; use `emailType` on the send and `deliveryPolicy` on events for the actual marketing or transactional policy when known. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Shorthand for targeting one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists` and `listIds`."},listIds:{type:"array",items:{type:"string"},description:"Shorthand for targeting one or more lists. Equivalent to targetLists {type:'lists', listIds}. Mutually exclusive with `targetLists` and `segmentId`."},targetLists:PQ("Campaign audience, saved on the draft. Omit to leave targeting unset and set it later with `update_campaign` or `schedule_campaign`. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Use this to send straight to a list without creating a segment first. Mutually exclusive with `segmentId` and `listIds`."),fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:t1},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},replyToName:{type:"string",description:t1},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},targetLists:PQ("Replace the draft's saved audience, using the same shapes as `create_campaign`, e.g. {type:'lists', listIds:['list_123']}. Send null to clear it and choose the audience in `schedule_campaign` instead; omit to leave it unchanged. Mutually exclusive with `segmentId` and `listIds`.",{nullable:!0}),segmentId:{type:"string",description:"Shorthand for retargeting the draft at one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists` and `listIds`."},listIds:{type:"array",items:{type:"string"},description:"Shorthand for retargeting the draft at one or more lists. Equivalent to targetLists {type:'lists', listIds}. Mutually exclusive with `targetLists` and `segmentId`."},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign, as a one-off send or on a repeating weekly/monthly cadence via `recurringInterval`. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:PQ("Optional campaign targeting object. Omit to use saved targeting - or, when none is saved, ALL active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule. Mutually exclusive with `listIds`."),listIds:{type:"array",items:{type:"string"},description:"Shorthand for sending to one or more lists. Equivalent to targetLists {type:'lists', listIds}. Mutually exclusive with `targetLists`."},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"unschedule_campaign",description:"Return a scheduled campaign to an editable draft. Removes its pending send and recurrence without permanently cancelling it, so it can be edited and scheduled again.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Scheduled campaign ID to return to draft."}},required:["campaignId"],additionalProperties:!1}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var O3=[{name:"list_email_components",description:"List the company's reusable email components newest first. Components are saved block groups that can be dropped into emails, plus the components pinned as company defaults for a slot (currently `footer`). Pass defaultsOnly to see only the pinned defaults.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},type:{type:"string",enum:["section","footer"],description:"Optional component type filter. `section` is an ordinary saved block group; `footer` is a footer component."},defaultsOnly:{type:"boolean",description:"When true, return only components pinned as a company default for a slot."}}}},{name:"get_email_component",description:"Get one email component's blocks and metadata by id, including its `version` and whether it is pinned as a company default slot.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},componentId:{type:"string",description:"Email component ID"}},required:["componentId"]}},{name:"get_default_email_component",description:"Get the company's default component for a slot - use this to read the current email footer before editing it. Returns not_found when no default is set, which means emails fall back to the footer Sequenzy generates from the company profile.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},slot:{type:"string",enum:["footer"],description:"Default slot to read. Currently only `footer`."}},required:["slot"]}},{name:"set_default_email_component",description:"Create or replace the company's default component for a slot. This is the supported way to change the footer on every email: sequence, campaign, and AI-generated emails built from blocks clone this component when they are built, instead of the generated default footer. Raw HTML emails are the exception - block chrome cannot be injected into raw HTML, so they keep their own markup and a generated unsubscribe footer is appended at send time unless the HTML contains {{unsubscribeUrl}}. Call get_default_email_component first and edit the blocks it returns, otherwise you replace the existing footer wholesale. A default footer always keeps its unsubscribe link enabled - transactional sends hide it at render time. Editing this does not rewrite emails that were already created.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},slot:{type:"string",enum:["footer"],description:"Default slot to write. Currently only `footer`."},blocks:{type:"array",description:`Blocks that make up the default component. ${x0}`,items:{type:"object"}},name:{type:"string",description:"Optional component name. Defaults to `Default Footer` when creating the footer default."},description:{type:"string",description:"Optional human-readable description."}},required:["slot","blocks"]}},{name:"create_email_component",description:"Create a reusable email component from a block list. Component names are unique per company. Use set_default_email_component instead when the goal is to change the footer every email gets.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Component name, unique within the company."},description:{type:"string",description:"Optional human-readable description."},blocks:{type:"array",description:`Blocks that make up the component. ${x0}`,items:{type:"object"}},componentType:{type:"string",enum:["section","footer"],description:"Component type. Defaults to `section`. Creating one with type `footer` does not pin it as the company default - use set_default_email_component for that."}},required:["name","blocks"]}},{name:"update_email_component",description:"Update an email component's metadata or replace its blocks. Replacing blocks bumps the component `version`. Emails that already cloned this component keep the copy they were built with; the new version applies to emails built afterwards. Editing the component pinned as the default footer keeps its unsubscribe link enabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},componentId:{type:"string",description:"Email component ID"},name:{type:"string",description:"New component name, unique within the company."},description:{type:"string",description:"New description. Send an empty string to clear it."},blocks:{type:"array",description:`Replacement blocks for the component. Replaces the whole block list. ${x0}`,items:{type:"object"}},componentType:{type:"string",enum:["section","footer"],description:"New component type."}},required:["componentId"]}},{name:"delete_email_component",description:"Delete an email component. Emails that already rendered it keep their copied blocks, so this does not change existing emails. Deleting the component pinned as the default footer makes new emails fall back to the generated footer.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},componentId:{type:"string",description:"Email component ID"}},required:["componentId"]}}];var K3=[{name:"get_event_schema",description:"Read the published payload of a built-in event: a real example payload per provider, plus every property path with its type, the merge tag that resolves it, and a note wherever the example alone is ambiguous. Call this BEFORE writing {{event.*}} merge tags or event property filters - an unrecognized merge tag renders as an empty string rather than an error, so a guessed property name ships silently broken. It is also the only place that spells out the traps the sample cannot: money fields ending in `Cents` are minor units while `predictedLtv` is whole currency units, `price` is a preformatted display string that must not be parsed, `churnRisk` is a 0-95 percent and not a probability, and `orderId` is a string on Shopify but a number on WooCommerce. Omit eventName to list every documented event, or pass provider to get one provider's payload instead of all of them. Custom events are first-class and deliberately absent from this list: `documented: false` means no sample is published, never that the event name is invalid or will be rejected. Static reference data - it describes the event shape, not what this account has received. Use list_integration_activity or the sequence's own enrollments to see real deliveries.",inputSchema:{type:"object",properties:{eventName:{type:"string",description:"Event to describe, for example `ecommerce.order_placed` or `ecommerce.browse_abandoned`. Legacy aliases such as `order.completed` resolve to their current name. Omit to list every documented event."},provider:{type:"string",description:"Return only this provider's payload. Omit to compare every provider that documents the event.",enum:["shopify","woocommerce","manual","api","stripe"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:[]}}];var Z3=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. When something you did through these tools produced a wrong or unexpected result, also fill in userIntent, toolCalls, expected, actual, and resourceIds so the team can reproduce it. Summarize tool arguments instead of pasting raw subscriber data, and never include secrets or API keys. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support, bug when a tool misbehaved or produced a wrong result (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."},userIntent:{type:"string",description:"For bug/wrong-outcome reports: the user's request, verbatim or closely paraphrased. Omit personal data that is not needed to reproduce the problem."},toolCalls:{type:"array",maxItems:25,description:"For bug/wrong-outcome reports: the ordered tool calls that led to the problem. Summarize arguments - do not paste raw subscriber data or full email bodies.",items:{type:"object",properties:{tool:{type:"string",description:"Tool name, e.g. update_campaign."},args:{type:"string",description:"Short summary of the arguments used."},error:{type:"string",description:"Error message returned by this call, if there was one."}},required:["tool"]}},expected:{type:"string",description:"What you expected to happen."},actual:{type:"string",description:"What actually happened instead."},resourceIds:{type:"array",maxItems:50,items:{type:"string"},description:"IDs of the affected resources (campaign, sequence, subscriber, segment, ...) so the team can correlate with server logs."}},required:["message"]}}];var P3=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form. This creates the email/name fields only - add typed custom fields (select, textarea, hidden, ...) afterwards with update_form's blocks argument.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."},theme:{type:"object",description:"Optional visual theme overrides so the form matches the brand instead of the default accent. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0}},required:["name","listIds"],additionalProperties:!1}},{name:"update_form",description:"Update a saved signup form: rename it, retarget its audience, edit its copy, restyle its theme, or replace its content blocks (for example to remove unwanted blocks that render publicly). Read the current content via list_forms first when editing blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."},name:{type:"string",description:"New internal saved-form name."},listIds:{type:"array",description:"Replacement list targeting. Every public submission will be added to these lists.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied by the saved form. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the form's first heading block. Fails if the form has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the form's first paragraph block. Fails if the form has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful submissions. Pass an empty string to switch back to the confirmation message."},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the form's content blocks. Fetch the current blocks from list_forms, modify them, and send the complete array - the form must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute (name must start with a letter and may contain letters, digits, "_", ".", "-"). select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. A hidden field with a defaultValue always stores that server-owned value and ignores whatever the page posts; a hidden field with an empty defaultValue stores the value the page submits. Other kinds and their properties: heading { content, level (1-3), align }, text { content, variant ("paragraph" | "eyebrow" | "caption"), align }, image { src, alt, fit ("cover" | "contain") }, button { text, url, variant, align }, divider {}, spacer { height (8-160) }, custom-html { html, height (40-1200) } - the markup goes in "html", not "content" - feature-grid { features: [{ title, description }], columns }, testimonial { testimonials: [{ quote, name, role }] }, countdown { label, endsAt }, form-step { title, description, blockIds }, submit-button { text, width }, success-screen { heading, message }, error-state { message }. Properties outside a kind's list are rejected rather than dropped, so a typo is reported instead of silently saving an empty block. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["formId"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var V3=[{name:"upload_image_asset",description:"Upload an image to the selected company's shared media library and return a hosted URL plus a ready-to-insert Sequenzy image block. Call this before create/update campaign, sequence, template, or transactional tools, then place the returned imageBlock in the target blocks array. Provide either filePath (local stdio MCP only) or imageBase64 (works with remote MCP when the client can supply attachment bytes), not both. PNG, JPEG, GIF, and WebP are supported up to 5MB. cropHeight with objectFit:'cover' provides a precise centered screenshot crop while displayWidthPercent keeps the image responsive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},filePath:{type:"string",description:"Local path to a PNG, JPEG, GIF, or WebP image. Available only when the MCP server runs locally. Provide filePath or imageBase64, not both."},imageBase64:{type:"string",description:"Raw base64 image bytes or a base64 data URL. Use this for remote MCP clients that can access attachment bytes. Provide imageBase64 or filePath, not both."},filename:{type:"string",description:"File name including extension. Required with imageBase64; optional override with filePath."},contentType:{type:"string",description:"Image MIME type when it cannot be inferred from filename, such as image/png."},altText:{type:"string",description:"Accessible description stored with the asset and returned as imageBlock.alt. Use an empty string only for a decorative image."},sourceWidth:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source width in pixels. Provide sourceWidth and sourceHeight together when known."},sourceHeight:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source height in pixels. Provide sourceWidth and sourceHeight together when known."},displayWidthPercent:{type:"number",minimum:1,maximum:100,description:"Responsive image width as a percentage of the email content area. Defaults to 100."},cropHeight:{type:"integer",minimum:1,maximum:2000,description:"Optional fixed display height in pixels. With objectFit:'cover', the image is centered and cropped to this height."},objectFit:{type:"string",enum:["cover","contain"],description:"How the image fits cropHeight. Defaults to cover when cropHeight is provided. Only valid with cropHeight."},align:{type:"string",enum:["left","center","right"],description:"Image alignment. Defaults to center."}},additionalProperties:!1}}];var j3=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var M3=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso. Check list_integration_capabilities first - each connectable provider lists its exact connectFields there. Credentials are validated against the provider where possible, stored encrypted, and never returned; payment providers queue their initial revenue backfill automatically. The response includes the webhookUrl the user must configure at the provider with the same secret - always relay it. Reconnecting an already-connected provider replaces its stored credentials. OAuth and app-install providers (Stripe, Shopify, Supabase, GitHub, WooCommerce, Meta) are rejected with guidance: their flows need a human in the dashboard. SECURITY: only pass credentials the user explicitly provided for this purpose; suggest the CLI (`sequenzy integrations connect`) or dashboard when the user prefers keeping secrets out of the conversation.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider to connect: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","affonso"]},apiKey:{type:"string",description:"Provider API key. Required for every provider except clerk and posthog."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider. For Chargebee, pass the webhook's basic-auth credentials as username:password."},providerAccountId:{type:"string",description:"Provider account id, required for paddle (seller ID), dodo (business ID), whop (company ID, biz_...), creem (store ID), and chargebee (site name). Polar resolves it from the API key; clerk, posthog, and affonso do not use one."},settings:{type:"object",description:"PostHog only: event delivery scope. Defaults to syncing all non-internal events.",properties:{syncAllEvents:{type:"boolean",description:"Sync every event PostHog delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these PostHog event names. Set syncAllEvents to false when using this."}}},historyImport:{type:"object",description:"PostHog only: import the project's event history after connecting. Needs a personal API key with query read access.",properties:{region:{type:"string",enum:["us","eu"],description:"PostHog Cloud region hosting the project."},projectId:{type:"string",description:"Numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog personal API key (phx_...)."}},required:["region","projectId","personalApiKey"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider","webhookSecret"]}},{name:"get_integration",description:"Inspect one connected integration in depth: what the provider syncs, every event it can emit and when, every matching tag rule, which sequences trigger on those events, recent integration-specific activity, and prioritized recommendations. `observedByAccount` and `accountLastSeenAt` are account-wide because event definitions can also be updated by another integration or the public events API; use the retained activity log for connection-specific delivery diagnosis. Read-only; credentials are never returned. Get the id from list_integrations.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"list_integration_capabilities",description:"Describe what Sequenzy's integration providers do, whether or not they are connected. For each provider: category, how it connects, what it syncs, every event it emits with the real-world moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats. Use this to answer 'what would connecting Stripe give me?', to compare providers before recommending one, or to check whether an event a sequence needs actually exists for that provider. Coverage differs sharply between providers - only Shopify has storefront browse tracking, and only Stripe and Chargebee cover the full trial lifecycle - so check here rather than assuming.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Only return this provider, for example `stripe`, `shopify`, `clerk`. Omit to list every provider."},category:{type:"string",description:"Filter by category: payments, ecommerce, auth, analytics, ads, affiliate, cms, developer."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_integration_activity",description:"Read recent integration webhook and sync activity, newest first. This is the log to check when an integration reports connected but contacts or events are not appearing: each row carries the action, status, event type, matched contact, and error. Payloads are sanitized at write time, so no credentials or secrets appear here. Activity is retained for 24 hours only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Only show activity for this integration."},provider:{type:"string",description:"Only show activity for this provider, for example `stripe`."},status:{type:"string",description:"Filter by status: received, queued, processed, skipped, or failed. Use `failed` to triage a broken integration.",enum:["received","queued","processed","skipped","failed"]},limit:{type:"number",description:"Rows to return, 1-100. Defaults to 25."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"set_integration_sync_enabled",description:"Turn a supported payment integration's future bulk imports and backfills on or off. Check get_integration.availableActions first; providers without enable_sync or disable_sync are dashboard-managed. Disabling keeps the connection, credentials, and live webhook delivery active, and requires any in-flight sync to finish first. It does not disconnect the integration. Idempotent: setting the current state succeeds with `changed: false`.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},syncEnabled:{type:"boolean",description:"True to enable sync, false to pause it."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","syncEnabled"]}},{name:"get_integration_pixel",description:"Check whether a Shopify store's storefront tracking pixel is installed and reporting to this account. Read live from Shopify on every call, because a merchant can remove the pixel without Sequenzy hearing about it. ALWAYS check this before promising that browse abandonment, cart recovery, product views, collection views, or storefront search will work: without a live pixel those events never arrive, the sequences built on them never fire, and nothing anywhere reports an error. Returns `pixel.healthy`, the endpoint and signed configuration state, and `dependentEvents` - the event names that rely on this pixel. When `pixel.error` is null and `pixel.healthy` is false, those events are confirmed dark; an error means Shopify could not confirm their state. Fix a confirmed unhealthy state with activate_integration_pixel. Shopify only; other providers return a clear error.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"activate_integration_pixel",description:"Install the Shopify storefront tracking pixel on the connected store, or repoint an existing one at this account. This is what turns on product views, cart activity, and browse abandonment - the data every browse-abandonment and cart-recovery sequence depends on. Idempotent: an already-live pixel returns `changed: false`. Events start flowing on the next storefront visit and nothing is backfilled for the period the pixel was off, so run it before, not after, building the sequence. If the store granted an older permission set, this fails with a message naming the reconnect step rather than silently doing nothing. Shopify only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"sync_integration",description:"Queue a manual re-sync for an integration: customers and revenue for a payment provider (Stripe, Polar, Paddle, Dodo, Creem, Chargebee, Whop), the user backfill for Supabase, or the event-history import for PostHog. Use this for Supabase before a campaign that depends on names or plan attributes - the live trigger only sends rows that change after it was installed, so existing users have no attributes until a backfill runs. The Supabase sync reads the project, schema, and table already configured for the integration and cannot be pointed at a different table; if none is configured yet it fails saying so. This is also the supported way to retry a failed PostHog history import: it restarts from the beginning using the stored personal API key, and already-imported events dedupe, so a re-run cannot duplicate them. Returns immediately - poll get_integration to watch `syncStatus` and `lastSyncAt`, and list_integration_activity for per-row outcomes. Fails with a conflict if a sync is already queued or running; terminal BullMQ failures release PostHog imports for retry. Providers whose backfill is not API-triggerable (Shopify products, Affonso affiliates) return a clear error naming the dashboard. Check `availableActions` on get_integration to see whether this is supported before calling.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var q3=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:BH},content:{type:"object",description:I4,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:I4,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"duplicate_landing_page",description:"Duplicate a landing page. The copy is created as a draft with its own slug and stats, so the original keeps its published URL.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID to duplicate."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name with a (copy) suffix."},slug:{type:"string",description:"Optional slug for the copy. It will be normalized and made unique within the company."}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:I4,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:I4,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var I3=[{name:"list_popups",description:"List saved signup popups for a company with their status, view and conversion counts, and engagement rates. Content blocks are omitted by default to keep the response small - use get_popup for one popup's full content. Popups are the on-site overlay capture surface; use list_forms for inline embedded forms.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list popups for. If not provided, uses the currently selected company."},includeContent:{type:"boolean",description:"Include every popup's full content blocks. Off by default because each popup adds roughly 1.8k characters; prefer get_popup when you only need one."}},additionalProperties:!1}},{name:"get_popup",description:"Get one saved popup with its complete content blocks, trigger, targeting, schedule, frequency, and theme. Read this before editing blocks so the replacement array stays complete.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."}},required:["popupId"],additionalProperties:!1}},{name:"create_popup",description:"Create a saved signup popup and get the one-line script tag that deploys it. The popup is published by default; its trigger, targeting, audience, and duplicate handling stay server-side, so the deployed script carries no API key. Pick a template for the starting design, then refine copy and behavior with update_popup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the popup in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-popup name."},template:{type:"string",enum:["newsletter-modal","discount-offer","countdown-launch","minimal-slide-in","exit-lead-magnet","live-demo","launch-modal","paper-digest","stark-takeover","top-bar","announcement-bar","fullscreen-welcome"],description:"Starting design. One of: newsletter-modal, discount-offer, countdown-launch, minimal-slide-in, exit-lead-magnet, live-demo, launch-modal, paper-digest, stark-takeover, top-bar, announcement-bar, fullscreen-welcome. Defaults to newsletter-modal."},status:{type:"string",enum:["draft","published"],description:"Defaults to published, which makes the embed script live immediately. Use draft to stage a popup that should not show yet."},listIds:{type:"array",description:"List IDs every signup is added to. Omit or pass an empty array to capture into every list, matching the dashboard default. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied to every signup. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},headline:{type:"string",description:"Optional popup headline."},description:{type:"string",description:"Optional supporting popup copy."},buttonText:{type:"string",description:"Optional submit button label."},successMessage:{type:"string",description:"Confirmation shown after a successful signup when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful signups. Omit it to show the saved confirmation message."},presentation:{type:"string",enum:["modal","slide-in","floating-bar","fullscreen"],description:"How the popup is presented on the page."},placement:{type:"string",enum:["center","left","right","top","bottom"],description:"Where the popup sits in the viewport."},trigger:{type:"object",description:'When the popup opens. { "type": "delay" | "scroll" | "exit-intent" | "click" | "manual", "delaySeconds": 0-3600, "scrollPercent": 1-100, "clickSelector": "#join" }. Only the key each type uses matters: delay reads delaySeconds, scroll reads scrollPercent, and click requires a clickSelector CSS selector. Merged into the current trigger, so patching one key keeps the rest.',additionalProperties:!0},targeting:{type:"object",description:'Where the popup may show. { "domains": ["shop.example.com"], "paths": ["/pricing"], "excludedPaths": ["/checkout"], "device": "all" | "desktop" | "mobile" }. Empty arrays mean no restriction. Merged into the current targeting.',additionalProperties:!0},schedule:{type:"object",description:'Optional run window as ISO 8601 timestamps: { "startsAt": "2026-09-01T00:00:00Z", "endsAt": "2026-09-08T00:00:00Z" }. Use null on either key to clear it. Merged into the current schedule.',additionalProperties:!0},frequency:{type:"object",description:'How often one visitor sees it: { "maxDisplays": 1-100, "windowDays": 1-365 }. Merged into the current frequency.',additionalProperties:!0},visual:{type:"object",description:'Media panel and urgency treatment: { "style": "none" | "accent" | "header" | "rail" | "image" | "countdown", "placement": "top" | "left" | "center" | "right", "imageUrl": "https://...", "imageAlt": "...", "countdownMinutes": 1-10080 }. Use style "image" with an imageUrl for a product panel, or "countdown" with countdownMinutes for a deadline. Style "image" requires an https imageUrl - without one the popup renders the accent rail instead of the split layout, so setting it without an image is rejected. Merged into the current visual.',additionalProperties:!0},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the popup's content blocks. Fetch the current blocks from get_popup, modify them, and send the complete array - the popup must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute. select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. Other kinds and their properties: heading { content, level (1-3), align }, text { content, variant ("paragraph" | "eyebrow" | "caption"), align }, image { src, alt, fit ("cover" | "contain") }, button { text, url, variant, align }, divider {}, spacer { height (8-160) }, custom-html { html, height (40-1200) } - the markup goes in "html", not "content" - feature-grid { features: [{ title, description }], columns }, testimonial { testimonials: [{ quote, name, role }] }, countdown { label, endsAt }, form-step { title, description, blockIds }, submit-button { text, width }, success-screen { heading, message }, error-state { message }. Properties outside a kind's list are rejected rather than dropped, so a typo is reported instead of silently saving an empty block. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["name"],additionalProperties:!1}},{name:"update_popup",description:"Update a saved popup: rename it, publish or unpublish it via status, retarget its audience, change when and where it fires, edit its copy, restyle its theme, or replace its content blocks. Read the current content via get_popup first when editing blocks. Setting status to draft stops it showing without deleting it or changing the embed script.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."},name:{type:"string",description:"New internal saved-popup name."},status:{type:"string",enum:["draft","published"],description:"Set to published to make the popup live, or draft to stop it showing while keeping it and its stats. The embed script stays valid either way."},listIds:{type:"array",description:"Replacement list targeting. Pass an empty array to capture into every list.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied to every signup. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the popup's first heading block. Fails if the popup has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the popup's first paragraph block. Fails if the popup has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful signups. Pass an empty string to switch back to the confirmation message."},presentation:{type:"string",enum:["modal","slide-in","floating-bar","fullscreen"],description:"How the popup is presented on the page."},placement:{type:"string",enum:["center","left","right","top","bottom"],description:"Where the popup sits in the viewport."},trigger:{type:"object",description:'When the popup opens. { "type": "delay" | "scroll" | "exit-intent" | "click" | "manual", "delaySeconds": 0-3600, "scrollPercent": 1-100, "clickSelector": "#join" }. Only the key each type uses matters: delay reads delaySeconds, scroll reads scrollPercent, and click requires a clickSelector CSS selector. Merged into the current trigger, so patching one key keeps the rest.',additionalProperties:!0},targeting:{type:"object",description:'Where the popup may show. { "domains": ["shop.example.com"], "paths": ["/pricing"], "excludedPaths": ["/checkout"], "device": "all" | "desktop" | "mobile" }. Empty arrays mean no restriction. Merged into the current targeting.',additionalProperties:!0},schedule:{type:"object",description:'Optional run window as ISO 8601 timestamps: { "startsAt": "2026-09-01T00:00:00Z", "endsAt": "2026-09-08T00:00:00Z" }. Use null on either key to clear it. Merged into the current schedule.',additionalProperties:!0},frequency:{type:"object",description:'How often one visitor sees it: { "maxDisplays": 1-100, "windowDays": 1-365 }. Merged into the current frequency.',additionalProperties:!0},visual:{type:"object",description:'Media panel and urgency treatment: { "style": "none" | "accent" | "header" | "rail" | "image" | "countdown", "placement": "top" | "left" | "center" | "right", "imageUrl": "https://...", "imageAlt": "...", "countdownMinutes": 1-10080 }. Use style "image" with an imageUrl for a product panel, or "countdown" with countdownMinutes for a deadline. Style "image" requires an https imageUrl - without one the popup renders the accent rail instead of the split layout, so setting it without an image is rejected. Merged into the current visual.',additionalProperties:!0},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the popup's content blocks. Fetch the current blocks from get_popup, modify them, and send the complete array - the popup must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute. select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. Other kinds and their properties: heading { content, level (1-3), align }, text { content, variant ("paragraph" | "eyebrow" | "caption"), align }, image { src, alt, fit ("cover" | "contain") }, button { text, url, variant, align }, divider {}, spacer { height (8-160) }, custom-html { html, height (40-1200) } - the markup goes in "html", not "content" - feature-grid { features: [{ title, description }], columns }, testimonial { testimonials: [{ quote, name, role }] }, countdown { label, endsAt }, form-step { title, description, blockIds }, submit-button { text, width }, success-screen { heading, message }, error-state { message }. Properties outside a kind's list are rejected rather than dropped, so a typo is reported instead of silently saving an empty block. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["popupId"],additionalProperties:!1}},{name:"get_popup_embed",description:"Get a published popup's script URL and ready-to-paste embed snippets for plain HTML, React/Next.js, WordPress, and Shopify. The snippet contains no API key - the trigger, targeting, and audience rules stay server-side.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."}},required:["popupId"],additionalProperties:!1}},{name:"duplicate_popup",description:"Copy a saved popup into a new draft with its own view and conversion counts. The original keeps showing and keeps its stats. Use this to test a new offer or headline against a popup that already performs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID to copy."},name:{type:"string",description:'Name for the copy. Defaults to the original name with " (copy)" appended.'}},required:["popupId"],additionalProperties:!1}},{name:"delete_popup",description:"Permanently delete a saved popup and its view and conversion counts. Subscribers it already captured are not affected. To stop a popup from showing while keeping its stats, set status to draft with update_popup instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."}},required:["popupId"],additionalProperties:!1}}];var N3=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product. For Stripe products, variants are the product's active prices (variantId = Stripe price ID), so an exact price can be targeted even when it is not the default. Returns one page: check pagination.total and pagination.hasMore, and page with offset to read the whole catalog.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."},limit:{type:"number",description:"Maximum products to return (1-100). Defaults to 50. Compare pagination.total against the products returned to detect truncation."},offset:{type:"number",description:"Number of products to skip. Defaults to 0. Use with limit to page through catalogs larger than 100."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."},providerCreatedAt:{type:["string","null"],description:"ISO 8601 creation time from the source catalog. Omit to preserve the stored value; pass null to clear it. Used for newest-product ranking."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration with bulk sync enabled. Pass integrationId when more than one Stripe account is connected; otherwise the most recently connected enabled account is used.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},integrationId:{type:"string",description:"Stripe integration ID from list_integrations. Recommended when multiple Stripe accounts are connected."}}}}];var E3=[{name:"render_email",description:"Render a campaign, sequence email step, or template to the exact email-safe HTML that would be sent, for embedding a visual preview in an external builder or dashboard, or for checking merge tags before anyone is enrolled. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact, so contact-specific merge tags resolve to empty values. Check unresolvedMergeTags in the response to tell an unrecognized tag apart from one that is merely blank for this contact - both render as an empty string, so the HTML alone cannot distinguish them. Only names this render could check are called unknown. Nothing is checkable without the contact's attributes, because a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass subscriberId (or an inline subscriber with customAttributes) to catch typos at all. On top of that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event, and {{recommendedProducts.*}} is only checkable when a stored subscriberId returns recommendations. Rendering a transactional email is checkable only when variables is passed, since its tags come from the variables of each send call and nothing marks them as such. 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 sequence step downstream of a create_discount step renders {{discount.*}} with that step's real terms and a clearly fake sample code; when the step is reachable by paths that do not all run the same discount step, or when a template is rendered on its own, {{discount.*}} is reported as no_value rather than as a typo. Links stay clean unless tracking is true. Per-send click redirects and the open pixel are added at send time against a real email send record, so they never appear here.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to render."},sequenceId:{type:"string",description:"Sequence ID. Requires nodeId."},nodeId:{type:"string",description:"Email step node ID from get_sequence. Requires sequenceId."},templateId:{type:"string",description:"Template ID to render."},subscriberId:{type:"string",description:"Personalize as this stored subscriber. Mutually exclusive with subscriber. The rendered HTML then carries that subscriber's details, so this needs the subscribers:read scope as well."},subscriber:{type:"object",description:"Personalize as an ad-hoc contact that need not exist in the account. Mutually exclusive with subscriberId.",properties:{email:{type:"string",description:"Contact email address."},firstName:{type:"string",description:"Contact first name."},lastName:{type:"string",description:"Contact last name."},customAttributes:{type:"object",description:"Custom attributes used by merge tags and blocks.",additionalProperties:!0}},required:["email"]},variables:{type:"object",description:"Extra merge variables layered over the contact's attributes. Values are HTML-escaped; content can prefix a tag with 'html.' ({{html.subscriber.body_html}}) to render a trusted, sanitized HTML value unescaped, and this tool previews that exactly as a send would.",additionalProperties:!0},locale:{type:"string",description:"Force a localization locale instead of deriving it from the contact."},variantId:{type:"string",description:"Render a specific A/B test variant of the campaign or sequence step."},tracking:{type:"boolean",description:"Apply the company's auto-UTM link decoration as a real send would. Defaults to false so the preview shows the author's clean URLs."}},required:[]}}];var A$={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},T3={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},attributePath:{type:["string","null"],description:"Subscriber attribute path required for attribute_change goals."},attributeCondition:{type:["string","null"],enum:["changed","changed_to","changed_from_to",null],description:"How the subscriber attribute must change."},attributeValue:{type:["string","null"],description:"Target value for changed_to or changed_from_to."},attributePreviousValue:{type:["string","null"],description:"Previous value required for changed_from_to."},eventPropertyName:{type:["string","null"],description:"Optional event property whose numeric value is tracked."},eventPropertyLabel:{type:["string","null"],description:"Display label for the tracked event property."},attributionWindowHours:{type:"integer",minimum:1,maximum:720,description:"Attribution window in whole hours."},isActive:{type:"boolean",description:"Whether conversion tracking is active for this goal. Defaults to true when creating."}},R3=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:A$,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event or subscriber-attribute conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...A$,...T3},required:["sequenceId","name"],additionalProperties:!1}},{name:"update_sequence_goal",description:"Update a persisted sequence conversion goal, including its signal, attribution window, or active state.",inputSchema:{type:"object",properties:{...A$,goalId:{type:"string",description:"Sequence goal ID."},...T3},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...A$,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var VQ={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},S3=[{name:"get_sequence_inbound_webhook",description:"Read the usable URL, mapping, sample payload, and setup status for a sequence inbound webhook.",inputSchema:{type:"object",properties:VQ,required:["sequenceId"],additionalProperties:!1}},{name:"configure_sequence_inbound_webhook",description:"Create or update the secret endpoint attached to a sequence inbound_webhook trigger. On first setup, omitted mapping/sample inputs apply the selected catalog or custom integration defaults; on later calls, omitted inputs keep the saved values, so a captured sample survives mapping-only updates. Use clearFieldMapping to return to pending setup and clearSamplePayload to drop the saved sample.",inputSchema:{type:"object",properties:{...VQ,fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},samplePayload:{type:"object",description:"Representative raw webhook payload for mapping setup.",additionalProperties:!0},clearFieldMapping:{type:"boolean",description:"Set true to clear the saved mapping and return the endpoint to pending_setup."},clearSamplePayload:{type:"boolean",description:"Set true to clear the saved sample payload."}},required:["sequenceId"],additionalProperties:!1}},{name:"rotate_sequence_inbound_webhook_secret",description:"Rotate the inbound webhook secret and return a new URL. The previous URL stops working immediately.",inputSchema:{type:"object",properties:VQ,required:["sequenceId"],additionalProperties:!1}}];var C3=[{name:"list_sequences",description:"List all email sequences (automations). Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},status:{type:"string",enum:["draft","active","paused","archived"],description:"Optional dashboard status filter."},search:{type:"string",description:"Case-insensitive search across sequence name and description."},labels:{type:"array",items:{type:"string"},description:"Return sequences assigned any of these dashboard label names."},limit:{type:"number",description:"Page size from 1 to 100. When limit and offset are both omitted, every sequence is returned."},offset:{type:"number",description:"Zero-based result offset."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, emailPreset (the per-email Style > Format for native blocks, including emails with supported custom HTML blocks; null when the entire email is standalone raw HTML), and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"list_sequence_enrollments",description:"List the individual contacts currently enrolled in a sequence, with the node each one is sitting on. Use this when get_sequence_stats gives you enrollmentCounts and you need the actual subscribers behind a number, such as everyone waiting at one step. Filter by currentNodeId (take the ID from get_sequence_stats enrollmentCounts.byCurrentNode or get_sequence nodes), status, subscriberId, or email, and page with limit/offset to export the full list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be listed."},currentNodeId:{type:"array",items:{type:"string"},description:"Only return enrollments currently sitting on these sequence node IDs."},status:{type:"array",items:{type:"string",enum:["active","waiting","completed","failed","cancelled"]},description:"Enrollment statuses to include. Defaults to active and waiting, which is every contact still moving through the sequence."},subscriberId:{type:"array",items:{type:"string"},description:"Only return enrollments for these subscriber IDs. Useful for checking where specific contacts stand."},email:{type:"string",description:"Only return enrollments for this exact email address (case-insensitive)."},sort:{type:"string",enum:["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],description:"Result order. Defaults to enrolled_at_desc (most recently enrolled first). Use wait_until_asc to see who resumes next."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved email step in a sequence. Call get_sequence first and pass the target email step's nodeId. Accepts 1-10 reviewer email addresses and returns one durable emailSendId per recipient for get_email_send delivery inspection. The sequence is not enabled and no subscribers are enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID containing the saved email step."},nodeId:{type:"string",description:"Email step nodeId from get_sequence. The node must belong to sequenceId."},recipients:{type:"array",minItems:1,maxItems:10,items:{type:"string",format:"email"},description:"One to ten internal reviewer email addresses. Duplicate addresses are sent only once."}},required:["sequenceId","nodeId","recipients"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code (later emails print it with {{discount.code}}), subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:t1},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},description:{type:"string",description:"Optional sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses blind-copied on every email in the sequence (max 10)."},labels:{type:"array",items:{type:"string"},description:"Dashboard label names to assign. Missing labels are created."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Trigger type: contact_added, tag_added, segment_entered, event_received, inbound_webhook, inactivity, or frequency. Defaults to contact_added for a blank dashboard-compatible draft."},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered triggers, cancel active enrollments when the contact leaves the segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inbound_webhook, inactivity, and frequency triggers)"},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook, for example cal-com."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Custom inbound webhook integration descriptor with name, setupInstructions, samplePayload, and fieldMapping.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",additionalProperties:!0},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"]}}},required:["name","setupInstructions","samplePayload","fieldMapping"]},propertyFilters:{type:"array",description:"Optional filters for event_received or inbound_webhook triggers. The sequence starts only when all filters match. Max 10.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Defaults to 'unlimited', which re-enrolls a subscriber every time the trigger fires again - for a tag_added drip that means re-applying the tag sends the whole series a second time, so set 'one_time' unless repeat runs are wanted. Exception: ecommerce.back_in_stock and ecommerce.replenishment_due triggers default to 'matching_field' so each product is notified separately; leave those alone unless the user asks otherwise. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value. Changeable later with update_sequence."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:J$,stopCondition:{type:"object",description:"Optional explicit auto-stop condition, re-evaluated before every step including the first one. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'added_to_list', value: 'list_123' } when they join a list, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. event_received only counts events received after enrollment - the enrolling event and earlier history never satisfy the stop. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching. For type 'event_received': { mode: 'event_property_filter', propertyFilters: [{ path: 'quota_used', operator: 'greater_than', value: 1 }] } stops only when an event received after enrollment matches every filter (operators: exists, not_exists, equals, not_equals, one_of, contains, greater_than, less_than), or { mode: 'event_property', rules: [{ entryFieldPath: 'orderId', eventFieldPath: 'orderId' }] } stops only when the stop event's field equals the same field on the enrolling event. For type 'field_changed': { mode: 'field_value', operator: 'equals', value: 'pro' } stops only when the field changes to a matching value. event_received stops only match events received after enrollment, so a stop on the trigger's own event name is safe when combined with propertyFilters.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value"]},propertyFilters:{type:"array",description:"event_property_filter mode: filters the stop event must all match; same shape as trigger propertyFilters.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Comparison value (string, number, or boolean; array for one_of). Omit for exists/not_exists."}},required:["path","operator"]}},rules:{type:"array",description:"event_property mode: entry-vs-stop-event field equality rules.",items:{type:"object",properties:{entryFieldPath:{type:"string"},eventFieldPath:{type:"string"}},required:["entryFieldPath","eventFieldPath"]}},operator:{type:"string",enum:["equals","not_equals","greater_than","less_than","contains","not_contains"],description:"field_value mode comparison operator."},value:{type:"string",description:"field_value mode comparison value."}},additionalProperties:!0}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:I6,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. Use this for imported provider HTML. ${U0}`},isTransactional:{type:"boolean",description:"Send this email as transactional and omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Addresses CC'd on this email step."},bccEmails:{type:"array",items:{type:"string"},description:"Addresses BCC'd on this email step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string",description:"Filename shown in the recipient's email client. Event merge tags are supported, for example file-{{event.order_id}}.pdf."},path:{type:"string",description:"Public HTTPS URL or event-backed URL template such as {{event.file_url}}; resolved per enrollment and fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). Paths may use {{event.*}} values from the event that enrolled the subscriber; the resolved public URL is validated and fetched at send time."},...T4,text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:V6,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:Z6,waitUntilWeekday:P6,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:`Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.${Q$}`,properties:{label:{type:"string",description:"Builder label for the discount step."},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. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name"]}}];var k3=[{name:"update_sequence",description:"Update an existing sequence: both its settings and its steps. Sequence-level settings live directly on this tool - name, description, labels, trigger (with its trigger-specific field), enrollmentMode plus enrollmentFieldPath, enrollmentPaused, userCancellable, stopCondition, sendingWindow, bccEmails, and the sender/reply identity. This is the only way to change enrollmentMode after create_sequence, so use it to move a tag- or event-triggered sequence off the default 'unlimited' re-entry to 'one_time' or 'matching_field'. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. Deleting a step immediately moves parked recipients to its unique surviving successor, or completes them when no successor remains; inspect migratedRecipientCount and completedRecipientCount in the returned sequence. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},description:{type:"string",description:"Sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},labels:{type:"array",items:{type:"string"},description:"Replace dashboard labels by name. Missing labels are created; [] clears labels."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Atomically replace the existing dashboard trigger. Include the fields required by the new trigger type. Active sequences also require confirmLiveChange:true."},listId:{type:"string",description:"List ID for a contact_added trigger replacement."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},segmentId:{type:"string",description:"Saved segment ID required for a segment_entered trigger replacement."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered, stop active enrollments when the subscriber leaves the segment."},eventName:{type:"string",description:"Event name required for event_received, inbound_webhook, inactivity, and frequency trigger replacements."},propertyFilters:{type:"array",description:"Optional event-property filters for event_received or inbound_webhook.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Scalar comparison value, or an array for one_of."}},required:["path","operator"],additionalProperties:!1}},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Typed custom inbound webhook descriptor used instead of a catalog integration.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"],additionalProperties:!1}}},required:["name","setupInstructions","samplePayload","fieldMapping"],additionalProperties:!1},inactiveDays:{type:"number",description:"Days without event activity required for an inactivity trigger."},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"Baseline for subscribers who have never produced the inactivity event."},minCount:{type:"number",description:"Minimum event count for a frequency trigger."},timeWindowDays:{type:"number",description:"Frequency trigger lookback window in days."},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:t1},replyProfileId:{type:"string",description:"Set an existing reply profile (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms replacing the trigger of an active sequence. Required with trigger when the sequence is active."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. Use this to move an existing sequence off the default 'unlimited', which re-enrolls a subscriber every time the trigger fires again. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:J$,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition, which is re-evaluated before every step including the first one. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'added_to_list', value: 'list_123' } to stop when they join a list, or { type: 'none', value: null } to clear it. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. event_received only counts events received after enrollment - the enrolling event and earlier history never satisfy the stop. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching, three shapes keyed by mode. (1) For type 'event_received', { mode: 'event_property_filter', propertyFilters: [{ path: 'quota_used', operator: 'greater_than', value: 1 }] } stops only when an event received AFTER enrollment matches every filter (operators: exists, not_exists, equals, not_equals, one_of, contains, greater_than, less_than - same shape as trigger propertyFilters). Use this when a later occurrence must satisfy specific criteria, e.g. enroll on quota_used=1 and stop when quota_used is greater than 1. Without propertyFilters, a same-name event stop fires on any later occurrence. (2) For type 'event_received', { mode: 'event_property', rules: [{ entryFieldPath: 'orderId', eventFieldPath: 'orderId' }] } stops only when the stop event's field equals the same field captured on the enrolling event (requires an event-based trigger). (3) For type 'field_changed', { mode: 'field_value', operator: 'equals', value: 'pro' } stops only when the field changes to a matching value (operators: equals, not_equals, greater_than, less_than, contains, not_contains). Pass null to clear. Note: event_received stops only match events received after enrollment; the enrolling event itself never satisfies the stop.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value"],description:"Which matching shape the config uses. Defaults to event_property_filter when omitted and propertyFilters is present."},propertyFilters:{type:"array",description:"event_property_filter mode: filters a stop event must all match, e.g. [{ path: 'quota_used', operator: 'greater_than', value: 1 }].",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the stop event's properties, e.g. 'quota_used' or 'order.total'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Comparison value (string, number, or boolean; array of values for one_of). Omit for exists/not_exists."}},required:["path","operator"]}},rules:{type:"array",description:"event_property mode: entry-vs-stop-event field equality rules, e.g. [{ entryFieldPath: 'orderId', eventFieldPath: 'orderId' }].",items:{type:"object",properties:{entryFieldPath:{type:"string"},eventFieldPath:{type:"string"}},required:["entryFieldPath","eventFieldPath"]}},operator:{type:"string",enum:["equals","not_equals","greater_than","less_than","contains","not_contains"],description:"field_value mode comparison operator."},value:{type:"string",description:"field_value mode comparison value."}},additionalProperties:!0}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. Use get_sequence first to choose afterNodeId and existing target nodes. Each conditional path can provide new steps, targetNodeId, or both; the else path uses elseSteps and/or elseTargetNodeId. A target may be the completion node. Empty paths require allowEmptyPaths:true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},splitMode:JQ,randomPercentages:wQ,branches:{type:"array",description:GQ,items:XQ},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path. Not valid on a random split.",items:R4},elseTargetNodeId:{type:"string",description:"Optional existing node to route the else path to. Use a node ID from get_sequence, including the completion node. If elseSteps are also provided, they run before this target."},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating UI placeholders. A path with targetNodeId is already explicit and does not need this flag."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:R4}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${U0}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${U0}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company 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. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${O1}${X$}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (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. Pass [] to remove all attachments."},...T4}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${U0}`},htmlContent:{type:"string",description:`Alias for html. ${U0}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company 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. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${O1}${X$}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (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. Pass [] to remove all attachments."},...T4}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:I6},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. For a direct text-forward email, use changes:{ emailPreset:'minimal' } on its action_email node; this changes only that linked email's Style > Format. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:w$.properties.nodeId,changes:pW,expectedUpdatedAt:w$.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays or setting several action_email nodes to changes:{ emailPreset:'minimal' } without changing the company theme. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:w$},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; duplicate_node creates an independent copy; delete_node safely splices a node and immediately moves parked recipients to its unique surviving successor (or completes them when none remains); replace_edges replaces the complete topology. The returned sequence reports migratedRecipientCount and completedRecipientCount. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one dashboard-compatible typed step into an existing sequence: email, SMS, delay/date wait, discount (later emails print the generated code with {{discount.code}}), subscriber update, tag/list action, outbound webhook, AI step (later steps use the generated text with {{ai.KEY.field}}), condition gate, wait-for-event, or wired If/Else branch. Use get_sequence first and pass afterNodeId. Branch paths can target existing nodes, including completion. To nest a branch inside a branch path, end that path with the step the nested branch should follow, then call insert_sequence_step again with type 'logic_branch' and afterNodeId set to that path node - addedBranchPathNodeIds in the response lists each path's node IDs in order, and the nested paths reconnect to the shared steps that already followed it. A logic_branch with splitMode 'random' plus randomPercentages is a weighted split rather than an If/Else, so it runs a concurrent A/B test inside the flow - use it to compare two offers in the same abandoned-cart sequence instead of running duplicate sequences one after another. To A/B test the content of one existing email step and have a winner picked automatically, use create_ab_test with automationNodeId instead. For active sequences, confirm the structural change first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms","delay","create_discount","update_subscriber","add_tag","remove_tag","add_to_list","remove_from_list","webhook","ai","condition","logic_wait_for_event","logic_branch"],description:"Dashboard step type. Defaults to email."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:K6,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${U0}`},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 in addition to sequence-level 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."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new 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:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new 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. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: Reply-To display name override for the new step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"Display label for SMS, wait-for-event, or branch steps."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},config:{...I6,description:"update_subscriber only: typed subscriber profile/custom-attribute changes."},tagId:{type:"string",description:"Tag ID for tag actions or tag conditions."},tagName:{type:"string",description:"Tag name for tag actions or tag conditions; missing definitions are created."},listId:{type:"string",description:"List ID for list actions or in_list conditions."},listName:{type:"string",description:"Optional cached list display name for list actions."},url:{type:"string",description:"webhook only: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}}."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'webhook only: 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:"webhook / 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 ai steps. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"webhook / 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."},prompt:{type:"string",description:"ai only: prompt template sent to the model, resolved per contact at execution time. Ask for the short per-contact fragments the output fields name (a sentence or two each), never a whole email - the email around them is authored separately. Supports merge tags like {{first_name}}, {{event.plan}}, and {{webhooks.KEY.data.field}}. Max 8000 chars."},outputFields:{type:"array",description:"ai only: 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. 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. Letters, numbers, underscores; must start with a letter; unique within the step."},description:{type:"string",description:"What the model should produce for this field. Max 300 chars."},maxLength:{type:"integer",minimum:1,maximum:4000,description:"Hard cap on stored characters (1-4000). Defaults to 500."},fallback:{type:"string",description:"Text used verbatim when generation fails or the model omits the field."}},required:["key"],additionalProperties:!1}},includeTags:{type:"boolean",description:"ai only: include the contact's tags in the prompt context."},includeEventProperties:{type:"boolean",description:"ai only: include the enrollment's trigger event name and properties in the prompt context."},includeRecentEvents:{type:"boolean",description:"ai only: include the contact's most recent custom events (newest first) in the prompt context."},recentEventLimit:{type:"number",description:"ai only: how many recent events to include when includeRecentEvents is true (1-50, default 10)."},includeAttributes:{type:"array",items:{type:"string"},description:"ai only: custom attribute keys to include in the prompt context (max 30). Only the listed keys are sent."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional cached segment display name."},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 only: condition evaluated before continuing."},linkUrl:{type:"string"},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"]},fieldName:{type:"string"},fieldValue:{type:"string"},delay:V6,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:Z6,waitUntilWeekday:P6,eventName:{type:"string",description:"logic_wait_for_event only: event to wait for, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event only: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event only: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},discount:{type:"object",description:"create_discount only: provider discount configuration.",additionalProperties:!0},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"},splitMode:JQ,randomPercentages:wQ,branches:{type:"array",description:`logic_branch only: ${GQ}`,items:XQ},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path. Not valid on a random split.",items:R4},elseTargetNodeId:{type:"string",description:"logic_branch only: existing node for the else path, such as the original follow-up node or completion node."},allowEmptyPaths:{type:"boolean",description:"logic_branch only: set true only to create empty dashboard placeholders. Explicit target nodes do not require it."}},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"duplicate_sequence",description:"Create an independent draft copy of a sequence, including its graph, email templates, and sequence A/B tests. The original is not changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to copy."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name plus (Copy)."}},required:["sequenceId"]}},{name:"archive_sequence",description:"Archive a sequence and stop new enrollments. Archived sequences remain available in the dashboard's archive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to archive."}},required:["sequenceId"]}},{name:"unarchive_sequence",description:"Restore an archived sequence as a disabled draft so it can be reviewed before activation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Archived sequence ID to restore."}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: cancelAll to drain every active/waiting enrollment (use this to fully stop a live sequence instead of only freezing enrollment), subscriberIds for a specific batch, subscriberId for one subscriber, or fieldValues to match stored entry event properties. Every bulk target defaults to dryRun, so pass dryRun false to actually cancel. Bulk cancellation is capped per call: while the response reports remainingCount above zero, call again with the same arguments until it reaches zero.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},cancelAll:{type:"boolean",description:"Cancel every active/waiting enrollment in the sequence, regardless of how contacts entered it. Use this when segment-triggered enrollments expose no shared entry field value. Defaults to dryRun; pass dryRun false to apply."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide exactly one target."},subscriberIds:{type:"array",items:{type:"string"},description:"Up to 500 subscriber IDs to cancel in this sequence. IDs that do not resolve come back in target.notFoundSubscriberIds. Provide exactly one target."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide exactly one target."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. cancelAll, subscriberIds, and fieldValues default to dryRun unless explicitly false; a single subscriberId cancels immediately."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"move_sequence_enrollments",description:"Release a bounded batch of contacts off one sequence step and onto another, keeping their existing enrollment. Use this to let the next N contacts waiting on a delay continue early instead of cancelling and re-enrolling them, which discards the enrollment's entry event properties and stop-condition snapshots. Provide sequenceId and fromNodeId; targetNodeId defaults to the source step's only next step. Defaults to dryRun, so pass dryRun false to actually move. Moved contacts become active on the target step immediately, so this sends email as soon as the worker picks them up. limit defaults to 100 and is capped at 500 per call: while remainingCount is above zero, call again to release more. Unlike enroll_subscribers_in_sequence this still works while the sequence has new enrollment paused, because the contacts are already enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be moved."},fromNodeId:{type:"string",description:"Node ID the contacts are currently sitting on, such as the delay step they are waiting at. Get it from list_sequence_enrollments (currentNodeId) or get_sequence."},targetNodeId:{type:"string",description:"Node ID to move them onto. Defaults to the source step's next step, and is required when that step branches or is terminal. Cannot be the trigger node."},limit:{type:"number",description:"Maximum enrollments to move in this call. Defaults to 100, maximum 500."},sort:{type:"string",enum:["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"],description:"Which enrollments to take first. Defaults to wait_until_asc, meaning the contacts that have been waiting longest for their next step."},subscriberIds:{type:"array",items:{type:"string"},description:"Optional narrowing filter: only move these subscribers, up to 500. Omit to take whichever enrollments the sort selects."},dailyLimit:{type:"number",description:"Guardrail. Refuses to move more than this many enrollments onto targetNodeId in a rolling 24 hours, counting the moves recorded by earlier calls. The response reports movedInWindow and dailyRemaining so a paced release can resume tomorrow."},tags:{type:"array",items:{type:"string"},description:"Tag names applied to the moved contacts so the released wave stays identifiable. The tags must already exist (create_tag). Requires the subscribers:tag scope. Applying them never enrolls contacts in tag_added sequences."},reason:{type:"string",description:"Note stored on every moved enrollment and returned by list_sequence_enrollments as moveReason."},dryRun:{type:"boolean",description:"When true (the default), reports which enrollments would move without moving them. Pass false to apply."}},required:["sequenceId","fromNodeId"],additionalProperties:!1}},{name:"realign_sequence_enrollments",description:"Pull waiting enrollments forward to the start of the sequence's sending window on the day they are already scheduled for. Use this after changing sendingWindow (or a wait-until-weekday step) on a live sequence: node and sequence updates deliberately keep existing wait timestamps, so contacts already parked on an email-bound delay keep resuming at whatever minute their delay landed on, and a narrowed window silently defers them to the NEXT allowed day. Non-email actions are never advanced by the sequence sending window. Realignment never cancels, re-enrolls, or reschedules onto a different local day, and never pushes a contact later - a wait only ever moves earlier within the day it already has, and never earlier than now. Defaults to dryRun. Passing dryRun false queues a background apply and returns jobId; call get_sequence_enrollment_realignment until it completes. Each completed job is capped: when result.hasMore is true, queue another apply with result.nextCursor as cursor.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose waiting enrollments should realign."},nodeIds:{type:"array",items:{type:"string"},description:"Optional step IDs to limit realignment to. Use nodeIds from get_sequence, or currentNodeId values from list_sequence_enrollments. Defaults to every step."},subscriberIds:{type:"array",items:{type:"string"},description:"Optional subscriber IDs to limit realignment to (maximum 500). Defaults to every waiting contact."},cursor:{type:"string",description:"Opaque continuation cursor. When a response has hasMore true, pass its nextCursor here to continue after the enrollments already scanned."},dryRun:{type:"boolean",description:"When true (the default), reports the new wait times without writing them. Pass false to apply."}},required:["sequenceId"],additionalProperties:!1}},{name:"get_sequence_enrollment_realignment",description:"Check a queued sequence enrollment realignment. Call this with the jobId returned by realign_sequence_enrollments after applying with dryRun false. When status is completed, result contains the realignment counts, sample, and any nextCursor needed for another bounded apply call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID used when the realignment was queued."},jobId:{type:"string",description:"Realignment job ID returned by realign_sequence_enrollments."}},required:["sequenceId","jobId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var DM={type:"object",properties:{email:{type:"string",description:"Subscriber email address. Optional when the record has a phone - such rows import as phone-only (SMS) contacts."},externalId:{type:"string",description:"Customer-owned subscriber ID"},firstName:{type:"string"},lastName:{type:"string"},phone:{type:"string",description:"Phone number. National-format values use the batch defaultPhoneCountry."},status:{type:"string",enum:["active","unsubscribed","bounced"]},tags:{type:"array",items:{type:"string"}},customAttributes:{type:"object",description:"CRM fields and other custom attributes. Values may be strings, numbers, booleans, arrays of those scalar values, or null.",additionalProperties:!0},createdAt:{type:"string",description:"Original signup date (ISO 8601) from the source platform. Set this when migrating so date-relative segments are correct immediately rather than treating every imported contact as having joined today. An existing contact's date only ever moves earlier."}},required:[],additionalProperties:!1},v3=[{name:"add_subscriber",description:"Add one subscriber. Status is only applied when creating a new contact; use update_subscriber to change an existing contact's status. For multiple contacts or CRM records, use create_subscriber_import instead of looping this tool. For an email-only batch going into one list, add_subscribers_to_list is also available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Optional when phone is provided - a contact created with only a phone becomes a phone-only (SMS) contact."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},phone:{type:"string",description:"Phone number in E.164 or national format, stored as a native profile field. With no email, creates or matches a phone-only (SMS) contact."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number. Never inferred from phone presence."},firstName:{type:"string",description:"Subscriber first name, stored as a native profile field."},lastName:{type:"string",description:"Subscriber last name, stored as a native profile field."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Use firstName/lastName for names instead of attributes."},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active and does not change an existing contact; use update_subscriber for existing contacts."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."},createdAt:{type:"string",description:"Original signup date (ISO 8601) when importing a contact from another platform. Preserves their real history so date-relative segments like 'added in the last 30 days' are correct immediately instead of treating every imported contact as brand new. An existing contact's date only ever moves earlier. Supplying this also stops welcome sequences from firing, since it describes the past rather than a signup happening now."}},required:[]}},{name:"create_subscriber_import",description:"Queue one CRM-grade subscriber import with up to 5,000 full contact records. Supports names, external IDs, phones, statuses, tags, lists, and custom attributes. Prefer this over repeated add_subscriber calls. Returns an import ID for get_subscriber_import. Use optInMode='confirmed' only when the contacts already gave verified email consent.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},subscribers:{type:"array",minItems:1,maxItems:5000,items:DM,description:"Full subscriber records to import in one batch."},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How existing contacts are handled. Defaults to skip. Merge fills missing fields; overwrite replaces public fields without reactivating unsubscribed contacts."},fileName:{type:"string",description:"Optional source label shown in import history, such as copper-export.csv."},listIds:{type:"array",items:{type:"string"},description:"Lists to add every successfully imported active subscriber to."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll imported contacts. Defaults to false and requires automations:trigger."},defaultPhoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used for national-format phone numbers, such as SG or US."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for every imported phone number."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Email consent mode. Default follows workspace double opt-in settings. Confirmed creates active contacts immediately and must only be used for verified consent. Double_opt_in may send confirmation email and requires automations:trigger."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},importId:{type:"string",description:"Import ID or batch ID returned by create_subscriber_import."}},required:["importId"]}},{name:"update_subscriber",description:"Update an existing subscriber's profile, phone, status, attributes, or tags. Names and phones are native profile fields - set them here rather than as custom attributes. Setting status to unsubscribed suppresses the contact from all marketing, deactivates list memberships, and cancels active sequence enrollments while preserving the record and suppression history.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},firstName:{type:"string",description:"New first name, stored as a native profile field. Pass an empty string to clear it."},lastName:{type:"string",description:"New last name, stored as a native profile field. Pass an empty string to clear it."},phone:{type:"string",description:"New phone number in E.164 or national format, stored as a native profile field. Pass an empty string to clear it, which is rejected for a phone-only (SMS) contact that has no email. Changing the number resets SMS consent unless smsConsent is sent in the same call."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number; false unsubscribes them from SMS. Omitting this leaves consent unchanged unless phone changes, which resets consent because it belonged to the old number. Consent is never inferred from phone presence."},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"New global subscriber status. Use unsubscribed for compliance-grade suppression without deleting the record. Use active only when the contact has valid consent to be resubscribed."},attributes:{type:"object",description:"Custom attributes to update. Use firstName/lastName for names instead of attributes."},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe a subscriber while preserving the record and suppression history. Only permanently deletes when hardDelete is true.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes the subscriber and suppression history. Defaults to false, which globally unsubscribes the contact, deactivates list memberships, and cancels active sequence enrollments."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity. For commerce customers, customAttributes include nightly predictive analytics: predictedLtv (next-12-month spend), churnRisk (percent), expectedNextOrderAt, avgDaysBetweenOrders, and predictionConfidence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:h0},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"trigger_subscriber_event",description:"Emit a custom event for one subscriber, exactly as an integration or the public API would. This is the supported way to exercise event triggers, matching-field idempotency, branch conditions, and stop conditions end to end without waiting for real traffic. The event is recorded, sync rules apply, and matching event_received sequences enroll. Creates the subscriber if they do not exist. Use trigger_subscriber_events for several events on the same contact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},event:{type:"string",description:"Event name, such as saas.purchase or invoice.paid. The event definition is created if it does not exist."},properties:{type:"object",description:"Event properties. Include the sequence's matching field (for example order.id or invoice.id) when testing idempotency or cancellation by field value.",additionalProperties:!0},firstName:{type:"string",description:"First name applied to the subscriber profile."},lastName:{type:"string",description:"Last name applied to the subscriber profile."},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). Omit for live events. If this is more than an hour in the past the event is recorded as history: it is stored with its real timestamp and counts for segments and the timeline, but no sequences enroll, no sync rules apply, no waiting steps resume, and no webhooks fire. A historical event also moves the contact's signup date back to when it occurred (never later), so imported contacts do not read as added today. Use this when backfilling from another platform - never to fake a live event, since the side effects you are testing will not run."},eventId:{type:"string",description:"Your own id for this event. Makes a historical import idempotent: re-sending the same eventId writes nothing new."}},required:["event"]}},{name:"trigger_subscriber_events",description:"Emit several custom events for one subscriber in order. Events are processed independently and sequentially, so a partial failure can still leave earlier events recorded.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},events:{type:"array",minItems:1,maxItems:500,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). When every event in the batch is more than an hour old the batch is imported as history in one idempotent write, with no sequences, sync rules, waiting steps or webhooks; the contact's signup date also moves back to the earliest event in the batch (never later)."},eventId:{type:"string",description:"Your own id for this event, making a re-run idempotent."}},required:["name"],additionalProperties:!1},description:"Events to trigger, in order, for this subscriber."},firstName:{type:"string"},lastName:{type:"string"},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0}},required:["events"]}},{name:"bulk_add_subscriber_tags",description:"Add tags to up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Built for reconciling historical or derived tags: subscribers that do not exist are reported in notFound instead of being created, and tag automations do NOT run unless triggerAutomations is true. Needs the subscribers:tag scope; a tag name that does not exist yet also needs tags:write. The agent_safe key preset includes both. Use add_subscriber or update_subscriber for single-contact changes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to add to every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to tag. Combine with externalIds/subscriberIds as needed; at least one identifier list is required."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to tag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to tag."},triggerAutomations:{type:"boolean",description:"Whether tag_added sequences may enroll these contacts. Defaults to false, which is what backfills want. Requires the automations:trigger scope."}},required:["tags"]}},{name:"bulk_remove_subscriber_tags",description:"Remove tags from up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Subscribers that do not exist are reported in notFound. Needs the subscribers:tag scope; the broader subscribers:write scope also satisfies it. Use this to roll back or reconcile a derived-tag backfill.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to remove from every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to untag."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to untag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to untag."}},required:["tags"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, segment, custom attribute, or opt-out date. Each subscriber carries unsubscribedAt, the date the contact opted out - use it rather than updatedAt, which any later tag or attribute write overwrites. If you omit limit, the tool fetches all pages and returns every match in one call - that is the fastest way to enumerate an audience. To walk a large audience in chunks instead, pass limit and then follow pagination.nextCursor (or pagination.nextOffset) until pagination.hasMore is false. Default searches are newest first; searches with attribute use stable subscriber-ID ascending order.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query. A whole email address is matched exactly against the contact's email or external ID; anything shorter is a substring search across email, external ID, name, and tags. Prefer a whole address when you know it - it is an indexed lookup, while a partial term has to examine the entire audience."},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},unsubscribedAfter:{type:"string",description:"Only return contacts whose opt-out is on or after this ISO 8601 date/datetime. Bare dates use UTC midnight; datetimes must include Z or an explicit offset. Contacts with no opt-out date are excluded: active contacts, and contacts imported as already unsubscribed."},unsubscribedBefore:{type:"string",description:"Only return contacts whose recorded opt-out is on or before this ISO 8601 date/datetime. Bare dates use UTC midnight; datetimes must include Z or an explicit offset. Combine with unsubscribedAfter to audit a window of opt-outs."},attribute:{type:"string",description:'Filter by custom attribute name, e.g. "plan". Pair with attributeValue and attributeOperator. The wire form "name:value" is also accepted. Cannot be combined with segmentId - use a saved segment for compound attribute filters.'},attributeValue:{type:"string",description:"Value the custom attribute is compared against. Omit only when attributeOperator is is_not_empty."},attributeOperator:{type:"string",enum:[...G$],description:"How to compare the custom attribute. Defaults to is. Use is_not_empty to match every subscriber that has the attribute set to any value. For is_not, not_contains, or is_empty, create a segment and pass segmentId instead."},limit:{type:"number",minimum:1,description:"Maximum results to return. If omitted, the tool returns all matches across pages."},offset:{type:"number",minimum:0,maximum:999999,description:"Number of matches to skip before returning results, up to 999999. Use with limit to page through a large audience; follow pagination.nextOffset from the previous response, then switch to nextCursor for deeper pagination."},page:{type:"number",description:"1-based page number, an alternative to offset. Requires limit, which defines the page size. Cannot be combined with offset."},cursor:{type:"string",description:"pagination.nextCursor from the previous response. The cheapest way to walk a large audience in chunks, because the server does not re-scan the rows already returned. Cannot be combined with offset or page."}}}}];var _3={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},x3=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:_3,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:_3,required:["email"],additionalProperties:!1}}];var h3=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...j6],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...j6],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:nW,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example commerce collection filter (anyone who bought any product in the collection; value is a collection id or handle): [{"id":"filter-1","field":"commerceCollection","operator":"is","value":"skincare"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...dW,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:nW,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...dW,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var y3=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var f3=[{name:"list_templates",description:"List the company's email bodies newest first, including per-locale localization sync status and each body's `emailPreset` Style > Format (branded or minimal; null for standalone raw HTML). Results include standalone templates plus the bodies behind campaigns and transactional emails. Returns 50 per call by default (100 max); page with offset while pagination.hasMore is true, and read pagination.total for the full count. You can also pass a campaign's emailId to get_template to fetch one body directly. Bodies are kept when their campaign or transactional email is deleted.",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."},limit:{type:"number",description:"Templates per page, 1-100. Defaults to 50."},offset:{type:"number",description:"Templates to skip before returning results. Add pagination.count to the current offset to fetch the next page while pagination.hasMore is true."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status. `emailPreset` reports the per-email Style > Format (branded or minimal; null when the whole email is standalone raw HTML) the same way get_sequence does per step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},previewText:{type:["string","null"],description:"Inbox preview text. Send null to clear the existing preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:`Localized email HTML. Mutually exclusive with \`blocks\`. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"share_template",description:"Create (or fetch) the public view-in-browser link for an individual email - a transactional email, a sequence email, or a standalone template. Accepts an email/template ID or a transactional email's ID or slug; for a sequence email, pass the step's emailId from get_sequence. The hosted page renders an anonymized copy - sample contact, inert unsubscribe link, no open/click tracking - so the URL is safe to forward to anyone. Idempotent: if a link is already active, the same URL is returned with created=false rather than rotating it, so previously shared copies keep working. get_template reports the current link as shareUrl (null when none). Revoke with unshare_template. Campaigns have their own campaign-level link that follows the A/B winning variant - use share_campaign for those.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Email/template ID, or a transactional email's ID or slug."}},required:["templateId"],additionalProperties:!1}},{name:"unshare_template",description:"Revoke the email's public view-in-browser link. The shared URL returns 404 immediately, and sharing again later mints a different URL - previously distributed copies stay dead. Returns revoked=false if no link was active.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Email/template ID, or a transactional email's ID or slug."}},required:["templateId"],additionalProperties:!1}}];var u3=[{name:"list_transactional_emails",description:"List transactional email templates with subjects, delivery metrics, API slugs, and dashboard URLs. Each item also carries `emailPreset`, the per-email Style > Format (branded or minimal, null for a standalone raw HTML email), so a chrome drift check across templates does not need one get_transactional_email call each. Search by name, slug, or email title; filter active state; and sort by sends, opens, open rate, clicks, or CTR.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across template name, API slug, and linked email subject/title."},status:{type:"string",description:"Template status: all, active, or disabled."},sort:{type:"string",description:"Sort field: date, sends, opens, open-rate, clicks, or ctr. Defaults to date."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},includeMachineEngagement:{type:"boolean",description:"Include bot, scanner, and privacy-proxy engagement in open and click metrics. Defaults to false."}},additionalProperties:!1}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs. `emailPreset` reports the per-email Style > Format the same way get_sequence does per step (branded or minimal; null when the whole email is standalone raw HTML), so it can be compared against sequence steps and campaigns without rendering them - minimal suppresses the company logo at render time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${U0}`},blocks:{type:"array",description:`${x0} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${U0}`},blocks:{type:"array",description:`${O1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"delete_transactional_email",description:"Permanently delete a saved transactional email template by ID or slug. Use this to retire an obsolete template: the slug stops sending and becomes free to reuse. Already-sent deliveries and their stats are kept, so history and analytics survive the delete. The linked email content stays as a reusable template and comes back as `deleted.emailId`; pass that to `delete_template` to remove the content too. To stop sends without losing the template, call `update_transactional_email` with `enabled` set to false instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. The default delivery policy is transactional. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit variables take precedence. Set `emailType` to `marketing` to add subscriber suppression, a marketing footer, and RFC 8058 one-click unsubscribe. Company Reply-To defaults are inherited when no override is provided, and `{{viewInBrowserUrl}}` is replaced with a hosted copy URL. Attach up to 10 files with Base64 `content` or a public `path`; `contentId` embeds a CID image referenced by the HTML. Use `trackingSettings` with `clickTracking` or `openTracking` set to `false` to disable click-link rewriting or the open-tracking pixel for this send only; these opt-out fields cannot enable tracking the account has disabled. Returns a durable emailSendId and the accepted emailType; pass the ID to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field. Use `{{viewInBrowserUrl}}` for a hosted copy link generated at send time."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit values, including blanks, take precedence. Variables are HTML-escaped; a template can prefix a tag with 'html.' ({{html.prerenderedHtml}}) to insert a trusted, sanitized HTML value unescaped."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics, localization, and saved-name personalization on single-recipient sends. Maximum length: 255 characters."},emailType:{type:"string",description:"Delivery policy: `transactional` (default) or `marketing`. Marketing mode supports exactly one recipient and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. When omitted, the saved template or company default is used."},attachments:{type:"array",maxItems:10,description:"Files to attach (7MB total). Each item needs `filename` and exactly one of Base64 `content` or public HTTP(S) `path`. Set `contentId` to embed it as a CID image referenced from HTML, and optionally set `contentType` to override MIME detection.",items:{type:"object",properties:{filename:{type:"string"},content:{type:"string"},path:{type:"string"},contentId:{type:"string"},contentType:{type:"string"}},required:["filename"],additionalProperties:!1}},trackingSettings:{type:"object",description:"Per-send tracking opt-outs. Each field defaults to `true`, meaning the account tracking settings apply; set a field to `false` to disable that tracking for this send only. These fields cannot enable tracking the account has disabled.",properties:{clickTracking:{type:"boolean",description:"Set to `false` to skip click-link rewriting for this send only, which helps when tracking redirects break universal or deep links."},openTracking:{type:"boolean",description:"Set to `false` to skip the open-tracking pixel for this send only."}},additionalProperties:!1}},required:["to"],additionalProperties:!1}}];var c3=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...M6]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...M6]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var O$=[...F3,...M3,...K3,...v3,...x3,...N3,...h3,...L3,...f3,...O3,...D3,...A3,...E3,...P3,...I3,...q3,...V3,...C3,...k3,...R3,...S3,...u3,...B3,...y3,...j3,...c3,...U3,...Z3];async function m3($,W){let Q;switch($){case"get_account":{let X=await D("GET","/api/v1/account"),G=j1();Q={...X,selectedCompanyId:G??X.currentCompanyId};break}case"select_company":{let X=W.companyId,G=await D("GET","/api/v1/account"),J=G.companies?.find((w)=>w.id===X);if(!J)throw Error(`Company not found. Available companies: ${G.companies?.map((w)=>`${w.name} (${w.id})`).join(", ")??"none"}`);v4(X),Q={success:!0,message:`Switched to company: ${J.name}`,companyId:J.id,companyName:J.name};break}case"get_app_urls":{let X=await B$(W);Q={...A1({companyId:X,campaignId:L(W,"campaignId"),landingPageId:L(W,"landingPageId"),sequenceId:L(W,"sequenceId"),emailId:L(W,"emailId")??L(W,"templateId"),transactionalId:L(W,"transactionalId"),emailSendId:L(W,"emailSendId"),domainId:L(W,"domainId"),status:L(W,"status"),settingsTab:L(W,"settingsTab")}),...X===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let X=await D("POST","/api/v1/companies",{name:W.name,domain:W.domain});if(!X.success)throw Error("Failed to create company");let G=X.company.id,J=6,w=0,Y=X.company.status;while(Y==="processing"&&w<J){await new Promise((z)=>setTimeout(z,20000)),w++;let H=await D("GET",`/api/v1/companies/${G}`);if(H.success)Y=H.company.status}v4(G);let b=await D("GET",`/api/v1/companies/${G}`);Q={success:!0,company:b.company,message:Y==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${b.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let X=W.companyId;Q=await D("GET",`/api/v1/companies/${X}`);break}case"update_company":{let X=await T6("update_company",W),G=jH(W);Q=await D("PATCH",`/api/v1/companies/${X}`,G);break}case"get_sync_rules":{let X=W.companyId;Q=await D("GET","/api/v1/sync-rules",void 0,X);break}case"update_sync_rules":{let X=W.companyId;if(W.syncRules!==null&&!Array.isArray(W.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");Q=await D("PUT","/api/v1/sync-rules",{syncRules:W.syncRules},X);break}case"get_shopify_automation_settings":{let X=W.companyId;Q=await D("GET","/api/v1/shopify/automation-settings",void 0,X);break}case"update_shopify_automation_settings":{let X=W.companyId,G={};if(W.browseAbandonment!==void 0)G.browseAbandonment=W.browseAbandonment;if(W.cartAbandonment!==void 0)G.cartAbandonment=W.cartAbandonment;if(W.priceDrop!==void 0)G.priceDrop=W.priceDrop;if(Object.keys(G).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");Q=await D("PUT","/api/v1/shopify/automation-settings",G,X);break}case"create_api_key":{let X=W.companyId,G={};if(typeof W.name==="string")G.name=W.name;if(typeof W.preset==="string")G.preset=W.preset;if(Array.isArray(W.scopes))G.scopes=W.scopes;Q=await D("POST","/api/v1/api-keys",G,X);break}case"request_api_key_handoff":{let X=await T6($,W),G={};if(typeof W.name==="string")G.name=W.name;if(typeof W.preset==="string")G.preset=W.preset;if(Array.isArray(W.scopes))G.scopes=W.scopes;if(typeof W.replaceApiKeyId==="string")G.replaceApiKeyId=W.replaceApiKeyId;Q=await D("POST","/api/v1/api-key-handoff",G,X);break}case"list_api_keys":{let X=await T6($,W);Q=await D("GET","/api/v1/api-keys",void 0,X);break}case"update_api_key":{let X=await T6($,W),G={};if(typeof W.name==="string")G.name=W.name;if(typeof W.preset==="string")G.preset=W.preset;if(Array.isArray(W.scopes))G.scopes=W.scopes;if(Object.keys(G).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");Q=await D("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(W.apiKeyId))}`,G,X);break}case"revoke_api_key":case"delete_api_key":{let X=await T6($,W);Q=await D("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(W.apiKeyId))}`,void 0,X);break}case"list_websites":{let X=W.companyId;Q=await D("GET","/api/v1/websites",void 0,X);break}case"add_sending_domain":case"add_website":{let X=W.companyId;Q=await D("POST","/api/v1/websites",{domain:W.domain},X);break}case"check_website":{let X=W.companyId;Q=await D("GET",`/api/v1/websites/${encodeURIComponent(String(W.domain))}`,void 0,X);break}case"verify_sending_domain":{let X=W.companyId;Q=await D("POST",`/api/v1/websites/${encodeURIComponent(String(W.domain))}/verify`,void 0,X);break}case"list_integrations":{let X=W.companyId,G=new URLSearchParams;if(W.includeInactive===!0)G.set("includeInactive","true");let J=G.toString();Q=await D("GET",`/api/v1/integrations${J?`?${J}`:""}`,void 0,X);break}case"list_sender_profiles":{let X=W.companyId;Q=await D("GET","/api/v1/sender-profiles",void 0,X);break}case"update_sender_profile":{let{companyId:X,profileId:G}=W,J=W.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(G)}`:`/api/v1/sender-profiles/${encodeURIComponent(G)}`;Q=await D("PATCH",J,{name:W.name},X);break}case"get_sending_status":{let X=W.companyId;Q=await D("GET","/api/v1/sending-status",void 0,X);break}case"resume_sending":{let X=W.companyId;Q=await D("POST","/api/v1/sending-status/resume",{listSanitizationConfirmed:W.listSanitizationConfirmed===!0},X);break}case"get_tracking_settings":{let X=W.companyId;Q=await D("GET","/api/v1/tracking-settings",void 0,X);break}case"update_tracking_settings":{let X=W.companyId,G=MH(W);Q=await D("PATCH","/api/v1/tracking-settings",G,X);break}case"get_notification_preferences":{let X=W.companyId;Q=await D("GET","/api/v1/notification-preferences",void 0,X);break}case"update_notification_preferences":{let X=W.companyId;Q=await D("PATCH","/api/v1/notification-preferences",{notificationPreferences:W.notificationPreferences},X);break}case"get_integration_guide":Q=await D("POST","/api/v1/integration-guide",W);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function l3($,W){let Q;switch($){case"generate_email":{let X=W.companyId;Q=await D("POST","/api/v1/generate/email",W,X);break}case"generate_subject_lines":{let X=W.companyId;Q=await D("POST","/api/v1/generate/subjects",W,X);break}case"generate_sms":{let X=W.companyId;Q=await D("POST","/api/v1/generate/sms",W,X);break}case"get_sms_settings":{let X=W.companyId;Q=await D("GET","/api/v1/sms/settings",void 0,X);break}case"update_sms_number_label":{let X=W.companyId,G=A("update_sms_number_label",W,"numberId");if(W.label!==void 0&&typeof W.label!=="string")throw Error("update_sms_number_label `label` must be a string; pass an empty string to clear it.");if(W.brandPrefix!==void 0&&typeof W.brandPrefix!=="string")throw Error("update_sms_number_label `brandPrefix` must be a string; pass an empty string to clear it.");if(W.label===void 0&&W.brandPrefix===void 0)throw Error("update_sms_number_label requires `label` and/or `brandPrefix`.");Q=await D("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(G)}`,{...typeof W.label==="string"?{label:W.label.trim()||null}:{},...typeof W.brandPrefix==="string"?{brandPrefix:W.brandPrefix.trim()||null}:{}},X);break}case"send_test_sms":{let X=W.companyId,G={to:A("send_test_sms",W,"to")};for(let J of["text","imageUrls","blocks"])if(W[J]!==void 0)G[J]=W[J];Q=await D("POST","/api/v1/sms/test",G,X);break}case"submit_feedback":{let X=W.companyId,G={message:A("submit_feedback",W,"message"),source:"mcp"};for(let J of["category","context","userIntent","toolCalls","expected","actual","resourceIds"])if(W[J]!==void 0)G[J]=W[J];Q=await D("POST","/api/v1/feedback",G,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function g3($,W){let Q;switch($){case"list_transactional_emails":{let X=W.companyId,G=new URLSearchParams,J=L(W,"search"),w=u("list_transactional_emails",W,"status",["all","active","disabled"]),Y=u("list_transactional_emails",W,"sort",["date","sends","opens","open-rate","clicks","ctr"]),b=u("list_transactional_emails",W,"order",["asc","desc"]);if(J)G.set("search",J);if(w)G.set("status",w);if(Y)G.set("sort",Y);if(b)G.set("order",b);if(W.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");let H=G.toString();Q=await D("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,X);break}case"get_transactional_email":{let X=W.companyId;Q=await D("GET",`/api/v1/transactional/${W.idOrSlug}`,void 0,X);break}case"create_transactional_email":{let X=W.companyId,G=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),J=Object.keys(W).filter((Y)=>!G.has(Y));if(J.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((Y)=>`\`${Y}\``).join(", ")}.`);iH(W);let w=Object.fromEntries(Object.entries(W).filter(([Y])=>Y!=="companyId"));Q=await D("POST","/api/v1/transactional",w,X);break}case"update_transactional_email":{let X=W.companyId,G=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),J=Object.keys(W).filter((Y)=>!G.has(Y));if(J.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((Y)=>`\`${Y}\``).join(", ")}.`);if(y0("update_transactional_email",W),W.name===void 0&&W.enabled===void 0&&W.subject===void 0&&W.previewText===void 0&&W.html===void 0&&W.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let w=Object.fromEntries(Object.entries(W).filter(([Y])=>Y!=="companyId"&&Y!=="idOrSlug"));Q=await D("PATCH",`/api/v1/transactional/${W.idOrSlug}`,w,X);break}case"delete_transactional_email":{let X=W.companyId,G=A("delete_transactional_email",W,"idOrSlug");Q=await D("DELETE",`/api/v1/transactional/${encodeURIComponent(G)}`,void 0,X);break}case"send_email":{let X=W.companyId,G=A("send_email",W,"to"),J=W.templateId===void 0?void 0:A("send_email",W,"templateId"),w=W.subject===void 0?void 0:A("send_email",W,"subject"),Y=W.html===void 0?void 0:A("send_email",W,"html"),b=W.emailType===void 0?void 0:A("send_email",W,"emailType"),H=W.replyTo===void 0?void 0:A("send_email",W,"replyTo"),z;if(W.attachments!==void 0){if(!Array.isArray(W.attachments)||W.attachments.length>10)throw Error("`attachments` must be an array with at most 10 items when calling `send_email`.");z=W.attachments.map((B,K)=>{if(typeof B!=="object"||B===null||Array.isArray(B))throw Error(`\`attachments[${K}]\` must be an object when calling \`send_email\`.`);let P=B,q=new Set(["filename","content","path","contentId","contentType"]);if(Object.keys(P).some((v)=>!q.has(v)))throw Error(`\`attachments[${K}]\` contains an unsupported field when calling \`send_email\`.`);let M={};for(let v of q){let k=P[v];if(k===void 0)continue;if(typeof k!=="string")throw Error(`\`attachments[${K}].${v}\` must be a string when calling \`send_email\`.`);M[v]=k}if(!M.filename)throw Error(`\`attachments[${K}].filename\` is required when calling \`send_email\`.`);let S=M.content!==void 0,C=M.path!==void 0;if(S===C)throw Error(`\`attachments[${K}]\` must provide exactly one of \`content\` or \`path\` when calling \`send_email\`.`);return M})}if(b!==void 0&&b!=="marketing"&&b!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(J!==void 0&&(w!==void 0||Y!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(J===void 0&&(w===void 0||Y===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let F;if(W.trackingSettings!==void 0){if(typeof W.trackingSettings!=="object"||W.trackingSettings===null||Array.isArray(W.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let B=W.trackingSettings;F={};for(let K of["clickTracking","openTracking"]){let P=B[K];if(P===void 0)continue;if(typeof P!=="boolean")throw Error(`\`trackingSettings.${K}\` must be a boolean when calling \`send_email\`.`);F[K]=P}}let U=Object.fromEntries(Object.entries({to:G,slug:J,subject:w,body:Y,variables:W.variables,subscriberExternalId:W.subscriberExternalId,emailType:b,replyTo:H,attachments:z,trackingSettings:F}).filter(([,B])=>B!==void 0));Q=await D("POST","/api/v1/transactional/send",U,X);break}case"get_stats":{let X=W.companyId,G=W.period??"7d",J=new URLSearchParams({period:String(G)}),w=W.emailType===void 0?void 0:A("get_stats",W,"emailType");if(w!==void 0&&!["campaign","transactional","sequence"].includes(w))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(w)J.set("emailType",w);if(W.includeMachineEngagement===!0)J.set("includeMachineEngagement","true");Q=await D("GET",`/api/v1/metrics?${J.toString()}`,void 0,X);break}case"get_campaign_stats":{let X=W.companyId,G=new URLSearchParams;if(typeof W.period==="string")G.set("period",W.period);if(typeof W.start==="string")G.set("start",W.start);if(typeof W.end==="string")G.set("end",W.end);if(W.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");let J=G.toString();Q=await D("GET",`/api/v1/metrics/campaigns/${W.campaignId}${J?`?${J}`:""}`,void 0,X);break}case"list_poll_responses":{let X=W.companyId,G=A("list_poll_responses",W,"campaignId"),J=new URLSearchParams,w=L(W,"blockId");if(w)J.set("blockId",w);for(let b of["page","limit"])if(W[b]!==void 0)J.set(b,String(W[b]));let Y=J.toString();Q=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(G)}/poll-responses${Y?`?${Y}`:""}`,void 0,X);break}case"get_transactional_stats":{let X=W.companyId,G=A("get_transactional_stats",W,"idOrSlug"),J=new URLSearchParams;for(let Y of["period","start","end"])if(typeof W[Y]==="string"&&W[Y].trim())J.set(Y,W[Y].trim());if(W.includeMachineEngagement===!0)J.set("includeMachineEngagement","true");let w=J.toString();Q=await D("GET",`/api/v1/metrics/transactional/${encodeURIComponent(G)}${w?`?${w}`:""}`,void 0,X);break}case"get_sequence_stats":{let X=W.companyId,G=new URLSearchParams;for(let w of["period","start","end"])if(typeof W[w]==="string"&&W[w].trim())G.set(w,W[w].trim());if(W.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");let J=G.toString();Q=await D("GET",`/api/v1/metrics/sequences/${W.sequenceId}${J?`?${J}`:""}`,void 0,X);break}case"list_campaign_events":{let X=W.companyId,G=A("list_campaign_events",W,"campaignId"),w=UQ("list_campaign_events",W).toString();Q=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(G)}/events${w?`?${w}`:""}`,void 0,X);break}case"list_sequence_events":{let X=W.companyId,G=A("list_sequence_events",W,"sequenceId"),J=UQ("list_sequence_events",W),w=L(W,"automationNodeId");if(w)J.set("automationNodeId",w);let Y=J.toString();Q=await D("GET",`/api/v1/metrics/sequences/${encodeURIComponent(G)}/events${Y?`?${Y}`:""}`,void 0,X);break}case"list_email_metrics":{let X=W.companyId,G=new URLSearchParams,J=u("list_email_metrics",W,"emailType",["campaign","sequence"]);if(J)G.set("emailType",J);let w=hW("list_email_metrics",W,"sequenceId"),Y=hW("list_email_metrics",W,"campaignId"),b=X0("list_email_metrics",W,"step",1,1000);if(Y.length>0&&(w.length>0||b))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(J==="campaign"&&(w.length>0||b!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(J==="sequence"&&Y.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(w.length>0)G.set("sequenceId",w.join(","));if(Y.length>0)G.set("campaignId",Y.join(","));if(b!==void 0)G.set("step",String(b));let H=u("list_email_metrics",W,"period",["1h","24h","7d","30d","90d"]);if(H)G.set("period",H);for(let P of["start","end"]){let q=L(W,P);if(q)G.set(P,q)}let z=u("list_email_metrics",W,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(z)G.set("sort",z);let F=u("list_email_metrics",W,"order",["asc","desc"]);if(F)G.set("order",F);let U=X0("list_email_metrics",W,"page",1,1e6);if(U!==void 0)G.set("page",String(U));let B=X0("list_email_metrics",W,"limit",1,500);if(B!==void 0)G.set("limit",String(B));if(W.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");let K=G.toString();Q=await D("GET",`/api/v1/metrics/emails${K?`?${K}`:""}`,void 0,X);break}case"get_subscriber_activity":{let X=W.companyId,G=$1("get_subscriber_activity",W),J=await S4(G,X,{includeMachineEngagement:W.includeMachineEngagement===!0});Q={success:J.success,email:J.subscriber.email,emailStats:J.subscriber.emailStats??null,activity:J.subscriber.activity??[],sequenceEnrollments:J.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function p3($,W){let Q;switch($){case"list_tags":{let X=W.companyId;Q=await D("GET","/api/v1/tags",void 0,X);break}case"create_tag":{let X=W.companyId,G=A("create_tag",W,"name"),J=u("create_tag",W,"color",j6);Q=await D("POST","/api/v1/tags",{name:G,...J!==void 0&&{color:J}},X);break}case"update_tag":{let X=W.companyId,G=A("update_tag",W,"tagId"),J=C4("update_tag",W,"color",j6);Q=await D("PATCH",`/api/v1/tags/${encodeURIComponent(G)}`,{color:J},X);break}case"delete_tag":{let X=W.companyId,G=A("delete_tag",W,"tagId");Q=await D("DELETE",`/api/v1/tags/${encodeURIComponent(G)}`,void 0,X);break}case"list_lists":{let X=W.companyId;Q=await D("GET","/api/v1/lists",void 0,X);break}case"create_list":{let X=W.companyId;Q=await D("POST","/api/v1/lists",W,X);break}case"update_list":{let X=W.companyId,G=A("update_list",W,"listId");if(W.name===void 0&&W.description===void 0&&W.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(W.name!==void 0&&L(W,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(W.description!==void 0&&W.description!==null&&typeof W.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(W.isPrivate!==void 0&&typeof W.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");Q=await D("PATCH",`/api/v1/lists/${encodeURIComponent(G)}`,{...W.name!==void 0&&{name:L(W,"name")},...W.description!==void 0&&{description:W.description},...W.isPrivate!==void 0&&{isPrivate:W.isPrivate}},X);break}case"delete_list":{let X=W.companyId,G=A("delete_list",W,"listId");Q=await D("DELETE",`/api/v1/lists/${encodeURIComponent(G)}`,void 0,X);break}case"add_subscribers_to_list":{let X=W.companyId,G=A("add_subscribers_to_list",W,"listId"),J=LQ("add_subscribers_to_list",W),w=u("add_subscribers_to_list",W,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=u("add_subscribers_to_list",W,"optInMode",["default","confirmed","double_opt_in"])??"default";Q=await D("POST",`/api/v1/lists/${encodeURIComponent(G)}/subscribers`,{emails:J,duplicateStrategy:w,enrollInSequences:W.enrollInSequences===!0,optInMode:Y},X);break}case"remove_subscribers_from_list":{let X=W.companyId,G=A("remove_subscribers_from_list",W,"listId"),J=LQ("remove_subscribers_from_list",W);Q=await D("POST",`/api/v1/lists/${encodeURIComponent(G)}/subscribers/remove`,{emails:J},X);break}case"list_segments":{let X=W.companyId;Q=await D("GET","/api/v1/segments",void 0,X);break}case"create_segment":{PH(W);let X=W.companyId;Q=await D("POST","/api/v1/segments",{...W,...W.filters!==void 0?{filters:Y$(W.filters)}:{},...W.root!==void 0?{root:b$(W.root)}:{}},X);break}case"update_segment":{VH(W);let X=W.companyId,G=A("update_segment",W,"segmentId"),J=L(W,"name"),w=u("update_segment",W,"filterJoinOperator",["and","or"]);Q=await D("PATCH",`/api/v1/segments/${encodeURIComponent(G)}`,{...J!==void 0&&{name:J},...w!==void 0&&{filterJoinOperator:w},...W.filters!==void 0?{filters:Y$(W.filters)}:{},...W.root!==void 0?{root:b$(W.root)}:{}},X);break}case"delete_segment":{let X=W.companyId,G=A("delete_segment",W,"segmentId");Q=await D("DELETE",`/api/v1/segments/${encodeURIComponent(G)}`,void 0,X);break}case"get_segment_count":{let X=W.companyId;Q=await D("GET",`/api/v1/segments/${W.segmentId}/count`,void 0,X);break}case"list_audience_syncs":{let X=W.companyId;Q=await D("GET","/api/v1/audience-syncs",void 0,X);break}case"list_ad_accounts":{let X=W.companyId;Q=await D("GET","/api/v1/ad-accounts",void 0,X);break}case"create_audience_sync":{let X=W.companyId,G=L(W,"segmentId"),J=L(W,"predefinedSegmentId");if(G&&J)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!G&&!J)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");Q=await D("POST","/api/v1/audience-syncs",{segmentId:G,predefinedSegmentId:J,adAccountId:A("create_audience_sync",W,"adAccountId"),audienceName:A("create_audience_sync",W,"audienceName"),...W.frequency!==void 0?{frequency:W.frequency}:{}},X);break}case"update_audience_sync":{let X=W.companyId,G=A("update_audience_sync",W,"syncId");Q=await D("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(G)}`,{...W.frequency!==void 0?{frequency:W.frequency}:{},...W.isActive!==void 0?{isActive:W.isActive}:{}},X);break}case"delete_audience_sync":{let X=W.companyId,G=A("delete_audience_sync",W,"syncId");Q=await D("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(G)}`,void 0,X);break}case"sync_audience_now":{let X=W.companyId,G=A("sync_audience_now",W,"syncId");Q=await D("POST",`/api/v1/audience-syncs/${encodeURIComponent(G)}/sync`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function i3($,W){let Q;switch($){case"list_templates":{let X=W.companyId,G=new URLSearchParams,J=L(W,"label");if(J)G.set("label",J);let w=X0("list_templates",W,"limit",1,100);if(w!==void 0)G.set("limit",String(w));let Y=X0("list_templates",W,"offset",0,1e6);if(Y!==void 0)G.set("offset",String(Y));Q=await D("GET",`/api/v1/templates${G.size>0?`?${G}`:""}`,void 0,X);break}case"get_template":{let X=W.companyId;Q=await D("GET",`/api/v1/templates/${W.templateId}`,void 0,X);break}case"create_template":{let X=W.companyId;lH(W);let G=Object.fromEntries(Object.entries(W).filter(([J])=>J!=="companyId"));Q=await D("POST","/api/v1/templates",G,X);break}case"update_template":{let X=W.companyId,G=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),J=Object.keys(W).filter((w)=>!G.has(w));if(J.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);if(y0("update_template",W),K1("update_template",W),W.name===void 0&&W.subject===void 0&&W.previewText===void 0&&W.html===void 0&&W.blocks===void 0&&W.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");Q=await D("PUT",`/api/v1/templates/${W.templateId}`,W,X);break}case"set_template_localization":{let X=W.companyId,G=A("set_template_localization",W,"templateId"),J=A("set_template_localization",W,"locale"),w=A("set_template_localization",W,"subject"),Y=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),b=Object.keys(W).filter((z)=>!Y.has(z));if(b.length>0)throw Error(`\`set_template_localization\` received unsupported field${b.length===1?"":"s"}: ${b.map((z)=>`\`${z}\``).join(", ")}.`);y0("set_template_localization",W,{requireContent:!0});let H={subject:w};if(W.previewText!==void 0)H.previewText=W.previewText;if(W.html!==void 0)H.html=W.html;if(W.blocks!==void 0)H.blocks=W.blocks;Q=await D("PUT",`/api/v1/templates/${encodeURIComponent(G)}/localizations/${encodeURIComponent(J)}`,H,X);break}case"sync_template_localizations":{let X=W.companyId,G=A("sync_template_localizations",W,"templateId"),J=new Set(["companyId","templateId","locales"]),w=Object.keys(W).filter((b)=>!J.has(b));if(w.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${w.length===1?"":"s"}: ${w.map((b)=>`\`${b}\``).join(", ")}.`);let Y;if(W.locales!==void 0){if(!Array.isArray(W.locales)||W.locales.length===0||W.locales.some((b)=>typeof b!=="string"||b.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");Y=W.locales.map((b)=>b.trim())}Q=await D("POST",`/api/v1/templates/${encodeURIComponent(G)}/localizations/sync`,Y===void 0?{}:{locales:Y},X);break}case"delete_template":{let X=W.companyId;Q=await D("DELETE",`/api/v1/templates/${W.templateId}`,void 0,X);break}case"share_template":{let X=W.companyId,G=A("share_template",W,"templateId");Q=await D("POST",`/api/v1/templates/${encodeURIComponent(G)}/share-link`,void 0,X);break}case"unshare_template":{let X=W.companyId,G=A("unshare_template",W,"templateId");Q=await D("DELETE",`/api/v1/templates/${encodeURIComponent(G)}/share-link`,void 0,X);break}case"list_ab_tests":{let X=W.companyId,G=new URLSearchParams,J=L(W,"sequenceId");if(J)G.set("sequenceId",J);Q=await D("GET",`/api/v1/ab-tests${G.size>0?`?${G}`:""}`,void 0,X);break}case"get_ab_test":{let X=W.companyId;Q=await D("GET",`/api/v1/ab-tests/${W.abTestId}`,void 0,X);break}case"get_ab_test_stats":{let X=W.companyId,G=new URLSearchParams,J=L(W,"period"),w=L(W,"start"),Y=L(W,"end");if(J)G.set("period",J);if(w)G.set("start",w);if(Y)G.set("end",Y);if(W.includeMachineEngagement===!0)G.set("includeMachineEngagement","true");Q=await D("GET",`/api/v1/ab-tests/${W.abTestId}/stats${G.size>0?`?${G}`:""}`,void 0,X);break}case"restart_ab_test":{let X=W.companyId,G=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),J=Object.keys(W).filter((H)=>!G.has(H));if(J.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${J.length===1?"":"s"}: ${J.map((H)=>`\`${H}\``).join(", ")}.`);let w=L(W,"testType");if(w!==void 0&&w!=="subject"&&w!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let Y=W.winnerThreshold===void 0?void 0:Number(W.winnerThreshold);if(Y!==void 0&&(!Number.isInteger(Y)||Y<10||Y>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let b=W.variantCount===void 0?void 0:Number(W.variantCount);if(b!==void 0&&(!Number.isInteger(b)||b<2||b>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");Q=await D("POST",`/api/v1/ab-tests/${W.abTestId}/restart`,{sourceVariantId:L(W,"sourceVariantId"),testType:w,winnerThreshold:Y,variantCount:b},X);break}case"update_ab_test_variant":{let X=W.companyId,G=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),J=Object.keys(W).filter((w)=>!G.has(w));if(J.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);if(y0("update_ab_test_variant",W),W.confirmLiveChange!==void 0&&typeof W.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(W.subject===void 0&&W.previewText===void 0&&W.html===void 0&&W.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");Q=await D("PATCH",`/api/v1/ab-tests/${W.abTestId}/variants/${W.variantId}`,W,X);break}case"update_ab_test":{let X=W.companyId,G=A("update_ab_test",W,"abTestId"),J=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),w=Object.keys(W).filter((B)=>!J.has(B));if(w.length>0)throw Error(`\`update_ab_test\` received unsupported field${w.length===1?"":"s"}: ${w.map((B)=>`\`${B}\``).join(", ")}.`);if(W.confirmLiveChange!==void 0&&typeof W.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let Y=L(W,"name"),b=X0("update_ab_test",W,"testPercentage",5,50),H=X0("update_ab_test",W,"testDurationMinutes",15,1440),z=u("update_ab_test",W,"winnerCriteria",["open_rate","click_rate"]),F=u("update_ab_test",W,"testType",["subject","content"]),U=X0("update_ab_test",W,"winnerThreshold",10,1000);if(Y===void 0&&b===void 0&&H===void 0&&z===void 0&&F===void 0&&U===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");Q=await D("PATCH",`/api/v1/ab-tests/${encodeURIComponent(G)}`,{...Y!==void 0&&{name:Y},...b!==void 0&&{testPercentage:b},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...F!==void 0&&{testType:F},...U!==void 0&&{winnerThreshold:U},...W.confirmLiveChange===!0&&{confirmLiveChange:!0}},X);break}case"create_ab_test":{let X=W.companyId,G=L(W,"campaignId"),J=L(W,"automationNodeId");if(W.confirmLiveChange!==void 0&&typeof W.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(G)===Boolean(J))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let w=L(W,"name"),Y=X0("create_ab_test",W,"testPercentage",5,50),b=X0("create_ab_test",W,"testDurationMinutes",15,1440),H=u("create_ab_test",W,"winnerCriteria",["open_rate","click_rate"]),z=u("create_ab_test",W,"testType",["subject","content"]),F=X0("create_ab_test",W,"winnerThreshold",10,1000);if(W.variants!==void 0){if(!Array.isArray(W.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");W.variants.forEach((B,K)=>{if(!h(B)||typeof B.subject!=="string"||B.subject.trim()==="")throw Error(`\`variants\` item ${K+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(B.blocks!==void 0&&!Array.isArray(B.blocks))throw Error(`\`variants\` item ${K+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let U=Array.isArray(W.variants)?W.variants:void 0;if(J!==void 0&&(!U||U.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(U&&U.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");Q=await D("POST","/api/v1/ab-tests",{...G!==void 0&&{campaignId:G},...J!==void 0&&{automationNodeId:J},...W.confirmLiveChange===!0&&{confirmLiveChange:!0},...w!==void 0&&{name:w},...Y!==void 0&&{testPercentage:Y},...b!==void 0&&{testDurationMinutes:b},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...F!==void 0&&{winnerThreshold:F},...W.variants!==void 0&&{variants:W.variants}},X);break}case"add_ab_test_variant":{let X=W.companyId,G=A("add_ab_test_variant",W,"abTestId"),J=A("add_ab_test_variant",W,"subject"),w=L(W,"previewText");if(W.blocks!==void 0&&!Array.isArray(W.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(W.confirmLiveChange!==void 0&&typeof W.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");Q=await D("POST",`/api/v1/ab-tests/${encodeURIComponent(G)}/variants`,{subject:J,...w!==void 0&&{previewText:w},...W.blocks!==void 0&&{blocks:W.blocks},...W.confirmLiveChange===!0&&{confirmLiveChange:!0}},X);break}case"delete_ab_test_variant":{let X=W.companyId,G=A("delete_ab_test_variant",W,"abTestId"),J=A("delete_ab_test_variant",W,"variantId");if(W.confirmLiveChange!==void 0&&typeof W.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");Q=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(G)}/variants/${encodeURIComponent(J)}${W.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,X);break}case"delete_ab_test":{let X=W.companyId,G=A("delete_ab_test",W,"abTestId");Q=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(G)}`,void 0,X);break}case"list_campaigns":{let X=W.companyId,G=new URLSearchParams;if(W.status)G.set("status",String(W.status));let J=L(W,"label");if(J)G.set("label",J);for(let w of["limit","offset"])if(W[w]!==void 0)G.set(w,String(W[w]));Q=await D("GET",`/api/v1/campaigns?${G}`,void 0,X);break}case"get_campaign":{let X=W.companyId;Q=await D("GET",`/api/v1/campaigns/${W.campaignId}`,void 0,X);break}case"get_campaign_audience":{let X=W.companyId;Q=await D("GET",`/api/v1/campaigns/${encodeURIComponent(String(W.campaignId))}/audience`,void 0,X);break}case"get_email_send":{let X=W.companyId;Q=await D("GET",`/api/v1/email-sends/${encodeURIComponent(String(W.emailSendId))}`,void 0,X);break}case"list_email_sends":{let X=W.companyId,G=new URLSearchParams,J=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let q of J){let M=L(W,q);if(M)G.set(q,M)}let w=u("list_email_sends",W,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),Y=u("list_email_sends",W,"emailType",["campaign","transactional","sequence"]),b=u("list_email_sends",W,"bounceType",["Permanent","Transient"]),H=u("list_email_sends",W,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=u("list_email_sends",W,"sortOrder",["asc","desc"]),F=X0("list_email_sends",W,"days",1,14),U=X0("list_email_sends",W,"page",1,Number.MAX_SAFE_INTEGER),B=X0("list_email_sends",W,"limit",1,100),K=[["status",w],["emailType",Y],["bounceType",b],["sortField",H],["sortOrder",z],["days",F],["page",U],["limit",B]];for(let[q,M]of K)if(M!==void 0)G.set(q,String(M));let P=G.toString();Q=await D("GET",`/api/v1/email-sends${P?`?${P}`:""}`,void 0,X);break}case"create_campaign":{let X=W.companyId;mH(W),q6("create_campaign",W);let G=Object.fromEntries(Object.entries(W).filter(([J])=>J!=="companyId"));Q=await D("POST","/api/v1/campaigns",G,X);break}case"update_campaign":{let X=W.companyId,G=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","listIds","labels"]),J=Object.keys(W).filter((w)=>!G.has(w));if(J.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);if(y0("update_campaign",W),K1("update_campaign",W),q6("update_campaign",W,{replyFirst:!0}),[W.segmentId,W.listIds,W.targetLists].filter((w)=>w!==void 0).length>1)throw Error("Provide at most one of `segmentId`, `listIds`, or `targetLists` when calling `update_campaign`.");if(W.name===void 0&&W.subject===void 0&&W.trackingCode===void 0&&W.html===void 0&&W.blocks===void 0&&W.fromEmail===void 0&&W.senderProfileId===void 0&&W.replyTo===void 0&&W.replyProfileId===void 0&&W.ccEmails===void 0&&W.bccEmails===void 0&&W.campaignData===void 0&&W.computedLists===void 0&&W.targetLists===void 0&&W.segmentId===void 0&&W.listIds===void 0&&W.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, or label field when calling `update_campaign`.");Q=await D("PUT",`/api/v1/campaigns/${W.campaignId}`,W,X);break}case"schedule_campaign":{let X=W.companyId,G=new Set(["companyId","campaignId","scheduledAt","targetLists","listIds","sendTimeOptimization","spreadOverHours","recurringInterval"]),J=Object.keys(W).filter((w)=>!G.has(w));if(J.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`listIds\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);gH(W),Q=await D("POST",`/api/v1/campaigns/${W.campaignId}/schedule`,{scheduledAt:W.scheduledAt,...W.targetLists!==void 0&&{targetLists:W.targetLists},...W.listIds!==void 0&&{listIds:W.listIds},...W.sendTimeOptimization!==void 0&&{sendTimeOptimization:W.sendTimeOptimization},...W.spreadOverHours!==void 0&&{spreadOverHours:W.spreadOverHours},...W.recurringInterval!==void 0&&{recurringInterval:W.recurringInterval}},X);break}case"send_test_email":{let X=W.companyId;Q=await D("POST",`/api/v1/campaigns/${W.campaignId}/test`,{to:W.to},X);break}case"cancel_campaign":{let X=W.companyId,G=A("cancel_campaign",W,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/cancel`,void 0,X);break}case"share_campaign":{let X=W.companyId,G=A("share_campaign",W,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/share-link`,void 0,X);break}case"unshare_campaign":{let X=W.companyId,G=A("unshare_campaign",W,"campaignId");Q=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(G)}/share-link`,void 0,X);break}case"unschedule_campaign":{let X=W.companyId,G=A("unschedule_campaign",W,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/unschedule`,void 0,X);break}case"pause_campaign":{let X=W.companyId,G=A("pause_campaign",W,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/pause`,void 0,X);break}case"resume_campaign":{let X=W.companyId,G=A("resume_campaign",W,"campaignId"),J=X0("resume_campaign",W,"spreadOverHours",1,72);Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/resume`,{...J!==void 0&&{spreadOverHours:J}},X);break}case"delete_campaign":{let X=W.companyId,G=A("delete_campaign",W,"campaignId");Q=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(G)}`,void 0,X);break}case"duplicate_campaign":{let X=W.companyId,G=A("duplicate_campaign",W,"campaignId"),J=u("duplicate_campaign",W,"mode",["campaign","ab_test","variant"]),w=L(W,"variantId");if(J==="variant"&&w===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/duplicate`,{...J!==void 0&&{mode:J},...w!==void 0&&{variantId:w}},X);break}case"resend_campaign_to_non_openers":{let X=W.companyId,G=A("resend_campaign_to_non_openers",W,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(G)}/resend-to-non-openers`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function jQ($,W){let Q=W.blocks;if(!Array.isArray(Q))throw Error(`\`blocks\` must be an array of block objects when calling \`${$}\`.`);return Q}var FM=new Set(["list_email_components","get_email_component","get_default_email_component","set_default_email_component","create_email_component","update_email_component","delete_email_component"]);async function n3($,W){if(!FM.has($))return{handled:!1,result:void 0};let Q=L(W,"companyId");if($==="list_email_components"){let J=new URLSearchParams,w=L(W,"type");if(w)J.set("type",w);if(W.defaultsOnly===!0)J.set("defaultsOnly","true");return{handled:!0,result:await D("GET",`/api/v1/email-components${J.size>0?`?${J}`:""}`,void 0,Q)}}if($==="get_email_component"){let J=A($,W,"componentId");return{handled:!0,result:await D("GET",`/api/v1/email-components/${encodeURIComponent(J)}`,void 0,Q)}}if($==="get_default_email_component"){let J=A($,W,"slot");return{handled:!0,result:await D("GET",`/api/v1/email-components/defaults/${encodeURIComponent(J)}`,void 0,Q)}}if($==="set_default_email_component"){let J=A($,W,"slot"),Y={blocks:jQ($,W)},b=L(W,"name"),H=L(W,"description");if(b!==void 0)Y.name=b;if(H!==void 0)Y.description=H;return{handled:!0,result:await D("PUT",`/api/v1/email-components/defaults/${encodeURIComponent(J)}`,Y,Q)}}if($==="create_email_component"){let J={name:A($,W,"name"),blocks:jQ($,W)},w=L(W,"description"),Y=L(W,"componentType");if(w!==void 0)J.description=w;if(Y!==void 0)J.componentType=Y;return{handled:!0,result:await D("POST","/api/v1/email-components",J,Q)}}if($==="update_email_component"){let J=A($,W,"componentId"),w={},Y=L(W,"name"),b=L(W,"description"),H=L(W,"componentType");if(Y!==void 0)w.name=Y;if(b!==void 0)w.description=b;if(H!==void 0)w.componentType=H;if(W.blocks!==void 0)w.blocks=jQ($,W);return{handled:!0,result:await D("PATCH",`/api/v1/email-components/${encodeURIComponent(J)}`,w,Q)}}let X=A($,W,"componentId");return{handled:!0,result:await D("DELETE",`/api/v1/email-components/${encodeURIComponent(X)}`,void 0,Q)}}async function d3($,W){if($!=="get_event_schema")return{handled:!1,result:void 0};let Q=new URLSearchParams,X=L(W,"eventName");if(X)Q.set("eventName",X);let G=L(W,"provider");if(G)Q.set("provider",G);let J=Q.toString();return{handled:!0,result:await D("GET",`/api/v1/events/schemas${J?`?${J}`:""}`,void 0,L(W,"companyId"))}}async function o3($,W){let Q;switch($){case"list_forms":{let X=W.companyId;Q=await D("GET","/api/v1/forms",void 0,X);break}case"create_form":{let X=W.companyId,G=A("create_form",W,"name"),J=Array.isArray(W.listIds)?W.listIds.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean):[];if(J.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let w=u("create_form",W,"duplicateStrategy",["skip","merge","overwrite"]),Y={name:G,listIds:J};for(let b of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(W[b]!==void 0)Y[b]=W[b];if(w!==void 0)Y.duplicateStrategy=w;Q=await D("POST","/api/v1/forms",Y,X);break}case"update_form":{let X=W.companyId,G=A("update_form",W,"formId"),J=u("update_form",W,"duplicateStrategy",["skip","merge","overwrite"]),w={};for(let Y of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(W[Y]!==void 0)w[Y]=W[Y];if(J!==void 0)w.duplicateStrategy=J;if(Object.keys(w).length===0)throw Error("Provide at least one field to change when calling `update_form`.");Q=await D("PATCH",`/api/v1/forms/${encodeURIComponent(G)}`,w,X);break}case"get_form_embed":{let X=W.companyId,G=A("get_form_embed",W,"formId");Q=await D("GET",`/api/v1/forms/embed/${encodeURIComponent(G)}`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function K$($,W,Q,X,G){let J=$[W];if(J===void 0)return;if(typeof J!=="number"||!Number.isFinite(J)||J<Q||J>X||G&&!Number.isInteger(J))throw Error(`\`${W}\` must be a ${G?"integer":"number"} between ${Q} and ${X} when calling \`upload_image_asset\`.`);return J}async function t3($,W){if($!=="upload_image_asset")return{handled:!1,result:void 0};let Q=L(W,"filePath"),X=L(W,"imageBase64");if(Q===void 0===(X===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let G=L(W,"filename");if(X!==void 0&&G===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let J=K$(W,"sourceWidth",1,20000,!0),w=K$(W,"sourceHeight",1,20000,!0);if(J===void 0!==(w===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let Y=K$(W,"displayWidthPercent",1,100,!1)??100,b=K$(W,"cropHeight",1,2000,!0),H=L(W,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&b===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=L(W,"align");if(z!==void 0&&!["left","center","right"].includes(z))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let F=typeof W.altText==="string"?W.altText.trim():void 0;if(F!==void 0&&F.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let U=await J3({companyId:L(W,"companyId"),filePath:Q,imageBase64:X,filename:G,contentType:L(W,"contentType"),altText:F,sourceWidth:J,sourceHeight:w}),B={type:"image",src:U.url,alt:U.altText??"",width:Y,widthType:"percent",...b!==void 0&&{height:b,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:U,imageBlock:B,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function r3($,W){let Q=W.companyId,X;switch($){case"connect_integration":{let G=A("connect_integration",W,"provider"),J=A("connect_integration",W,"webhookSecret");X=await D("POST","/api/v1/integrations/connect",{provider:G,webhookSecret:J,...typeof W.apiKey==="string"&&W.apiKey?{apiKey:W.apiKey}:{},...typeof W.providerAccountId==="string"&&W.providerAccountId?{providerAccountId:W.providerAccountId}:{},...W.settings!==void 0?{settings:W.settings}:{},...W.historyImport!==void 0?{historyImport:W.historyImport}:{}},Q);break}case"get_integration":{let G=A("get_integration",W,"integrationId");X=await D("GET",`/api/v1/integrations/${encodeURIComponent(G)}`,void 0,Q);break}case"list_integration_capabilities":{let G=new URLSearchParams;if(typeof W.provider==="string"&&W.provider)G.set("provider",W.provider);if(typeof W.category==="string"&&W.category)G.set("category",W.category);let J=G.toString();X=await D("GET",`/api/v1/integrations/catalog${J?`?${J}`:""}`,void 0,Q);break}case"list_integration_activity":{let G=new URLSearchParams;if(typeof W.integrationId==="string"&&W.integrationId)G.set("integrationId",W.integrationId);if(typeof W.provider==="string"&&W.provider)G.set("provider",W.provider);if(typeof W.status==="string"&&W.status)G.set("status",W.status);if(typeof W.limit==="number")G.set("limit",String(W.limit));let J=G.toString();X=await D("GET",`/api/v1/integrations/activity${J?`?${J}`:""}`,void 0,Q);break}case"set_integration_sync_enabled":{let G=A("set_integration_sync_enabled",W,"integrationId");if(typeof W.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");X=await D("PATCH",`/api/v1/integrations/${encodeURIComponent(G)}`,{syncEnabled:W.syncEnabled},Q);break}case"get_integration_pixel":{let G=A("get_integration_pixel",W,"integrationId");X=await D("GET",`/api/v1/integrations/${encodeURIComponent(G)}/pixel`,void 0,Q);break}case"activate_integration_pixel":{let G=A("activate_integration_pixel",W,"integrationId");X=await D("POST",`/api/v1/integrations/${encodeURIComponent(G)}/pixel`,void 0,Q);break}case"sync_integration":{let G=A("sync_integration",W,"integrationId");X=await D("POST",`/api/v1/integrations/${encodeURIComponent(G)}/sync`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:X}}async function s3($,W){let Q;switch($){case"list_landing_pages":{let X=W.companyId;Q=await D("GET","/api/v1/landing-pages",void 0,X);break}case"get_landing_page":{let X=W.companyId;Q=await D("GET",`/api/v1/landing-pages/${W.landingPageId}`,void 0,X);break}case"create_landing_page":{let X=W.companyId,G=new Set(["companyId","name","slug","template","content"]),J=Object.keys(W).filter((w)=>!G.has(w));if(J.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);Q=await D("POST","/api/v1/landing-pages",{...W.name!==void 0&&{name:W.name},...W.slug!==void 0&&{slug:W.slug},...W.template!==void 0&&{template:W.template},...W.content!==void 0&&{content:W.content}},X);break}case"update_landing_page":{let X=W.companyId,G=F$("update_landing_page",W,{requireUpdate:!0});Q=await D("PUT",`/api/v1/landing-pages/${W.landingPageId}`,G,X);break}case"publish_landing_page":{let X=W.companyId,G=F$("publish_landing_page",W,{requireUpdate:!1});Q=await D("POST",`/api/v1/landing-pages/${W.landingPageId}/publish`,G,X);break}case"unpublish_landing_page":{let X=W.companyId,G=F$("unpublish_landing_page",W,{requireUpdate:!1});Q=await D("POST",`/api/v1/landing-pages/${W.landingPageId}/unpublish`,G,X);break}case"duplicate_landing_page":{let X=W.companyId;Q=await D("POST",`/api/v1/landing-pages/${W.landingPageId}/duplicate`,{...W.name!==void 0&&{name:W.name},...W.slug!==void 0&&{slug:W.slug}},X);break}case"delete_landing_page":{let X=W.companyId;Q=await D("DELETE",`/api/v1/landing-pages/${W.landingPageId}`,void 0,X);break}case"connect_landing_page_domain":{let X=W.companyId;Q=await D("POST","/api/v1/landing-pages/domain",{domain:W.domain},X);break}case"update_landing_page_domain_settings":{let X=W.companyId,G=pH(W);Q=await D("PUT","/api/v1/landing-pages/domain",G,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}var a3=["listIds","tagIds","headline","description","buttonText","successMessage","redirectUrl","presentation","placement","trigger","targeting","schedule","frequency","visual","theme","blocks"];async function e3($,W){let Q;switch($){case"list_popups":{let X=W.companyId,G=W.includeContent===!0;Q=await D("GET",G?"/api/v1/popups?includeContent=true":"/api/v1/popups",void 0,X);break}case"get_popup":{let X=W.companyId,G=A("get_popup",W,"popupId");Q=await D("GET",`/api/v1/popups/${encodeURIComponent(G)}`,void 0,X);break}case"create_popup":{let X=W.companyId,G=A("create_popup",W,"name"),J=u("create_popup",W,"duplicateStrategy",["skip","merge","overwrite"]),w=u("create_popup",W,"status",["draft","published"]),Y=W.template,b={name:G};for(let H of a3)if(W[H]!==void 0)b[H]=W[H];if(J!==void 0)b.duplicateStrategy=J;if(w!==void 0)b.status=w;if(Y!==void 0)b.template=Y;Q=await D("POST","/api/v1/popups",b,X);break}case"update_popup":{let X=W.companyId,G=A("update_popup",W,"popupId"),J=u("update_popup",W,"duplicateStrategy",["skip","merge","overwrite"]),w=u("update_popup",W,"status",["draft","published"]),Y={};if(W.name!==void 0)Y.name=W.name;for(let b of a3)if(W[b]!==void 0)Y[b]=W[b];if(J!==void 0)Y.duplicateStrategy=J;if(w!==void 0)Y.status=w;if(Object.keys(Y).length===0)throw Error("Provide at least one field to change when calling `update_popup`.");Q=await D("PATCH",`/api/v1/popups/${encodeURIComponent(G)}`,Y,X);break}case"get_popup_embed":{let X=W.companyId,G=A("get_popup_embed",W,"popupId");Q=await D("GET",`/api/v1/popups/embed/${encodeURIComponent(G)}`,void 0,X);break}case"duplicate_popup":{let X=W.companyId,G=A("duplicate_popup",W,"popupId"),J={};if(W.name!==void 0)J.name=W.name;Q=await D("POST",`/api/v1/popups/${encodeURIComponent(G)}/duplicate`,J,X);break}case"delete_popup":{let X=W.companyId,G=A("delete_popup",W,"popupId");Q=await D("DELETE",`/api/v1/popups/${encodeURIComponent(G)}`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function $z($,W){let Q;switch($){case"list_products":{let X=W.companyId,G=new URLSearchParams;if(typeof W.provider==="string"&&W.provider.trim())G.set("provider",W.provider.trim());if(typeof W.search==="string"&&W.search.trim())G.set("search",W.search.trim());let J=X0("list_products",W,"limit",1,100);if(J!==void 0)G.set("limit",String(J));let w=X0("list_products",W,"offset",0,Number.MAX_SAFE_INTEGER);if(w!==void 0)G.set("offset",String(w));let Y=G.size>0?`?${G.toString()}`:"";Q=await D("GET",`/api/v1/products${Y}`,void 0,X);break}case"upsert_products":{let X=W.companyId;if(!Array.isArray(W.products)||W.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");Q=await D("POST","/api/v1/products",{products:W.products},X);break}case"delete_product":{let X=W.companyId,G=A("delete_product",W,"productId");Q=await D("DELETE",`/api/v1/products/${encodeURIComponent(G)}`,void 0,X);break}case"attach_product_file":{let X=W.companyId,G=A("attach_product_file",W,"productId"),J=L(W,"url"),w=L(W,"filePath");if(J===void 0===(w===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let Y;if(w!==void 0){let b=await eH(w,X);Y={url:b.url,source:"upload",fileName:L(W,"fileName")??b.fileName,fileSizeBytes:b.fileSizeBytes,mimeType:b.mimeType}}else{Y={url:J};let b=L(W,"fileName");if(b)Y.fileName=b}Q=await D("PUT",`/api/v1/products/${encodeURIComponent(G)}/delivery`,Y,X);break}case"remove_product_file":{let X=W.companyId,G=A("remove_product_file",W,"productId");Q=await D("DELETE",`/api/v1/products/${encodeURIComponent(G)}/delivery`,void 0,X);break}case"sync_products":{let X=W.companyId,G=new URLSearchParams;if(typeof W.integrationId==="string"&&W.integrationId)G.set("integrationId",W.integrationId);let J=G.toString();Q=await D("POST",`/api/v1/products/sync${J?`?${J}`:""}`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function UM($){let W=L($,"campaignId"),Q=L($,"sequenceId"),X=L($,"templateId"),G=[W,Q,X].filter((J)=>J!==void 0);if(G.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(G.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(W!==void 0)return`/api/v1/campaigns/${encodeURIComponent(W)}/render`;if(Q!==void 0){let J=A("render_email",$,"nodeId");return`/api/v1/sequences/${encodeURIComponent(Q)}/nodes/${encodeURIComponent(J)}/render`}return`/api/v1/templates/${encodeURIComponent(X)}/render`}var BM=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function Wz($,W){if($!=="render_email")return{handled:!1,result:void 0};let Q=UM(W),X={};for(let J of BM)if(W[J]!==void 0)X[J]=W[J];return{handled:!0,result:await D("POST",Q,X,L(W,"companyId"))}}var Qz=80,Xz=10;function LM($){if(!Array.isArray($.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if($.recipients.length>Xz)throw Error(`\`recipients\` must include no more than ${Xz} email addresses when calling \`send_sequence_test_email\`.`);if($.recipients.find((G)=>typeof G!=="string"||G.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let Q=Array.from(new Set($.recipients.map((G)=>typeof G==="string"?G.trim().toLowerCase():""))).filter(Boolean);if(Q.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let X=Q.find((G)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(G));if(X)throw Error(`Invalid test recipient email address: \`${X}\`.`);return Q}function AM($){let W=$.trim().replace(/\s+/g," ");if(W.length<=Qz)return W;return`${W.slice(0,Qz-3).trimEnd()}...`}async function MQ($,W){let Q;switch($){case"generate_sequence":{let X=A("generate_sequence",W,"goal"),G=typeof W.name==="string"&&W.name.trim().length>0?W.name.trim():void 0,w=(await MQ("create_sequence",{...W,goal:X,name:G??AM(X),trigger:"contact_added",durationDays:W.durationDays??14})).result;return{handled:!0,result:typeof w==="object"&&w!==null?{...w,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:w}}case"list_sequences":{let X=W.companyId,G=new URLSearchParams;for(let w of["status","search","limit","offset"])if(W[w]!==void 0)G.set(w,String(W[w]));if(Array.isArray(W.labels)&&W.labels.length>0)G.set("labels",W.labels.join(","));let J=G.size>0?`?${G.toString()}`:"";Q=await D("GET",`/api/v1/sequences${J}`,void 0,X);break}case"get_sequence":{let X=W.companyId;Q=await D("GET",`/api/v1/sequences/${W.sequenceId}`,void 0,X);break}case"list_sequence_enrollments":{let X=W.companyId,G=A($,W,"sequenceId"),J=new URLSearchParams;for(let Y of["currentNodeId","status","subscriberId"]){let b=W[Y];if(Array.isArray(b)){if(b.length>0)J.set(Y,b.join(","))}else if(b!==void 0)J.set(Y,String(b))}for(let Y of["email","sort","limit","offset"])if(W[Y]!==void 0)J.set(Y,String(W[Y]));let w=J.size>0?`?${J.toString()}`:"";Q=await D("GET",`/api/v1/sequences/${encodeURIComponent(G)}/enrollments${w}`,void 0,X);break}case"send_sequence_test_email":{let X=W.companyId,G=A($,W,"sequenceId"),J=A($,W,"nodeId"),w=LM(W);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(G)}/nodes/${encodeURIComponent(J)}/test`,{recipients:w},X);break}case"create_sequence":{let X=W.companyId;K1("create_sequence",W),q6("create_sequence",W);let G=Array.isArray(W.steps),J=W.goal===void 0&&W.steps===void 0,w=await D("POST","/api/v1/sequences",W,X);if(!w.success){Q=w;break}let Y=w.sequence.id;if(G||J){let U=await D("GET",`/api/v1/sequences/${Y}`,void 0,X);if(U.success)Q={...w,success:!0,sequence:U.sequence,message:`Sequence "${U.sequence.name}" created ${J?"as a blank draft":"with explicit steps"}. Review it before enabling.${w.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else Q=U;break}let b=7,H=0,z="pending";while(z!=="complete"&&H<b){let U=await D("GET",`/api/v1/sequences/${Y}`,void 0,X);if(U.success)z=U.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<b)await new Promise((B)=>setTimeout(B,20000))}let F=await D("GET",`/api/v1/sequences/${Y}`,void 0,X);if(F.success)Q={...w,success:!0,sequence:F.sequence,message:F.sequence.enrichmentStatus==="complete"?`Sequence "${F.sequence.name}" created with ${F.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${w.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${F.sequence.name}" created. Email enrichment is still in progress (${F.sequence.enrichedCount}/${F.sequence.emailCount} emails generated). You can check status with get_sequence.${w.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else Q=F;break}case"update_sequence":{let X=W.companyId,G=IH(W);Q=await D("PUT",`/api/v1/sequences/${W.sequenceId}`,G,X);break}case"update_sequence_node":{let X=W.companyId,G=A("update_sequence_node",W,"sequenceId"),J=_H(W);Q=await D("PUT",`/api/v1/sequences/${G}`,J,X);break}case"update_sequence_nodes":{let X=W.companyId,G=A("update_sequence_nodes",W,"sequenceId"),J=xH(W);Q=await D("PUT",`/api/v1/sequences/${G}`,J,X);break}case"edit_sequence_graph":{let X=W.companyId,G=hH(W);Q=await D("PUT",`/api/v1/sequences/${W.sequenceId}`,G,X);break}case"insert_sequence_step":{let X=W.companyId,G=yH(W),J=await D("PUT",`/api/v1/sequences/${W.sequenceId}`,G,X);if(typeof J==="object"&&J!==null){let w=J,Y=w.sequence;if(typeof Y==="object"&&Y!==null){let b=Y;Q={...w,...b.insertedNodeIds!==void 0?{insertedNodeIds:b.insertedNodeIds}:{},...b.insertedEmailIds!==void 0?{insertedEmailIds:b.insertedEmailIds}:{},...b.insertedEmailCount!==void 0?{insertedEmailCount:b.insertedEmailCount}:{},...b.addedBranchNodeId!==void 0?{addedBranchNodeId:b.addedBranchNodeId}:{},...b.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:b.addedBranchPathNodeIds}:{}};break}}Q=J;break}case"enable_sequence":{let X=W.companyId;Q=await D("POST",`/api/v1/sequences/${W.sequenceId}/enable`,void 0,X);break}case"disable_sequence":{let X=W.companyId;Q=await D("POST",`/api/v1/sequences/${W.sequenceId}/disable`,void 0,X);break}case"duplicate_sequence":{let X=W.companyId,G=A("duplicate_sequence",W,"sequenceId"),J=L(W,"name");Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(G)}/duplicate`,J===void 0?void 0:{name:J},X);break}case"archive_sequence":case"unarchive_sequence":{let X=W.companyId,G=A($,W,"sequenceId"),J=$==="archive_sequence"?"archive":"unarchive";Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(G)}/${J}`,void 0,X);break}case"list_sequence_goals":{let X=W.companyId,G=A($,W,"sequenceId");Q=await D("GET",`/api/v1/sequences/${encodeURIComponent(G)}/goals`,void 0,X);break}case"create_sequence_goal":case"update_sequence_goal":{let X=W.companyId,G=A($,W,"sequenceId");if($==="create_sequence_goal")A($,W,"name"),NH(W);else EH(W);let J=$==="update_sequence_goal"?A($,W,"goalId"):void 0,w={...W};delete w.companyId,delete w.sequenceId,delete w.goalId,Q=await D($==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(G)}/goals${J?`/${encodeURIComponent(J)}`:""}`,w,X);break}case"delete_sequence_goal":{let X=W.companyId,G=A($,W,"sequenceId"),J=A($,W,"goalId");Q=await D("DELETE",`/api/v1/sequences/${encodeURIComponent(G)}/goals/${encodeURIComponent(J)}`,void 0,X);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let X=W.companyId,G=A($,W,"sequenceId");if(W.clearFieldMapping===!0&&W.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(W.clearSamplePayload===!0&&W.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let J=$==="configure_sequence_inbound_webhook",w=$==="rotate_sequence_inbound_webhook_secret",Y=J?{...W.clearFieldMapping===!0?{fieldMapping:null}:W.fieldMapping!==void 0?{fieldMapping:W.fieldMapping}:{},...W.clearSamplePayload===!0?{samplePayload:null}:W.samplePayload!==void 0?{samplePayload:W.samplePayload}:{}}:void 0;Q=await D(w?"POST":J?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(G)}/inbound-webhook${w?"/rotate-secret":""}`,Y,X);break}case"pause_sequence_enrollments":{let X=W.companyId;Q=await D("POST",`/api/v1/sequences/${W.sequenceId}/pause-enrollments`,void 0,X);break}case"resume_sequence_enrollments":{let X=W.companyId;Q=await D("POST",`/api/v1/sequences/${W.sequenceId}/resume-enrollments`,void 0,X);break}case"enroll_subscribers_in_sequence":{let X=W.companyId,G=A("enroll_subscribers_in_sequence",W,"sequenceId"),J=aH(W);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(G)}/enroll`,J,X);break}case"cancel_sequence_enrollments":{let X=W.companyId,G=uH(W);Q=await D("POST",`/api/v1/sequences/${W.sequenceId}/enrollments/cancel`,G,X);break}case"move_sequence_enrollments":{let X=W.companyId,G=A("move_sequence_enrollments",W,"sequenceId"),J=cH(W);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(G)}/enrollments/move`,J,X);break}case"realign_sequence_enrollments":{let X=W.companyId,G=A("realign_sequence_enrollments",W,"sequenceId"),J=fH(W);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(G)}/enrollments/realign-sending-window`,J,X);break}case"get_sequence_enrollment_realignment":{let X=W.companyId,G=A($,W,"sequenceId"),J=A($,W,"jobId");Q=await D("GET",`/api/v1/sequences/${encodeURIComponent(G)}/enrollments/realign-sending-window/jobs/${encodeURIComponent(J)}`,void 0,X);break}case"delete_sequence":{let X=W.companyId;Q=await D("DELETE",`/api/v1/sequences/${W.sequenceId}`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function Z$($,W,Q){let X=W[Q];if(X===void 0)return;if(!Array.isArray(X))throw Error(`\`${Q}\` must be an array of strings when calling \`${$}\`.`);let G=X.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter((J)=>J.length>0);if(G.length!==X.length)throw Error(`\`${Q}\` must contain only non-empty strings when calling \`${$}\`.`);return G}function OM($,W){let Q=Z$($,W,"tags");if(Q===void 0||Q.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${$}\`.`);let X=Z$($,W,"emails"),G=Z$($,W,"externalIds"),J=Z$($,W,"subscriberIds");if((X?.length??0)+(G?.length??0)+(J?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${$}\`.`);return{tags:Q,...X?.length?{emails:X}:{},...G?.length?{externalIds:G}:{},...J?.length?{subscriberIds:J}:{},...$==="bulk_add_subscriber_tags"&&typeof W.triggerAutomations==="boolean"?{triggerAutomations:W.triggerAutomations}:{}}}async function Gz($,W){let Q;switch($){case"add_subscriber":{let X=W.companyId,G=typeof W.phone==="string"&&W.phone.trim()!==""?W.phone.trim():void 0,J=G?DQ(W):$1("add_subscriber",W),w=u("add_subscriber",W,"status",["active","unsubscribed","bounced"]),Y=u("add_subscriber",W,"optInMode",["default","confirmed","double_opt_in"]);if(Q=await D("POST","/api/v1/subscribers",{...J,...G!==void 0&&{phone:G},...typeof W.phoneCountry==="string"&&W.phoneCountry.trim()!==""&&{phoneCountry:W.phoneCountry.trim()},...typeof W.smsConsent==="boolean"&&{smsConsent:W.smsConsent},...W.firstName!==void 0&&{firstName:W.firstName},...W.lastName!==void 0&&{lastName:W.lastName},customAttributes:W.attributes,tags:W.tags,lists:W.listIds,...w!==void 0&&{status:w},...Y!==void 0&&{optInMode:Y},...W.createdAt!==void 0&&{createdAt:W.createdAt}},X),w!==void 0&&h(Q)&&h(Q.subscriber)&&Q.subscriber.skipped===!0&&Q.subscriber.status!==w)throw Error(`Existing subscriber was not changed to status '${w}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let X=W.companyId;if(!Array.isArray(W.subscribers)||W.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(W.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let w=0;w<W.subscribers.length;w+=1){let Y=W.subscribers[w],b=h(Y)&&typeof Y.email==="string"&&Y.email.trim()!=="",H=h(Y)&&typeof Y.phone==="string"&&Y.phone.trim()!=="";if(!b&&!H)throw Error(`Subscriber record ${w} must include an email or a phone number.`)}let G=u("create_subscriber_import",W,"duplicateStrategy",["skip","merge","overwrite"]),J=u("create_subscriber_import",W,"optInMode",["default","confirmed","double_opt_in"]);Q=await D("POST","/api/v1/subscribers/imports",{subscribers:W.subscribers,...G!==void 0&&{duplicateStrategy:G},...W.fileName!==void 0&&{fileName:W.fileName},...W.listIds!==void 0&&{listIds:W.listIds},...W.enrollInSequences!==void 0&&{enrollInSequences:W.enrollInSequences},...W.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:W.defaultPhoneCountry},...W.smsConsent!==void 0&&{smsConsent:W.smsConsent},...J!==void 0&&{optInMode:J}},X);break}case"get_subscriber_import":{let X=W.companyId,G=A("get_subscriber_import",W,"importId");Q=await D("GET",`/api/v1/subscribers/imports/${encodeURIComponent(G)}`,void 0,X);break}case"update_subscriber":{let X=W.companyId,G=$1("update_subscriber",W),J=u("update_subscriber",W,"status",["active","unsubscribed","bounced"]),Y=h(W.attributes)||W.addTags!==void 0||W.removeTags!==void 0?await S4(G,X):null,b=Array.isArray(Y?.subscriber.tags)?Y.subscriber.tags.filter((B)=>typeof B==="string"):[],H=Array.isArray(W.addTags)?W.addTags.filter((B)=>typeof B==="string"&&B.trim()!=="").map(zQ):[],z=new Set(Array.isArray(W.removeTags)?W.removeTags.filter((B)=>typeof B==="string"&&B.trim()!=="").map(zQ):[]),F=b.filter((B)=>!z.has(B));for(let B of H)if(!F.includes(B))F.push(B);let U={};if(G.email&&G.externalId)U.externalId=G.externalId;if(W.firstName!==void 0)U.firstName=W.firstName;if(W.lastName!==void 0)U.lastName=W.lastName;if(typeof W.phone==="string"||W.phone===null)U.phone=W.phone;if(typeof W.phoneCountry==="string")U.phoneCountry=W.phoneCountry;if(typeof W.smsConsent==="boolean")U.smsConsent=W.smsConsent;if(J!==void 0)U.status=J;if(h(W.attributes))U.customAttributes={...h(Y?.subscriber.customAttributes)?Y.subscriber.customAttributes:{},...W.attributes};if(W.addTags||W.removeTags)U.tags=F;Q=await D("PATCH",U$(G),U,X);break}case"remove_subscriber":{let X=W.companyId,G=$1("remove_subscriber",W),J=U$(G);if(W.hardDelete===!0)Q=await D("DELETE",J,void 0,X);else Q=await D("PATCH",J,{status:"unsubscribed"},X);break}case"get_subscriber":{let X=W.companyId,G=$1("get_subscriber",W);Q=await S4(G,X,{includeMachineEngagement:W.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let X=W.companyId,G=$1("list_subscriber_notes",W);Q=await D("GET",FQ(G),void 0,X);break}case"add_subscriber_note":{let X=W.companyId,G=$1("add_subscriber_note",W),J=typeof W.body==="string"?W.body.trim():void 0;if(!J)throw Error("`body` is required when calling `add_subscriber_note`.");if(J.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");Q=await D("POST",FQ(G),{body:J},X);break}case"delete_subscriber_note":{let X=W.companyId,G=typeof W.noteId==="string"?W.noteId.trim():"";if(!G)throw Error("`noteId` is required when calling `delete_subscriber_note`.");Q=await D("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(G)}`,void 0,X);break}case"trigger_subscriber_event":{let X=W.companyId,G=$1("trigger_subscriber_event",W),J=A("trigger_subscriber_event",W,"event");if(W.properties!==void 0&&!h(W.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");Q=await D("POST","/api/v1/subscribers/events",{...G,event:J,...W.properties!==void 0&&{properties:W.properties},...W.firstName!==void 0&&{firstName:W.firstName},...W.lastName!==void 0&&{lastName:W.lastName},...W.attributes!==void 0&&{customAttributes:W.attributes},...W.occurredAt!==void 0&&{occurredAt:W.occurredAt},...W.eventId!==void 0&&{eventId:W.eventId}},X);break}case"trigger_subscriber_events":{let X=W.companyId,G=$1("trigger_subscriber_events",W);if(!Array.isArray(W.events)||W.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(W.events.length>500)throw Error("`trigger_subscriber_events` accepts at most 500 events per call. Split a larger history import into several calls.");for(let J=0;J<W.events.length;J+=1){let w=W.events[J];if(!h(w)||typeof w.name!=="string"||w.name.trim()==="")throw Error(`Event ${J} must include a non-empty \`name\` string.`)}Q=await D("POST","/api/v1/subscribers/events/bulk",{...G,events:W.events,...W.firstName!==void 0&&{firstName:W.firstName},...W.lastName!==void 0&&{lastName:W.lastName},...W.attributes!==void 0&&{customAttributes:W.attributes}},X);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let X=W.companyId,G=OM($,W);Q=await D("POST",`/api/v1/subscribers/bulk/tags/${$==="bulk_add_subscriber_tags"?"add":"remove"}`,G,X);break}case"search_subscribers":{let X=W.companyId;Q=await tH(W,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function Jz($,W){if($!=="get_recipient_suppression"&&$!=="remove_recipient_suppression")return{handled:!1,result:void 0};let Q=L(W,"companyId"),X=A($,W,"email"),G=L(W,"region"),J=new URLSearchParams;if(G)J.set("region",G);let w=`/api/v1/suppressions/${encodeURIComponent(X)}${J.size>0?`?${J}`:""}`;return{handled:!0,result:await D($==="get_recipient_suppression"?"GET":"DELETE",w,void 0,Q)}}async function wz($,W){let Q;switch($){case"list_team_members":{let X=W.companyId;Q=await D("GET","/api/v1/team",void 0,X);break}case"invite_team_member":{let X=W.companyId,G=A("invite_team_member",W,"email"),J=C4("invite_team_member",W,"role",["admin","viewer","restricted"]);if(W.canManageBilling!==void 0&&typeof W.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");Q=await D("POST","/api/v1/team/invitations",{email:G,role:J,...W.canManageBilling!==void 0&&{canManageBilling:W.canManageBilling}},X);break}case"cancel_team_invitation":{let X=W.companyId,G=A("cancel_team_invitation",W,"invitationId");Q=await D("DELETE",`/api/v1/team/invitations/${encodeURIComponent(G)}`,void 0,X);break}case"list_conversations":{let X=W.companyId,G=new URLSearchParams,J=u("list_conversations",W,"status",["open","closed","all"]);if(J)G.set("status",J);let w=L(W,"search");if(w)G.set("search",w);if(W.unread!==void 0){if(typeof W.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(W.unread)G.set("unread","true")}if(W.page!==void 0){if(typeof W.page!=="number"||!Number.isInteger(W.page)||W.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");G.set("page",String(W.page))}let Y=X0("list_conversations",W,"limit",1,100);if(Y!==void 0)G.set("limit",String(Y));Q=await D("GET",`/api/v1/conversations${G.size>0?`?${G}`:""}`,void 0,X);break}case"get_conversation":{let X=W.companyId,G=A("get_conversation",W,"conversationId");Q=await D("GET",`/api/v1/conversations/${encodeURIComponent(G)}`,void 0,X);break}case"reply_to_conversation":{let X=W.companyId,G=A("reply_to_conversation",W,"conversationId"),J=u("reply_to_conversation",W,"type",["outbound","note"])??"outbound",w=L(W,"subject"),Y=L(W,"bodyText"),b=L(W,"bodyHtml");if(J==="outbound"&&Y===void 0&&b===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");Q=await D("POST",`/api/v1/conversations/${encodeURIComponent(G)}/messages`,{type:J,...w!==void 0&&{subject:w},...Y!==void 0&&{bodyText:Y},...b!==void 0&&{bodyHtml:b}},X);break}case"update_conversation_status":{let X=W.companyId,G=A("update_conversation_status",W,"conversationId"),J=C4("update_conversation_status",W,"status",["open","closed"]);Q=await D("POST",`/api/v1/conversations/${encodeURIComponent(G)}/status`,{status:J},X);break}case"mark_conversation_read":{let X=W.companyId,G=A("mark_conversation_read",W,"conversationId");Q=await D("POST",`/api/v1/conversations/${encodeURIComponent(G)}/read`,void 0,X);break}case"list_webhooks":{let X=W.companyId;Q=await D("GET","/api/v1/webhooks",void 0,X);break}case"create_webhook":{let X=W.companyId,G=A("create_webhook",W,"name"),J=A("create_webhook",W,"url"),w=BQ("create_webhook",W);Q=await D("POST","/api/v1/webhooks",{name:G,url:J,...w!==void 0&&{events:w}},X);break}case"update_webhook":{let X=W.companyId,G=A("update_webhook",W,"webhookId"),J=L(W,"name"),w=L(W,"url"),Y=BQ("update_webhook",W),b=u("update_webhook",W,"status",["enabled","disabled"]);if(J===void 0&&w===void 0&&Y===void 0&&b===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");Q=await D("PATCH",`/api/v1/webhooks/${encodeURIComponent(G)}`,{...J!==void 0&&{name:J},...w!==void 0&&{url:w},...Y!==void 0&&{events:Y},...b!==void 0&&{status:b}},X);break}case"delete_webhook":{let X=W.companyId,G=A("delete_webhook",W,"webhookId");Q=await D("DELETE",`/api/v1/webhooks/${encodeURIComponent(G)}`,void 0,X);break}case"test_webhook":{let X=W.companyId,G=A("test_webhook",W,"webhookId");Q=await D("POST",`/api/v1/webhooks/${encodeURIComponent(G)}/test`,void 0,X);break}case"list_webhook_deliveries":{let X=W.companyId,G=A("list_webhook_deliveries",W,"webhookId"),J=X0("list_webhook_deliveries",W,"limit",1,100),w=new URLSearchParams;if(J!==void 0)w.set("limit",String(J));Q=await D("GET",`/api/v1/webhooks/${encodeURIComponent(G)}/deliveries${w.size>0?`?${w}`:""}`,void 0,X);break}case"replay_webhook_delivery":{let X=W.companyId,G=A("replay_webhook_delivery",W,"webhookId"),J=A("replay_webhook_delivery",W,"deliveryId");Q=await D("POST",`/api/v1/webhooks/${encodeURIComponent(G)}/deliveries/${encodeURIComponent(J)}/replay`,void 0,X);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}var Yz=[m3,r3,d3,Gz,Jz,$z,p3,i3,n3,Wz,o3,e3,s3,t3,MQ,g3,wz,l3];var KM=new Set(["create_campaign","update_campaign","create_template","update_template","set_template_localization","create_transactional_email","update_transactional_email","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","insert_sequence_step","update_ab_test_variant","create_ab_test"]);function bz($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function qQ($){if(Array.isArray($))return $.some(qQ);if(!bz($))return!1;for(let[W,Q]of Object.entries($)){if((W==="html"||W==="htmlContent")&&typeof Q==="string"&&Q.trim().length>0)return!0;if(qQ(Q))return!0}return!1}function Hz($,W,Q){if(!KM.has($)||!qQ(W)||!bz(Q))return Q;let X=Array.isArray(Q.warnings)?Q.warnings.filter((G)=>typeof G==="string"):[];return{...Q,warnings:[...new Set([...X,cW])]}}var P$="Ordinary searches are ordered newest-created first; attribute-filtered searches are ordered by subscriber ID ascending. Sort the returned array yourself if you need another order.",ZM={search_subscribers:{filters:"Use the tags, list/listId/listName, status, and attribute arguments for single conditions, or create_segment plus segmentId for compound, OR, engagement, or event conditions.",filterJoinOperator:"The supported arguments always combine with AND. Use create_segment plus segmentId for OR logic.",sortBy:P$,sortOrder:P$,sort:P$,order:P$,attributes:'Filter on one attribute at a time with attribute: "attributeName:value".',customAttributes:'Filter on one attribute at a time with attribute: "attributeName:value".',page:"Omit limit to fetch every page automatically, or set limit to cap the result size.",offset:"Omit limit to fetch every page automatically, or set limit to cap the result size.",cursor:"Omit limit to fetch every page automatically, or set limit to cap the result size."}},zz=null;function PM($){return zz??=new Map(O$.map((W)=>{let Q=W.inputSchema.properties;return[W.name,new Set(Q&&typeof Q==="object"?Object.keys(Q):[])]})),zz.get($)??null}function Dz($,W){let Q=PM($);if(!Q)return;let X=Object.keys(W??{}).filter((Y)=>!Q.has(Y));if(X.length===0)return;let G=ZM[$]??{},J=[...new Set(X.flatMap((Y)=>G[Y]?[G[Y]]:[]))],w=Q.size>0?`Supported arguments: ${[...Q].map((Y)=>`\`${Y}\``).join(", ")}.`:`\`${$}\` takes no arguments.`;throw Error([`Unsupported field${X.length===1?"":"s"}: ${X.map((Y)=>`\`${Y}\``).join(", ")}.`,`\`${$}\` rejects arguments it does not support rather than ignoring them, because ignoring them would return a result that silently does not match the request.`,w,...J].join(" "))}var Fz=O$.map(H3).map(LH);async function Uz($,W){try{Dz($,W);let Q,X=!1;for(let J of Yz){let w=await J($,W);if(w.handled){Q=w.result,X=!0;break}}if(!X)throw Error(`Unknown tool: ${$}`);let G=nH(Q);if(G)throw G;return Q=Hz($,W,Q),Q=await W3($,W,Q),{structuredContent:z3(Q),content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}catch(Q){return{isError:!0,content:[{type:"text",text:V1(Q)}]}}}async function Bz($,W,Q){let X=W.getRequestContext?.($)??{};try{return await j$(X,Q)}finally{await W.onRequestContextUpdated?.(X,$)}}function IQ($={}){let W=new _W({name:"sequenzy",version:HH.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. When a tool call produced a wrong or unexpected result, include userIntent, toolCalls, expected, actual, and resourceIds in the submission so the team can reproduce it. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
|
|
58
|
-
`)});return
|
|
59
|
-
`);if(
|
|
60
|
-
`}class EQ{constructor(
|
|
57
|
+
Before protected server-side API work, use create_api_key and save the key to .env as SEQUENZY_API_KEY. Static-site saved forms are the exception: use list_forms/create_form/get_form_embed and never place a secret key in browser code.`,inputSchema:{type:"object",properties:{framework:{type:"string",description:"Framework/language (nextjs, express, python, etc.)"},use_case:{type:"string",description:"Use case: 'transactional' (sending emails), 'subscribe_form' (adding subscribers), 'event_tracking' (tracking CUSTOM events only - payment events should come from Stripe/Polar/etc integration), 'ecommerce' (connecting a custom e-commerce platform via the Commerce API)"}}}}];var U3=[{name:"generate_email",description:"Generate email blocks from a prompt. Generated blocks include the company's branding chrome (logo, footer with company name/address/unsubscribe) by default, matching emails created in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the email to generate"},style:{type:"string",description:"Style: minimal, branded, promotional"},tone:{type:"string",description:"Tone: professional, casual, friendly"},applyBranding:{type:"boolean",description:"Wrap the generated content with company branding (logo + footer). Defaults to true; set false to get raw content blocks only."},emailType:{type:"string",enum:["marketing","transactional"],description:"Email type. Transactional emails get a footer without the unsubscribe link. Defaults to marketing."}},required:["prompt"]}},{name:"generate_sequence",description:"[DEPRECATED compatibility alias - use create_sequence] Create and persist a disabled AI-generated email sequence draft from a goal. The saved draft appears in list_sequences. The name defaults to the goal and the trigger defaults to contact_added; optionally pass listId to scope it. Review before enabling.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},goal:{type:"string",description:"Goal of the sequence (e.g., 'onboard new SaaS trial users')"},name:{type:"string",description:"Optional sequence name. Defaults to the goal."},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days (default: 14)"},listId:{type:"string",description:"Optional list ID. When provided, only contacts added to this list trigger the sequence."}},required:["goal"]}},{name:"generate_subject_lines",description:"Generate A/B test subject line variants",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},topic:{type:"string",description:"Topic or context for the subject lines"},count:{type:"number",description:"Number of variants to generate (default: 5)"}},required:["topic"]}},{name:"generate_sms",description:"Generate SMS marketing message variants from a prompt. Returns plain-text messages with per-message encoding and segment counts. Use the results as the 'text' of an SMS sequence step (insert_sequence_step with type 'sms' or a create_sequence sms step). Messages exclude opt-out footers and brand prefixes - the platform adds those automatically at send time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},prompt:{type:"string",description:"Description of the SMS to generate (e.g., 'cart reminder with a free-shipping hook')"},count:{type:"number",description:"Number of message variants to generate (default: 3, max: 10)"}},required:["prompt"]}},{name:"get_sms_settings",description:"Get the company's SMS add-on status: whether SMS is enabled, plan eligibility, credit balance, brand prefix, phone numbers, and whether SMS steps will actually send. Check this before adding SMS steps to sequences so you can warn the user when SMS is not ready.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_sms_number_label",description:"Update one SMS number's settings: the user-facing label and/or its brand prefix override. Use get_sms_settings to find the number ID. Omitted fields keep their value; pass an empty string to clear one. Requires workspace-management permission.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},numberId:{type:"string",description:"SMS number ID returned by get_sms_settings."},label:{type:"string",description:"Label up to 100 characters, such as Marketing or Support. Pass an empty string to clear it."},brandPrefix:{type:"string",description:'Per-number brand prefix override up to 100 characters; messages go out as "{prefix}: your message". Pass an empty string to clear it back to the account-wide prefix.'}},required:["numberId"]}},{name:"send_test_sms",description:"Send a test SMS to a phone number. IMPORTANT: sends a real text message and charges SMS credits - only call when the user explicitly asks for a test send. Requires the SMS add-on with a verified number (check get_sms_settings). Limited to 5 test sends per hour; bypasses quiet hours; excluded from step stats.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Destination phone number in international E.164 format, e.g. +15550100123."},text:{type:"string",description:"Plain-text message body. Merge tags are not resolved for test sends to arbitrary numbers. Provide text or blocks."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable image URLs sent as MMS media (US/CA only)."},blocks:{type:"array",items:{type:"object"},description:"SMS content blocks (text + image subset). Provide text or blocks, not both."}},required:["to"]}}];var L3=[{name:"get_stats",description:"Get overview statistics for a time period, including reply count and reply rate. Counts form a funnel over the sends made inside the period: opened and clicked are unique per email send (not total open events) and include engagement that arrives after the period ends, so they never exceed sent. Rates divide by rateDenominator (delivered, falling back to sent), reported alongside rateDenominatorBasis. Set emailType to transactional for Send API and transactional SMTP open/click rates, including both direct and saved-template sends. When no emailType filter is used and a background-computed snapshot is available, the response also includes a top-level commerceForecast with predicted AOV, 12-month customer value, 90-day revenue, confidence, and data-eligibility reasons.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},period:{type:"string",description:"Time period: 7d, 30d, or 90d (default: 7d)"},emailType:{type:"string",description:"Optional structural email type filter: campaign, transactional, or sequence. Use transactional for Send API and transactional SMTP traffic."},includeMachineEngagement:h0}}},{name:"get_transactional_stats",description:"Get aggregate sends, deliveries, bounces, opens, clicks, and rates for one saved transactional email selected by ID or slug. Results are all-time by default; pass period or start/end for a window. For direct-content Send API messages, use get_stats with emailType transactional and list_email_sends/get_email_send for delivery-level detail.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Saved transactional email ID or API slug."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:h0},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), product recommendation funnel metrics, a per-link click breakdown in the top-level clickedLinks array, and any Poll or NPS survey summaries in the top-level polls array",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},period:{type:"string",description:"Time period: 1h, 24h, 7d, 30d, or 90d"},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too"},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too"},includeMachineEngagement:h0},required:["campaignId"]}},{name:"list_poll_responses",description:"List individual Poll and NPS responses for a campaign, newest answer first, with each respondent's email, their answer and stored value, the subscriber attribute the answer was saved to, and the response time. get_campaign_stats reports the totals; this reports who answered what and when. Only each subscriber's latest answer per poll block is returned, so the counts match the campaign stats summary. Do not reconstruct respondents by scanning subscribers for the poll attribute - the attribute carries no response time and reflects the latest answer to any email. Multi-select answers list every selected option in answers/values. Results are paginated: read the returned pagination object and keep paging with page while page < totalPages.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID. For a sequence email step, pass the step's automation node ID."},blockId:{type:"string",description:"Restrict to one poll block. Block IDs come from the polls array of get_campaign_stats. Omit to return every poll block in the email."},page:{type:"number",description:"1-based page number. Defaults to 1."},limit:{type:"number",description:"Page size. Defaults to 100 and is capped at 500 by the server."}},required:["campaignId"]}},{name:"get_sequence_stats",description:"Get statistics for a sequence. The steps array is the per-step breakdown: one entry per email step in graph order with its step number, automation nodeId, subject, and its own sent, delivered, bounced, opened, clicked, replies, and unsubscribed counts plus rates - so this is where you read how many of Email 4 went out, without reconstructing anything from list_sequence_events. Step counts come from the retained event stream, not the 14-day delivery history behind list_email_sends, so they stay answerable for old sends. Also returns the aggregate funnel across every step, attributed conversions and revenue (revenueCents), product recommendation funnel metrics, per-step failed subscribers and failure reasons, and enrollmentSkipped counts for trigger matches where the contact could not be enrolled (unsubscribed/bounced). Pass period or start/end to use one explicit window for every historical metric; without them, step and aggregate counts are all-time and enrollmentSkipped defaults to the last 30 days. The enrollmentCounts field is a live snapshot of active and waiting enrollments grouped by current node, so it is not limited by period or start/end. To compare the same step across many sequences in one call, use list_email_metrics instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days."},includeMachineEngagement:h0},required:["sequenceId"]}},{name:"list_campaign_events",description:"List paginated raw email events for a campaign. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},eventType:{type:"string",description:`Optional single event type. Supported values: ${E4}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${E4}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:h0},required:["campaignId"]}},{name:"list_sequence_events",description:"List paginated raw email events for every email step in a sequence, or for one step via automationNodeId. Defaults to deliveries; use eventType or eventTypes to include opens, clicks, bounces, complaints, unsubscribes, sends, or delivery delays. This is the per-recipient event stream - do not page it to count sends. Per-step and per-sequence totals already exist as get_sequence_stats steps[], and list_email_metrics gives the same per-step totals across many sequences at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},automationNodeId:{type:"string",description:"Optional email step to scope the stream to, taken from get_sequence_stats steps[].nodeId or get_sequence nodes. Must be an email step of this sequence. Defaults to every email step."},eventType:{type:"string",description:`Optional single event type. Supported values: ${E4}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${E4}. Defaults to delivery.`,items:{type:"string"}},period:{type:"string",description:"Optional sliding time window: 1h, 24h, 7d, 30d, or 90d. Ignored when start/end are provided."},start:{type:"string",description:"Optional ISO 8601 start time. Must be used with end; max range is 90 days."},end:{type:"string",description:"Optional ISO 8601 end time. Must be used with start; max range is 90 days."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Events per page. Defaults to 100; maximum 500."},includeMachineEngagement:h0},required:["sequenceId"]}},{name:"list_email_metrics",description:"List per-email metrics across the account: one row per campaign and per sequence email step, each with its own delivery funnel, attributed conversions, and revenueCents. This is the tool for cross-sequence questions - 'how many Email 4s went out across these sequences' is one call with step=4 plus the returned totals, instead of one get_sequence_stats per sequence. Sequence rows carry sequenceId, sequenceName, automationNodeId, and step, so you can group or compare steps yourself. Counts come from the retained event stream (not the 14-day list_email_sends history) and match get_sequence_stats steps[] for the same step. Filter by emailType, sequenceId, campaignId, and step; sort with sort/order; page with page/limit. totals covers every matching email, not just the current page.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailType:{type:"string",description:"Optional email type: campaign or sequence. Defaults to both. Implied as sequence when sequenceId or step is set."},sequenceId:{type:"array",description:"Optional sequence IDs to restrict the breakdown to. Omit for every sequence in the account. Cannot be combined with campaignId.",items:{type:"string"}},campaignId:{type:"array",description:"Optional campaign IDs to restrict the breakdown to. Cannot be combined with sequenceId, step, or emailType sequence.",items:{type:"string"}},step:{type:"number",description:"Optional 1-based email step position to keep, counted in graph order per sequence. step 4 keeps only the fourth email of each sequence. Sequence emails only."},period:{type:"string",description:"Optional sliding window: 1h, 24h, 7d, 30d, or 90d. Ignored when start and end are provided. Omit for all-time counts."},start:{type:"string",description:"Optional ISO 8601 custom range start. Must be provided with end."},end:{type:"string",description:"Optional ISO 8601 custom range end. Must be provided with start; maximum range is 90 days. Omit start and end for all-time counts over the full retained window."},sort:{type:"string",description:"Sort field: sent, delivered, opened, clicked, openRate, clickRate, unsubscribed, conversions, revenue, step, or name. Defaults to sent."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},page:{type:"number",description:"Page number, starting at 1. Defaults to 1."},limit:{type:"number",description:"Emails per page. Defaults to 50; maximum 500."},includeMachineEngagement:h0}}},{name:"get_subscriber_activity",description:"Get recent activity, email stats, and current sequence enrollments for a subscriber",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:h0},required:[]}}];var B3=[{name:"list_audience_syncs",description:"List Meta custom audience syncs (segment -> ad audience mappings) with their schedule and last sync status. Requires the Meta Ads integration to be connected in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_ad_accounts",description:"List the Meta ad accounts available through the connected Meta Ads integration. Use the returned account id as `adAccountId` when creating an audience sync.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_audience_sync",description:'Push a segment to a Meta custom audience and keep it synced on a schedule. Provide `segmentId` for an existing segment OR `predefinedSegmentId` for a ready-made template (for example "zero-ltv", "no-purchase-1y", "recent-buyers", "high-spenders-ecom", "non-buyers", "engaged") - the template segment is created automatically on first use. The first upload runs immediately. Note: audiences are add-only; subscribers who later leave the segment stay in the Meta audience.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Existing segment ID to sync. Mutually exclusive with `predefinedSegmentId`."},predefinedSegmentId:{type:"string",description:'Predefined segment template ID (for example "zero-ltv", "no-purchase-1y", "recent-buyers"). The segment is created automatically if it does not exist. Mutually exclusive with `segmentId`.'},adAccountId:{type:"string",description:"Meta ad account ID (act_...) from `list_ad_accounts`."},audienceName:{type:"string",description:"Name for the custom audience in Meta Ads Manager."},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"How often to re-upload the segment. Default: daily."}},required:["adAccountId","audienceName"]}},{name:"update_audience_sync",description:"Update an audience sync's frequency or pause/resume it (`isActive`).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID"},frequency:{type:"string",enum:["hourly","daily","weekly"],description:"New sync frequency."},isActive:{type:"boolean",description:"Set false to pause the sync, true to resume it."}},required:["syncId"]}},{name:"delete_audience_sync",description:"Remove an audience sync mapping. The Meta audience itself is kept (running ads are not disrupted) - only future syncs stop.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to remove."}},required:["syncId"]}},{name:"sync_audience_now",description:"Trigger an immediate upload of the segment's subscribers to its Meta custom audience, outside the regular schedule.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},syncId:{type:"string",description:"Audience sync ID to run."}},required:["syncId"]}}];function PQ(W,$){return{type:$?.nullable?["object","null"]:"object",description:W,properties:{type:{type:"string",enum:["all","lists","segment","filtered","rules"],description:"Audience shape. all = every active subscriber; lists = subscribers on any of listIds; segment = one saved segment; filtered = ad-hoc subscriber filters; rules = combined include/exclude rules."},listIds:{type:"array",items:{type:"string"},description:"List IDs to target. Required when type is 'lists'."},segmentId:{type:["string","null"],description:"Saved segment ID. Required when type is 'segment'."},filters:{type:"array",items:{type:"object"},description:"Subscriber filter objects {id, field, operator, value}. Required when type is 'filtered'."},filterJoinOperator:{type:"string",enum:["and","or"],description:"How 'filtered' filters combine. Optional, defaults to 'and'."},include:{type:"array",items:{type:"object"},description:"Include rules. Required when type is 'rules'; at least one is needed to schedule. Each rule is {type:'all'} | {type:'lists', listIds:[...]} | {type:'segments', segmentIds:[...]} | {type:'filtered', filters:[...]}."},exclude:{type:"array",items:{type:"object"},description:"Exclude rules for type 'rules'. Optional. Same shapes as include except {type:'all'}."}},required:["type"],additionalProperties:!0}}var A3=[{name:"list_campaigns",description:"List campaigns. Each item carries `emailPreset`, the linked email's Style > Format (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so chrome can be compared across campaigns without one get_campaign call each. Results are paginated: the default page size is 50 and limit is capped at 100. Always read the returned `pagination` object (`limit`, `offset`, `count`, `total`, `hasMore`) and keep paging with `offset` while `hasMore` is true - a single call does not necessarily return every campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list campaigns for. If not provided, uses the currently selected company."},status:{type:"string",description:"Filter by status (draft, scheduled, sent, sending, cancelled, paused, waiting_approval, or rejected). Rejected campaign results include rejectionComment feedback when provided."},label:{type:"string",description:"Optional label name filter. Only campaigns assigned this label are returned."},limit:{type:"number",description:"Page size from 1 to 100. Defaults to 50."},offset:{type:"number",description:"Zero-based result offset. Defaults to 0."}}}},{name:"get_campaign",description:"Get campaign details and stats, including rejectionComment reviewer feedback for rejected campaigns. `emailId` is the campaign's linked email body - the same record returned by the templates tools - and can be passed as templateId to create_campaign to reuse the design; it is null for SMS campaigns. `emailPreset` reports that email's Style > Format the same way get_sequence does per step (branded or minimal; null for SMS campaigns and standalone raw HTML emails), so campaign chrome can be compared against sequence steps and transactional templates without rendering them - minimal suppresses the company logo at render time. `targetLists` holds the raw audience targeting (IDs only); call get_campaign_audience for resolved list/segment names and a recipient count. Note that `computedLists` is email personalization (product lists rendered inside the email), not audience targeting. For native sends, `sentAt` is stamped when the last recipient is handed off, so on a paced send it is the end of the delivery window; `spreadOverHours`, `sendTimeOptimization`, and `sendTimeWindowHours` report recorded pacing. Imported campaigns may not include pacing metadata from their source provider, so absent pacing fields do not prove that delivery happened all at once.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"get_campaign_audience",description:"Resolve exactly who a campaign will reach. Returns the targeting kind, resolved list and segment names (flagging references that no longer exist), filter conditions, individual include/exclude adjustments, a plain-language summary, and a live recipient count. Critically, it reports whether targeting is unset - an unset campaign falls back to every active subscriber when scheduled. Use this to verify a scheduled campaign's audience before it sends. This is a read-only resolved view, not the write shape: to change targeting, pass `targetLists` (e.g. {type:'lists', listIds:['list_123']}) or the `segmentId`/`listIds` shorthands to update_campaign or schedule_campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"}},required:["campaignId"]}},{name:"share_campaign",description:"Create (or fetch) the campaign's public view-in-browser link. The hosted page renders an anonymized copy - sample contact, inert unsubscribe link, no open/click tracking - so the URL is safe to forward to anyone, unlike a recipient's personal browser copy. Idempotent: if a link is already active, the same URL is returned with created=false rather than rotating it, so previously shared copies keep working. get_campaign reports the current link as shareUrl (null when none). Revoke with unshare_campaign. Email campaigns only - SMS campaigns have no browser view.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to share."}},required:["campaignId"],additionalProperties:!1}},{name:"unshare_campaign",description:"Revoke the campaign's public view-in-browser link. The shared URL returns 404 immediately, and sharing again later mints a different URL - previously distributed copies stay dead. Returns revoked=false if no link was active.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to stop sharing."}},required:["campaignId"],additionalProperties:!1}},{name:"list_email_sends",description:"List and filter the recent sent-email delivery history shown in the dashboard. Search subject/title or recipient, filter by delivery status, email type, bounce type, or source ID, then pass a returned emailSendId to get_email_send for exact open/click timestamps and the complete event timeline. Each row carries recipientEmail, subscriberId, automationNodeId, abTestVariantId, and sent/delivered/opened/clicked timestamps, so rows join into a recipient-level delivery matrix without re-reading the raw event stream. Pass automationNodeId to list only the recipients of one sequence step. Delivery rows are retained for 14 days, so this is the wrong tool for send totals: read get_sequence_stats steps[] or list_email_metrics, which cover the full retained event window.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across subject and recipient email."},subject:{type:"string",description:"Case-insensitive subject/title filter."},recipient:{type:"string",description:"Case-insensitive recipient email filter."},status:{type:"string",description:"Delivery status: pending, sent, delivered, opened, clicked, bounced, complained, failed, or suppressed. Opened includes clicked deliveries, matching the dashboard."},emailType:{type:"string",description:"Email type: campaign, transactional, or sequence."},bounceType:{type:"string",description:"Bounce type: Permanent or Transient."},campaignId:{type:"string",description:"Filter deliveries from one campaign."},transactionalEmailId:{type:"string",description:"Filter deliveries from one saved transactional email."},automationId:{type:"string",description:"Filter deliveries from one sequence/automation."},automationNodeId:{type:"string",description:"Filter deliveries from one email step of a sequence, using the nodeId from get_sequence_stats steps[] or get_sequence nodes."},days:{type:"number",description:"History window in days, from 1 to 14. Defaults to 14."},page:{type:"number",description:"Page number starting at 1. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."},sortField:{type:"string",description:"Sort field: recipientEmail, subject, status, eventAt, sentAt, or createdAt. Defaults to createdAt."},sortOrder:{type:"string",description:"Sort order: asc or desc. Defaults to desc."}}}},{name:"get_email_send",description:"Get an email delivery by emailSendId, including queued and test sends, delivery status, provider failure reason, stored HTML, effective Reply-To, copied-recipient identity and primary email send ID, and the ClickHouse event timeline. `type` is the legacy source category; use `emailType` on the send and `deliveryPolicy` on events for the actual marketing or transactional policy when known. Queue jobs are internal execution details and are not exposed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},emailSendId:{type:"string",description:"Durable email delivery ID to inspect."}},required:["emailSendId"]}},{name:"create_campaign",description:"Create a new campaign. Omit all content fields to create an empty draft. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup. Defaults to draft; status 'sent' only archives an already-sent campaign.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the campaign in. If not provided, uses the currently selected company."},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text. Optional when `prompt` is provided because the generated preview text will be used."},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested."},status:{type:"string",description:"Initial status: draft or sent. Defaults to draft. Use sent only for imported/already-sent campaigns; it does not send email or create delivery history."},sentAt:{type:"string",description:"ISO date-time for an imported/already-sent campaign. Only valid when status is sent; defaults to now if omitted."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},prompt:{type:"string",description:"Generate campaign blocks from a prompt. Generated blocks include the company's logo and footer, and the created campaign inherits the company brand font. Mutually exclusive with `html`, `blocks`, and `templateId`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},templateId:{type:"string",description:"Use a template instead of html"},segmentId:{type:"string",description:"Shorthand for targeting one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists` and `listIds`."},listIds:{type:"array",items:{type:"string"},description:"Shorthand for targeting one or more lists. Equivalent to targetLists {type:'lists', listIds}. Mutually exclusive with `targetLists` and `segmentId`."},targetLists:PQ("Campaign audience, saved on the draft. Omit to leave targeting unset and set it later with `update_campaign` or `schedule_campaign`. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Use this to send straight to a list without creating a segment first. Mutually exclusive with `segmentId` and `listIds`."),fromEmail:{type:"string",description:"From address for this campaign. Its domain must be configured and verified; a sender profile is created when needed."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},replyTo:{type:"string",description:"Reply-To address for this campaign. A reply profile is created when needed."},replyToName:{type:"string",description:t1},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},campaignData:{type:"object",description:"Optional campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Optional computed list definitions derived from campaignData at send time.",items:{type:"object"}},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_campaign",description:"Update a draft campaign",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},name:{type:"string",description:"Campaign name"},subject:{type:"string",description:"Email subject line"},trackingCode:{type:"string",description:"Optional campaign tracking code for UTM templates. Use only when explicitly requested. Send an empty string to clear it."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider campaigns. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},replyTo:{type:"string",description:"Set reply-to using an existing reply profile email address for this company."},replyProfileId:{type:"string",description:"Set reply-to using a reply profile ID for this company (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},replyToName:{type:"string",description:t1},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName."},ccEmails:{type:["array","null"],description:"Addresses CC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},bccEmails:{type:["array","null"],description:"Addresses BCC'd on every recipient's campaign email (max 10). Send an empty array or null to clear them; omit to leave unchanged.",items:{type:"string"},maxItems:10},campaignData:{type:"object",description:"Set campaign-scoped JSON data for repeat blocks and personalization."},computedLists:{type:"array",description:"Set computed list definitions derived from campaignData at send time.",items:{type:"object"}},targetLists:PQ("Replace the draft's saved audience, using the same shapes as `create_campaign`, e.g. {type:'lists', listIds:['list_123']}. Send null to clear it and choose the audience in `schedule_campaign` instead; omit to leave it unchanged. Mutually exclusive with `segmentId` and `listIds`.",{nullable:!0}),segmentId:{type:"string",description:"Shorthand for retargeting the draft at one saved segment. Equivalent to targetLists {type:'segment', segmentId}. Mutually exclusive with `targetLists` and `listIds`."},listIds:{type:"array",items:{type:"string"},description:"Shorthand for retargeting the draft at one or more lists. Equivalent to targetLists {type:'lists', listIds}. Mutually exclusive with `targetLists` and `segmentId`."},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["campaignId"],additionalProperties:!1}},{name:"schedule_campaign",description:"Schedule a draft or already scheduled campaign, as a one-off send or on a repeating weekly/monthly cadence via `recurringInterval`. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Returns dashboard edit and preview URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID"},scheduledAt:{type:"string",description:"Future ISO 8601 timestamp for the send, for example 2026-06-01T14:00:00Z."},targetLists:PQ("Optional campaign targeting object. Omit to use saved targeting - or, when none is saved, ALL active subscribers. Examples: {type:'all'}, {type:'lists', listIds:['list_123']}, {type:'segment', segmentId:'seg_123'}, {type:'filtered', filters:[...], filterJoinOperator:'and'}, or {type:'rules', include:[{type:'lists', listIds:['list_123']}], exclude:[{type:'segments', segmentIds:['seg_123']}]}. Rules audiences require at least one include rule. Mutually exclusive with `listIds`."),listIds:{type:"array",items:{type:"string"},description:"Shorthand for sending to one or more lists. Equivalent to targetLists {type:'lists', listIds}. Mutually exclusive with `targetLists`."},sendTimeOptimization:{type:"boolean",description:"Whether to use send-time optimization."},spreadOverHours:{type:"number",description:"Spread delivery over an integer number of hours from 1 to 72. When set, spread delivery takes precedence over send-time optimization."},recurringInterval:{type:"string",enum:["weekly","monthly"],description:"Repeat this campaign on a cadence starting at scheduledAt. The campaign becomes a recurring template: each run is duplicated and sent automatically, re-evaluating audience membership every time. Omit for a one-shot send; scheduling again without it stops the recurrence."}},required:["campaignId","scheduledAt"],additionalProperties:!1}},{name:"send_test_email",description:"Queue a campaign test email to a single address. Returns a durable emailSendId; pass it to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to test"},to:{type:"string",description:"Email address to send test to"}},required:["campaignId","to"]}},{name:"unschedule_campaign",description:"Return a scheduled campaign to an editable draft. Removes its pending send and recurrence without permanently cancelling it, so it can be edited and scheduled again.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Scheduled campaign ID to return to draft."}},required:["campaignId"],additionalProperties:!1}},{name:"cancel_campaign",description:"Cancel a campaign. Stops scheduled and sending campaigns (also works for paused and approval-pending ones). Remaining emails will not be sent and the campaign cannot be restarted - this cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to cancel."}},required:["campaignId"]}},{name:"pause_campaign",description:"Pause a campaign that is currently sending. Only campaigns in sending status can be paused. Use resume_campaign to continue delivery later.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to pause."}},required:["campaignId"]}},{name:"resume_campaign",description:"Resume a paused campaign. Only campaigns in paused status can be resumed. Optionally spread the remaining delivery over a number of hours.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to resume."},spreadOverHours:{type:"number",description:"Spread the remaining delivery over an integer number of hours from 1 to 72."}},required:["campaignId"]}},{name:"delete_campaign",description:"Permanently delete a campaign. This cannot be undone. Sending, scheduled, or paused campaigns must be cancelled with cancel_campaign first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to delete."}},required:["campaignId"]}},{name:"duplicate_campaign",description:"Duplicate a campaign as a new draft. mode 'campaign' (default) copies the campaign and its email, 'ab_test' also duplicates the campaign's A/B test with all variants, and 'variant' copies a single variant's content as the new campaign email (requires variantId).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to duplicate."},mode:{type:"string",enum:["campaign","ab_test","variant"],description:"Duplication mode. Defaults to campaign."},variantId:{type:"string",description:"A/B test variant ID whose content becomes the new campaign email. Required when mode is variant."}},required:["campaignId"]}},{name:"resend_campaign_to_non_openers",description:"Create a draft that resends a sent campaign to everyone in the same audience who didn't open it. Copies the campaign email and reuses the original audience with a 'didn't open this campaign' rule added. Only available 6 hours after the campaign finishes sending. The draft must be scheduled or sent separately. Returns the new draft and an estimate of how many subscribers haven't opened the original.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"ID of the sent campaign to resend to non-openers."}},required:["campaignId"]}}];var O3=[{name:"get_email_block_schema",description:'Field reference for Sequenzy email blocks: which fields each block type requires, which are optional, the allowed values of every enum field, and the shape of nested item arrays. Call this before authoring blocks for a type you have not written before, or after a block write is rejected. The `blocks` parameter on create_campaign, create_sequence, create_template, and update_sequence_node accepts any of these types, but is declared as a plain object array because the union is too large to inline. Without a blockType this lists every type with its required and optional fields; with one it returns that type\'s full reference plus a minimal valid example and authoring notes. Note that lists are their own block type rather than a text variant: a numbered list is {"type":"list","variant":"numbered","items":[{"content":"First"}]}, and a visual numbered walkthrough is {"type":"steps","variant":"numbered","items":[{"title":"Step one","description":"What happens"},{"title":"Step two","description":"What happens next"}]}. A `text` block only accepts variants paragraph, lead, and html, and never accepts `items`.',inputSchema:{type:"object",properties:{blockType:{type:"string",description:'A single block type to describe, for example "list", "steps", "text", or "hero". Omit to list every block type.'},creatableOnly:{type:"boolean",description:"Only list block types an author should hand-create, hiding structural types that the editor manages. Ignored when blockType is set."}},required:[]}}];var Z3=[{name:"list_email_components",description:"List the company's reusable email components newest first. Components are saved block groups that can be dropped into emails, plus the components pinned as company defaults for a slot (currently `footer`). Pass defaultsOnly to see only the pinned defaults.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},type:{type:"string",enum:["section","footer"],description:"Optional component type filter. `section` is an ordinary saved block group; `footer` is a footer component."},defaultsOnly:{type:"boolean",description:"When true, return only components pinned as a company default for a slot."}}}},{name:"get_email_component",description:"Get one email component's blocks and metadata by id, including its `version` and whether it is pinned as a company default slot.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},componentId:{type:"string",description:"Email component ID"}},required:["componentId"]}},{name:"get_default_email_component",description:"Get the company's default component for a slot - use this to read the current email footer before editing it. Returns not_found when no default is set, which means emails fall back to the footer Sequenzy generates from the company profile.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},slot:{type:"string",enum:["footer"],description:"Default slot to read. Currently only `footer`."}},required:["slot"]}},{name:"set_default_email_component",description:"Create or replace the company's default component for a slot. This is the supported way to change the footer on every email: sequence, campaign, and AI-generated emails built from blocks clone this component when they are built, instead of the generated default footer. Raw HTML emails are the exception - block chrome cannot be injected into raw HTML, so they keep their own markup and a generated unsubscribe footer is appended at send time unless the HTML contains {{unsubscribeUrl}}. Call get_default_email_component first and edit the blocks it returns, otherwise you replace the existing footer wholesale. A default footer always keeps its unsubscribe link enabled - transactional sends hide it at render time. Editing this does not rewrite emails that were already created.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},slot:{type:"string",enum:["footer"],description:"Default slot to write. Currently only `footer`."},blocks:{type:"array",description:`Blocks that make up the default component. ${x0}`,items:{type:"object"}},name:{type:"string",description:"Optional component name. Defaults to `Default Footer` when creating the footer default."},description:{type:"string",description:"Optional human-readable description."}},required:["slot","blocks"]}},{name:"create_email_component",description:"Create a reusable email component from a block list. Component names are unique per company. Use set_default_email_component instead when the goal is to change the footer every email gets.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Component name, unique within the company."},description:{type:"string",description:"Optional human-readable description."},blocks:{type:"array",description:`Blocks that make up the component. ${x0}`,items:{type:"object"}},componentType:{type:"string",enum:["section","footer"],description:"Component type. Defaults to `section`. Creating one with type `footer` does not pin it as the company default - use set_default_email_component for that."}},required:["name","blocks"]}},{name:"update_email_component",description:"Update an email component's metadata or replace its blocks. Replacing blocks bumps the component `version`. Emails that already cloned this component keep the copy they were built with; the new version applies to emails built afterwards. Editing the component pinned as the default footer keeps its unsubscribe link enabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},componentId:{type:"string",description:"Email component ID"},name:{type:"string",description:"New component name, unique within the company."},description:{type:"string",description:"New description. Send an empty string to clear it."},blocks:{type:"array",description:`Replacement blocks for the component. Replaces the whole block list. ${x0}`,items:{type:"object"}},componentType:{type:"string",enum:["section","footer"],description:"New component type."}},required:["componentId"]}},{name:"delete_email_component",description:"Delete an email component. Emails that already rendered it keep their copied blocks, so this does not change existing emails. Deleting the component pinned as the default footer makes new emails fall back to the generated footer.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},componentId:{type:"string",description:"Email component ID"}},required:["componentId"]}}];var K3=[{name:"get_event_schema",description:"Read the published payload of a built-in event: a real example payload per provider, plus every property path with its type, the merge tag that resolves it, and a note wherever the example alone is ambiguous. Call this BEFORE writing {{event.*}} merge tags or event property filters - an unrecognized merge tag renders as an empty string rather than an error, so a guessed property name ships silently broken. It is also the only place that spells out the traps the sample cannot: money fields ending in `Cents` are minor units while `predictedLtv` is whole currency units, `price` is a preformatted display string that must not be parsed, `churnRisk` is a 0-95 percent and not a probability, and `orderId` is a string on Shopify but a number on WooCommerce. Omit eventName to list every documented event, or pass provider to get one provider's payload instead of all of them. Custom events are first-class and deliberately absent from this list: `documented: false` means no sample is published, never that the event name is invalid or will be rejected. Static reference data - it describes the event shape, not what this account has received. Use list_integration_activity or the sequence's own enrollments to see real deliveries.",inputSchema:{type:"object",properties:{eventName:{type:"string",description:"Event to describe, for example `ecommerce.order_placed` or `ecommerce.browse_abandoned`. Legacy aliases such as `order.completed` resolve to their current name. Omit to list every documented event."},provider:{type:"string",description:"Return only this provider's payload. Omit to compare every provider that documents the event.",enum:["shopify","woocommerce","manual","api","stripe"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:[]}}];var P3=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team. IMPORTANT: call this tool whenever the user wanted to accomplish something and Sequenzy did not expose functionality for it - a missing tool or argument, an unsupported workflow, a confusing behavior, or a bug. When something you did through these tools produced a wrong or unexpected result, also fill in userIntent, toolCalls, expected, actual, and resourceIds so the team can reproduce it. Summarize tool arguments instead of pasting raw subscriber data, and never include secrets or API keys. Briefly tell the user you reported the gap. This feedback goes straight to the team and shapes what gets built next. Do not use it for questions about the user's own account or data. Submitting feedback never changes account data.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},message:{type:"string",description:"The feedback itself. Be specific: what was needed, what was missing or wrong, and what you did instead (workaround, gave up, used the dashboard)."},category:{type:"string",enum:["missing_capability","bug","docs","ux","praise","other"],description:"Feedback category. Use missing_capability when the user wanted something these tools do not support, bug when a tool misbehaved or produced a wrong result (default: other)."},context:{type:"string",description:"Optional: what the user was trying to accomplish, in their words, plus any relevant tool names or arguments you tried."},userIntent:{type:"string",description:"For bug/wrong-outcome reports: the user's request, verbatim or closely paraphrased. Omit personal data that is not needed to reproduce the problem."},toolCalls:{type:"array",maxItems:25,description:"For bug/wrong-outcome reports: the ordered tool calls that led to the problem. Summarize arguments - do not paste raw subscriber data or full email bodies.",items:{type:"object",properties:{tool:{type:"string",description:"Tool name, e.g. update_campaign."},args:{type:"string",description:"Short summary of the arguments used."},error:{type:"string",description:"Error message returned by this call, if there was one."}},required:["tool"]}},expected:{type:"string",description:"What you expected to happen."},actual:{type:"string",description:"What actually happened instead."},resourceIds:{type:"array",maxItems:50,items:{type:"string"},description:"IDs of the affected resources (campaign, sequence, subscriber, segment, ...) so the team can correlate with server logs."}},required:["message"]}}];var V3=[{name:"list_forms",description:"List saved signup forms for a company, including their server-managed audience settings and public action URLs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list forms for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"create_form",description:"Create and publish a saved signup form whose opaque formId is a client-safe public capability. The selected lists, tags, duplicate behavior, and success action stay server-side; no API key is needed in the deployed form. This creates the email/name fields only - add typed custom fields (select, textarea, hidden, ...) afterwards with update_form's blocks argument.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the form in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-form name."},listIds:{type:"array",description:"One or more list IDs that every public submission will be added to. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied by the saved form. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},buttonText:{type:"string",description:"Optional submit button label."},headline:{type:"string",description:"Optional form headline."},description:{type:"string",description:"Optional supporting form copy."},successMessage:{type:"string",description:"Confirmation shown after a successful submission when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful submissions. Omit it to show the saved confirmation message."},showFirstName:{type:"boolean",description:"Whether the generated form also collects first name."},showLastName:{type:"boolean",description:"Whether the generated form also collects last name."},theme:{type:"object",description:"Optional visual theme overrides so the form matches the brand instead of the default accent. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0}},required:["name","listIds"],additionalProperties:!1}},{name:"update_form",description:"Update a saved signup form: rename it, retarget its audience, edit its copy, restyle its theme, or replace its content blocks (for example to remove unwanted blocks that render publicly). Read the current content via list_forms first when editing blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."},name:{type:"string",description:"New internal saved-form name."},listIds:{type:"array",description:"Replacement list targeting. Every public submission will be added to these lists.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied by the saved form. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the form's first heading block. Fails if the form has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the form's first paragraph block. Fails if the form has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful submissions. Pass an empty string to switch back to the confirmation message."},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the form's content blocks. Fetch the current blocks from list_forms, modify them, and send the complete array - the form must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute (name must start with a letter and may contain letters, digits, "_", ".", "-"). select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. A hidden field with a defaultValue always stores that server-owned value and ignores whatever the page posts; a hidden field with an empty defaultValue stores the value the page submits. Other kinds and their properties: heading { content, level (1-3), align }, text { content, variant ("paragraph" | "eyebrow" | "caption"), align }, image { src, alt, fit ("cover" | "contain") }, button { text, url, variant, align }, divider {}, spacer { height (8-160) }, custom-html { html, height (40-1200) } - the markup goes in "html", not "content" - feature-grid { features: [{ title, description }], columns }, testimonial { testimonials: [{ quote, name, role }] }, countdown { label, endsAt }, form-step { title, description, blockIds }, submit-button { text, width }, success-screen { heading, message }, error-state { message }. Properties outside a kind's list are rejected rather than dropped, so a typo is reported instead of silently saving an empty block. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["formId"],additionalProperties:!1}},{name:"get_form_embed",description:"Get a published saved form's action URL, one-line JavaScript embed, minimal native form action, and fetch example. Use this for Astro, Hugo, Jekyll, Cloudflare Pages, Netlify, GitHub Pages, or any browser integration.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},formId:{type:"string",description:"Saved form ID returned by list_forms or create_form."}},required:["formId"],additionalProperties:!1}}];var j3=[{name:"upload_image_asset",description:"Upload an image to the selected company's shared media library and return a hosted URL plus a ready-to-insert Sequenzy image block. Call this before create/update campaign, sequence, template, or transactional tools, then place the returned imageBlock in the target blocks array. Provide either filePath (local stdio MCP only) or imageBase64 (works with remote MCP when the client can supply attachment bytes), not both. PNG, JPEG, GIF, and WebP are supported up to 5MB. cropHeight with objectFit:'cover' provides a precise centered screenshot crop while displayWidthPercent keeps the image responsive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},filePath:{type:"string",description:"Local path to a PNG, JPEG, GIF, or WebP image. Available only when the MCP server runs locally. Provide filePath or imageBase64, not both."},imageBase64:{type:"string",description:"Raw base64 image bytes or a base64 data URL. Use this for remote MCP clients that can access attachment bytes. Provide imageBase64 or filePath, not both."},filename:{type:"string",description:"File name including extension. Required with imageBase64; optional override with filePath."},contentType:{type:"string",description:"Image MIME type when it cannot be inferred from filename, such as image/png."},altText:{type:"string",description:"Accessible description stored with the asset and returned as imageBlock.alt. Use an empty string only for a decorative image."},sourceWidth:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source width in pixels. Provide sourceWidth and sourceHeight together when known."},sourceHeight:{type:"integer",minimum:1,maximum:20000,description:"Optional intrinsic source height in pixels. Provide sourceWidth and sourceHeight together when known."},displayWidthPercent:{type:"number",minimum:1,maximum:100,description:"Responsive image width as a percentage of the email content area. Defaults to 100."},cropHeight:{type:"integer",minimum:1,maximum:2000,description:"Optional fixed display height in pixels. With objectFit:'cover', the image is centered and cropped to this height."},objectFit:{type:"string",enum:["cover","contain"],description:"How the image fits cropHeight. Defaults to cover when cropHeight is provided. Only valid with cropHeight."},align:{type:"string",enum:["left","center","right"],description:"Image alignment. Defaults to center."}},additionalProperties:!1}}];var M3=[{name:"list_conversations",description:"List inbox conversations (email replies from subscribers). Filter by status, free-text search, or unread state, with pagination.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},status:{type:"string",enum:["open","closed","all"],description:"Filter by conversation status. Defaults to all."},search:{type:"string",description:"Free-text search across conversation subjects and participants."},unread:{type:"boolean",description:"Set true to only return conversations with unread messages."},page:{type:"number",description:"Page number. Defaults to 1."},limit:{type:"number",description:"Results per page, from 1 to 100. Defaults to 20."}}}},{name:"get_conversation",description:"Get a conversation with its full message history, subscriber details, and context.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}},{name:"reply_to_conversation",description:"Send a reply in a conversation, or add an internal note. type 'outbound' (default) emails the subscriber and requires bodyText or bodyHtml; type 'note' adds a private team-only note. Replying to a closed conversation reopens it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID to reply in."},type:{type:"string",enum:["outbound","note"],description:"Message type: outbound emails the subscriber, note is internal-only. Defaults to outbound."},subject:{type:"string",description:"Optional subject override. Defaults to the conversation subject."},bodyText:{type:"string",description:"Plain-text message body."},bodyHtml:{type:"string",description:"HTML message body."}},required:["conversationId"]}},{name:"update_conversation_status",description:"Open or close a conversation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."},status:{type:"string",enum:["open","closed"],description:"New conversation status."}},required:["conversationId","status"]}},{name:"mark_conversation_read",description:"Mark all unread inbound messages in a conversation as read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},conversationId:{type:"string",description:"Conversation ID."}},required:["conversationId"]}}];var q3=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso. Check list_integration_capabilities first - each connectable provider lists its exact connectFields there. Credentials are validated against the provider where possible, stored encrypted, and never returned; payment providers queue their initial revenue backfill automatically. The response includes the webhookUrl the user must configure at the provider with the same secret - always relay it. Reconnecting an already-connected provider replaces its stored credentials. OAuth and app-install providers (Stripe, Shopify, Supabase, GitHub, WooCommerce, Meta) are rejected with guidance: their flows need a human in the dashboard. SECURITY: only pass credentials the user explicitly provided for this purpose; suggest the CLI (`sequenzy integrations connect`) or dashboard when the user prefers keeping secrets out of the conversation.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider to connect: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, or affonso.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","affonso"]},apiKey:{type:"string",description:"Provider API key. Required for every provider except clerk and posthog."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider. For Chargebee, pass the webhook's basic-auth credentials as username:password."},providerAccountId:{type:"string",description:"Provider account id, required for paddle (seller ID), dodo (business ID), whop (company ID, biz_...), creem (store ID), and chargebee (site name). Polar resolves it from the API key; clerk, posthog, and affonso do not use one."},settings:{type:"object",description:"PostHog only: event delivery scope. Defaults to syncing all non-internal events.",properties:{syncAllEvents:{type:"boolean",description:"Sync every event PostHog delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these PostHog event names. Set syncAllEvents to false when using this."}}},historyImport:{type:"object",description:"PostHog only: import the project's event history after connecting. Needs a personal API key with query read access.",properties:{region:{type:"string",enum:["us","eu"],description:"PostHog Cloud region hosting the project."},projectId:{type:"string",description:"Numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog personal API key (phx_...)."}},required:["region","projectId","personalApiKey"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider","webhookSecret"]}},{name:"get_integration",description:"Inspect one connected integration in depth: what the provider syncs, every event it can emit and when, every matching tag rule, which sequences trigger on those events, recent integration-specific activity, and prioritized recommendations. `observedByAccount` and `accountLastSeenAt` are account-wide because event definitions can also be updated by another integration or the public events API; use the retained activity log for connection-specific delivery diagnosis. Read-only; credentials are never returned. Get the id from list_integrations.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"list_integration_capabilities",description:"Describe what Sequenzy's integration providers do, whether or not they are connected. For each provider: category, how it connects, what it syncs, every event it emits with the real-world moment that triggers it, the subscriber attributes it writes, supported actions, availability, and caveats. Use this to answer 'what would connecting Stripe give me?', to compare providers before recommending one, or to check whether an event a sequence needs actually exists for that provider. Coverage differs sharply between providers - only Shopify has storefront browse tracking, and only Stripe and Chargebee cover the full trial lifecycle - so check here rather than assuming.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Only return this provider, for example `stripe`, `shopify`, `clerk`. Omit to list every provider."},category:{type:"string",description:"Filter by category: payments, ecommerce, auth, analytics, ads, affiliate, cms, developer."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"list_integration_activity",description:"Read recent integration webhook and sync activity, newest first. This is the log to check when an integration reports connected but contacts or events are not appearing: each row carries the action, status, event type, matched contact, and error. Payloads are sanitized at write time, so no credentials or secrets appear here. Activity is retained for 24 hours only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Only show activity for this integration."},provider:{type:"string",description:"Only show activity for this provider, for example `stripe`."},status:{type:"string",description:"Filter by status: received, queued, processed, skipped, or failed. Use `failed` to triage a broken integration.",enum:["received","queued","processed","skipped","failed"]},limit:{type:"number",description:"Rows to return, 1-100. Defaults to 25."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"set_integration_sync_enabled",description:"Turn a supported payment integration's future bulk imports and backfills on or off. Check get_integration.availableActions first; providers without enable_sync or disable_sync are dashboard-managed. Disabling keeps the connection, credentials, and live webhook delivery active, and requires any in-flight sync to finish first. It does not disconnect the integration. Idempotent: setting the current state succeeds with `changed: false`.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},syncEnabled:{type:"boolean",description:"True to enable sync, false to pause it."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","syncEnabled"]}},{name:"get_integration_pixel",description:"Check whether a Shopify store's storefront tracking pixel is installed and reporting to this account. Read live from Shopify on every call, because a merchant can remove the pixel without Sequenzy hearing about it. ALWAYS check this before promising that browse abandonment, cart recovery, product views, collection views, or storefront search will work: without a live pixel those events never arrive, the sequences built on them never fire, and nothing anywhere reports an error. Returns `pixel.healthy`, the endpoint and signed configuration state, and `dependentEvents` - the event names that rely on this pixel. When `pixel.error` is null and `pixel.healthy` is false, those events are confirmed dark; an error means Shopify could not confirm their state. Fix a confirmed unhealthy state with activate_integration_pixel. Shopify only; other providers return a clear error.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"activate_integration_pixel",description:"Install the Shopify storefront tracking pixel on the connected store, or repoint an existing one at this account. This is what turns on product views, cart activity, and browse abandonment - the data every browse-abandonment and cart-recovery sequence depends on. Idempotent: an already-live pixel returns `changed: false`. Events start flowing on the next storefront visit and nothing is backfilled for the period the pixel was off, so run it before, not after, building the sequence. If the store granted an older permission set, this fails with a message naming the reconnect step rather than silently doing nothing. Shopify only.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Shopify integration ID from list_integrations or get_integration."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}},{name:"sync_integration",description:"Queue a manual re-sync for an integration: customers and revenue for a payment provider (Stripe, Polar, Paddle, Dodo, Creem, Chargebee, Whop), the user backfill for Supabase, or the event-history import for PostHog. Use this for Supabase before a campaign that depends on names or plan attributes - the live trigger only sends rows that change after it was installed, so existing users have no attributes until a backfill runs. The Supabase sync reads the project, schema, and table already configured for the integration and cannot be pointed at a different table; if none is configured yet it fails saying so. This is also the supported way to retry a failed PostHog history import: it restarts from the beginning using the stored personal API key, and already-imported events dedupe, so a re-run cannot duplicate them. Returns immediately - poll get_integration to watch `syncStatus` and `lastSyncAt`, and list_integration_activity for per-row outcomes. Fails with a conflict if a sync is already queued or running; terminal BullMQ failures release PostHog imports for retry. Providers whose backfill is not API-triggerable (Shopify products, Affonso affiliates) return a clear error naming the dashboard. Check `availableActions` on get_integration to see whether this is supported before calling.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var I3=[{name:"list_landing_pages",description:"List all landing pages for a company",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list landing pages for. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"get_landing_page",description:"Get landing page details, content, metrics, and URLs",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"create_landing_page",description:"Create a draft landing page. Provide content for an exact page, or a template for generated starter content.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the landing page in. If not provided, uses the currently selected company."},name:{type:"string",description:"Landing page name. Optional; defaults to a template-specific name."},slug:{type:"string",description:"Optional URL slug. It will be normalized and made unique within the company."},template:{type:"string",description:LH},content:{type:"object",description:I4,additionalProperties:!0}},additionalProperties:!1}},{name:"update_landing_page",description:"Edit a landing page's name, slug, or full content. Provide at least one update field.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Landing page name."},slug:{type:"string",description:"Landing page URL slug. It will be normalized and made unique within the company."},content:{type:"object",description:I4,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"duplicate_landing_page",description:"Duplicate a landing page. The copy is created as a draft with its own slug and stats, so the original keeps its published URL.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID to duplicate."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name with a (copy) suffix."},slug:{type:"string",description:"Optional slug for the copy. It will be normalized and made unique within the company."}},required:["landingPageId"],additionalProperties:!1}},{name:"delete_landing_page",description:"Delete a landing page",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."}},required:["landingPageId"],additionalProperties:!1}},{name:"publish_landing_page",description:"Publish a landing page. Optional name, slug, or content updates are saved before publishing.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before publishing."},content:{type:"object",description:I4,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"unpublish_landing_page",description:"Unpublish a landing page and return it to draft status. Optional name, slug, or content updates are saved first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},landingPageId:{type:"string",description:"Landing page ID."},name:{type:"string",description:"Optional landing page name update."},slug:{type:"string",description:"Optional slug update before unpublishing."},content:{type:"object",description:I4,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain for published landing pages. Returns the DNS target and verification records.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain, for example pages.example.com."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update landing page domain settings. Provide domain to replace the custom domain, verify true to refresh verification, or both.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Replacement custom domain."},verify:{type:"boolean",description:"Refresh domain verification after any domain update."}},additionalProperties:!1}}];var N3=[{name:"list_popups",description:"List saved signup popups for a company with their status, view and conversion counts, and engagement rates. Content blocks are omitted by default to keep the response small - use get_popup for one popup's full content. Popups are the on-site overlay capture surface; use list_forms for inline embedded forms.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list popups for. If not provided, uses the currently selected company."},includeContent:{type:"boolean",description:"Include every popup's full content blocks. Off by default because each popup adds roughly 1.8k characters; prefer get_popup when you only need one."}},additionalProperties:!1}},{name:"get_popup",description:"Get one saved popup with its complete content blocks, trigger, targeting, schedule, frequency, and theme. Read this before editing blocks so the replacement array stays complete.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."}},required:["popupId"],additionalProperties:!1}},{name:"create_popup",description:"Create a saved signup popup and get the one-line script tag that deploys it. The popup is published by default; its trigger, targeting, audience, and duplicate handling stay server-side, so the deployed script carries no API key. Pick a template for the starting design, then refine copy and behavior with update_popup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the popup in. If not provided, uses the currently selected company."},name:{type:"string",description:"Internal saved-popup name."},template:{type:"string",enum:["newsletter-modal","discount-offer","countdown-launch","minimal-slide-in","exit-lead-magnet","live-demo","launch-modal","paper-digest","stark-takeover","top-bar","announcement-bar","fullscreen-welcome"],description:"Starting design. One of: newsletter-modal, discount-offer, countdown-launch, minimal-slide-in, exit-lead-magnet, live-demo, launch-modal, paper-digest, stark-takeover, top-bar, announcement-bar, fullscreen-welcome. Defaults to newsletter-modal."},status:{type:"string",enum:["draft","published"],description:"Defaults to published, which makes the embed script live immediately. Use draft to stage a popup that should not show yet."},listIds:{type:"array",description:"List IDs every signup is added to. Omit or pass an empty array to capture into every list, matching the dashboard default. Use list_lists to resolve IDs.",items:{type:"string"}},tagIds:{type:"array",description:"Optional existing tag IDs applied to every signup. Use list_tags to resolve IDs.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber. Defaults to skip."},headline:{type:"string",description:"Optional popup headline."},description:{type:"string",description:"Optional supporting popup copy."},buttonText:{type:"string",description:"Optional submit button label."},successMessage:{type:"string",description:"Confirmation shown after a successful signup when redirectUrl is omitted."},redirectUrl:{type:"string",description:"Optional HTTP or HTTPS URL for successful signups. Omit it to show the saved confirmation message."},presentation:{type:"string",enum:["modal","slide-in","floating-bar","fullscreen"],description:"How the popup is presented on the page."},placement:{type:"string",enum:["center","left","right","top","bottom"],description:"Where the popup sits in the viewport."},trigger:{type:"object",description:'When the popup opens. { "type": "delay" | "scroll" | "exit-intent" | "click" | "manual", "delaySeconds": 0-3600, "scrollPercent": 1-100, "clickSelector": "#join" }. Only the key each type uses matters: delay reads delaySeconds, scroll reads scrollPercent, and click requires a clickSelector CSS selector. Merged into the current trigger, so patching one key keeps the rest.',additionalProperties:!0},targeting:{type:"object",description:'Where the popup may show. { "domains": ["shop.example.com"], "paths": ["/pricing"], "excludedPaths": ["/checkout"], "device": "all" | "desktop" | "mobile" }. Empty arrays mean no restriction. Merged into the current targeting.',additionalProperties:!0},schedule:{type:"object",description:'Optional run window as ISO 8601 timestamps: { "startsAt": "2026-09-01T00:00:00Z", "endsAt": "2026-09-08T00:00:00Z" }. Use null on either key to clear it. Merged into the current schedule.',additionalProperties:!0},frequency:{type:"object",description:'How often one visitor sees it: { "maxDisplays": 1-100, "windowDays": 1-365 }. Merged into the current frequency.',additionalProperties:!0},visual:{type:"object",description:'Media panel and urgency treatment: { "style": "none" | "accent" | "header" | "rail" | "image" | "countdown", "placement": "top" | "left" | "center" | "right", "imageUrl": "https://...", "imageAlt": "...", "countdownMinutes": 1-10080 }. Use style "image" with an imageUrl for a product panel, or "countdown" with countdownMinutes for a deadline. Style "image" requires an https imageUrl - without one the popup renders the accent rail instead of the split layout, so setting it without an image is rejected. Merged into the current visual.',additionalProperties:!0},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the popup's content blocks. Fetch the current blocks from get_popup, modify them, and send the complete array - the popup must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute. select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. Other kinds and their properties: heading { content, level (1-3), align }, text { content, variant ("paragraph" | "eyebrow" | "caption"), align }, image { src, alt, fit ("cover" | "contain") }, button { text, url, variant, align }, divider {}, spacer { height (8-160) }, custom-html { html, height (40-1200) } - the markup goes in "html", not "content" - feature-grid { features: [{ title, description }], columns }, testimonial { testimonials: [{ quote, name, role }] }, countdown { label, endsAt }, form-step { title, description, blockIds }, submit-button { text, width }, success-screen { heading, message }, error-state { message }. Properties outside a kind's list are rejected rather than dropped, so a typo is reported instead of silently saving an empty block. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["name"],additionalProperties:!1}},{name:"update_popup",description:"Update a saved popup: rename it, publish or unpublish it via status, retarget its audience, change when and where it fires, edit its copy, restyle its theme, or replace its content blocks. Read the current content via get_popup first when editing blocks. Setting status to draft stops it showing without deleting it or changing the embed script.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."},name:{type:"string",description:"New internal saved-popup name."},status:{type:"string",enum:["draft","published"],description:"Set to published to make the popup live, or draft to stop it showing while keeping it and its stats. The embed script stays valid either way."},listIds:{type:"array",description:"Replacement list targeting. Pass an empty array to capture into every list.",items:{type:"string"}},tagIds:{type:"array",description:"Replacement tag IDs applied to every signup. Pass an empty array to clear tags.",items:{type:"string"}},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How to handle an existing subscriber."},headline:{type:"string",description:"New text for the popup's first heading block. Fails if the popup has no heading block; edit blocks instead."},description:{type:"string",description:"New text for the popup's first paragraph block. Fails if the popup has no paragraph block; edit blocks instead."},buttonText:{type:"string",description:"New submit button label."},successMessage:{type:"string",description:"New confirmation message on the success screen."},redirectUrl:{type:"string",description:"HTTP or HTTPS URL for successful signups. Pass an empty string to switch back to the confirmation message."},presentation:{type:"string",enum:["modal","slide-in","floating-bar","fullscreen"],description:"How the popup is presented on the page."},placement:{type:"string",enum:["center","left","right","top","bottom"],description:"Where the popup sits in the viewport."},trigger:{type:"object",description:'When the popup opens. { "type": "delay" | "scroll" | "exit-intent" | "click" | "manual", "delaySeconds": 0-3600, "scrollPercent": 1-100, "clickSelector": "#join" }. Only the key each type uses matters: delay reads delaySeconds, scroll reads scrollPercent, and click requires a clickSelector CSS selector. Merged into the current trigger, so patching one key keeps the rest.',additionalProperties:!0},targeting:{type:"object",description:'Where the popup may show. { "domains": ["shop.example.com"], "paths": ["/pricing"], "excludedPaths": ["/checkout"], "device": "all" | "desktop" | "mobile" }. Empty arrays mean no restriction. Merged into the current targeting.',additionalProperties:!0},schedule:{type:"object",description:'Optional run window as ISO 8601 timestamps: { "startsAt": "2026-09-01T00:00:00Z", "endsAt": "2026-09-08T00:00:00Z" }. Use null on either key to clear it. Merged into the current schedule.',additionalProperties:!0},frequency:{type:"object",description:'How often one visitor sees it: { "maxDisplays": 1-100, "windowDays": 1-365 }. Merged into the current frequency.',additionalProperties:!0},visual:{type:"object",description:'Media panel and urgency treatment: { "style": "none" | "accent" | "header" | "rail" | "image" | "countdown", "placement": "top" | "left" | "center" | "right", "imageUrl": "https://...", "imageAlt": "...", "countdownMinutes": 1-10080 }. Use style "image" with an imageUrl for a product panel, or "countdown" with countdownMinutes for a deadline. Style "image" requires an https imageUrl - without one the popup renders the accent rail instead of the split layout, so setting it without an image is rejected. Merged into the current visual.',additionalProperties:!0},theme:{type:"object",description:"Visual theme overrides merged into the current theme. Any subset of: accentColor, backgroundColor, textColor, mutedTextColor, cardColor, borderColor (all #rrggbb), borderRadius (0-32), headingFontFamily, bodyFontFamily, density (compact | balanced | spacious).",additionalProperties:!0},blocks:{type:"array",description:`Full replacement for the popup's content blocks. Fetch the current blocks from get_popup, modify them, and send the complete array - the popup must keep exactly one required email field and one submit button. Blocks render in array order; every block needs a unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Input blocks are kind "form-field": { id, kind: "form-field", fieldType, name, label, placeholder, required, defaultValue, showLabel, width ("full" | "half"), mapsTo, options }. fieldType is one of text, email, phone, number, textarea, select, radio, checkbox, consent, hidden. mapsTo is one of email, firstName, lastName, phone, customAttribute and defaults to customAttribute, which stores the answer under the block's "name" as a subscriber custom attribute. select, radio, and checkbox fields require options: [{ value, label, id }] - label and id default to value when omitted. Other kinds and their properties: heading { content, level (1-3), align }, text { content, variant ("paragraph" | "eyebrow" | "caption"), align }, image { src, alt, fit ("cover" | "contain") }, button { text, url, variant, align }, divider {}, spacer { height (8-160) }, custom-html { html, height (40-1200) } - the markup goes in "html", not "content" - feature-grid { features: [{ title, description }], columns }, testimonial { testimonials: [{ quote, name, role }] }, countdown { label, endsAt }, form-step { title, description, blockIds }, submit-button { text, width }, success-screen { heading, message }, error-state { message }. Properties outside a kind's list are rejected rather than dropped, so a typo is reported instead of silently saving an empty block. Validation errors name the offending property, for example "blocks[3].options[0].value".`,items:{type:"object",additionalProperties:!0}}},required:["popupId"],additionalProperties:!1}},{name:"get_popup_embed",description:"Get a published popup's script URL and ready-to-paste embed snippets for plain HTML, React/Next.js, WordPress, and Shopify. The snippet contains no API key - the trigger, targeting, and audience rules stay server-side.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."}},required:["popupId"],additionalProperties:!1}},{name:"duplicate_popup",description:"Copy a saved popup into a new draft with its own view and conversion counts. The original keeps showing and keeps its stats. Use this to test a new offer or headline against a popup that already performs.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID to copy."},name:{type:"string",description:'Name for the copy. Defaults to the original name with " (copy)" appended.'}},required:["popupId"],additionalProperties:!1}},{name:"delete_popup",description:"Permanently delete a saved popup and its view and conversion counts. Subscribers it already captured are not affected. To stop a popup from showing while keeping its stats, set status to draft with update_popup instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},popupId:{type:"string",description:"Saved popup ID returned by list_popups or create_popup."}},required:["popupId"],additionalProperties:!1}}];var E3=[{name:"list_products",description:"List synced products (Stripe, Shopify, WooCommerce) including any attached digital delivery file. Useful before attaching a file or building a purchase sequence for a specific product. For Stripe products, variants are the product's active prices (variantId = Stripe price ID), so an exact price can be targeted even when it is not the default. Returns one page: check pagination.total and pagination.hasMore, and page with offset to read the whole catalog.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list products for. If not provided, uses the currently selected company."},provider:{type:"string",description:"Filter by provider: stripe, shopify, woocommerce, or manual."},search:{type:"string",description:"Filter products by title."},limit:{type:"number",description:"Maximum products to return (1-100). Defaults to 50. Compare pagination.total against the products returned to detect truncation."},offset:{type:"number",description:"Number of products to skip. Defaults to 0. Use with limit to page through catalogs larger than 100."}}}},{name:"upsert_products",description:"Create or update products in the catalog (Commerce API, keyed by your productId, stored under the api provider). Use this to add products that are not synced from Stripe/Shopify/WooCommerce, then attach a deliverable file with attach_product_file and build a purchase sequence for them.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},products:{type:"array",description:"Products to create or update (max 100).",items:{type:"object",properties:{productId:{type:"string",description:"Your stable product identifier (used for upserts and order line items)."},title:{type:"string",description:"Product title."},description:{type:"string",description:"Product description."},imageUrl:{type:"string",description:"Product image URL."},url:{type:"string",description:"Product page URL."},priceCents:{type:"number",description:"Price in the smallest currency unit."},currency:{type:"string",description:"ISO currency code, e.g. USD."},inStock:{type:"boolean",description:"Whether the product is in stock."},providerCreatedAt:{type:["string","null"],description:"ISO 8601 creation time from the source catalog. Omit to preserve the stored value; pass null to clear it. Used for newest-product ranking."}},required:["productId","title"]}}},required:["products"]}},{name:"delete_product",description:"Delete a product previously pushed via upsert_products (Commerce API products only), identified by your productId.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Your productId used when upserting the product."}},required:["productId"]}},{name:"attach_product_file",description:"Attach a distributable file to a product, either by public URL or by uploading a local file (filePath, local MCP server only). After a purchase of the product, sequence emails can link to it with {{event.download.url}} and {{event.download.name}}.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."},url:{type:"string",description:"Public http(s) URL of the file to deliver. Provide url or filePath, not both."},filePath:{type:"string",description:"Local path of a file to upload and attach (PDF, ePub, ZIP, image, audio, video, or text, up to 100MB). Only available when the MCP server runs locally on this machine."},fileName:{type:"string",description:"Display name for the file (e.g. guide.pdf). Used as {{event.download.name}}."}},required:["productId"]}},{name:"remove_product_file",description:"Remove the attached distributable file from a product.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},productId:{type:"string",description:"Product ID from list_products, or your own productId for products pushed via upsert_products."}},required:["productId"]}},{name:"sync_products",description:"Queue a sync of the Stripe product catalog into the products list. Requires an active Stripe integration with bulk sync enabled. Pass integrationId when more than one Stripe account is connected; otherwise the most recently connected enabled account is used.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},integrationId:{type:"string",description:"Stripe integration ID from list_integrations. Recommended when multiple Stripe accounts are connected."}}}}];var T3=[{name:"render_email",description:"Render a campaign, sequence email step, or template to the exact email-safe HTML that would be sent, for embedding a visual preview in an external builder or dashboard, or for checking merge tags before anyone is enrolled. Pass exactly one target: campaignId, sequenceId plus nodeId, or templateId. Without a subscriber the email renders for a sample contact, so contact-specific merge tags resolve to empty values. Check unresolvedMergeTags in the response to tell an unrecognized tag apart from one that is merely blank for this contact - both render as an empty string, so the HTML alone cannot distinguish them. Only names this render could check are called unknown. Nothing is checkable without the contact's attributes, because a bare {{plan}} reads the same attribute map as {{subscriber.plan}}, so pass subscriberId (or an inline subscriber with customAttributes) to catch typos at all. On top of that, {{event.*}} needs sample event properties in variables, since a real send fills those from the enrolling event, and {{recommendedProducts.*}} is only checkable when a stored subscriberId returns recommendations. Rendering a transactional email is checkable only when variables is passed, since its tags come from the variables of each send call and nothing marks them as such. 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 sequence step downstream of a create_discount step renders {{discount.*}} with that step's real terms and a clearly fake sample code; when the step is reachable by paths that do not all run the same discount step, or when a template is rendered on its own, {{discount.*}} is reported as no_value rather than as a typo. Links stay clean unless tracking is true. Per-send click redirects and the open pixel are added at send time against a real email send record, so they never appear here.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID to render."},sequenceId:{type:"string",description:"Sequence ID. Requires nodeId."},nodeId:{type:"string",description:"Email step node ID from get_sequence. Requires sequenceId."},templateId:{type:"string",description:"Template ID to render."},subscriberId:{type:"string",description:"Personalize as this stored subscriber. Mutually exclusive with subscriber. The rendered HTML then carries that subscriber's details, so this needs the subscribers:read scope as well."},subscriber:{type:"object",description:"Personalize as an ad-hoc contact that need not exist in the account. Mutually exclusive with subscriberId.",properties:{email:{type:"string",description:"Contact email address."},firstName:{type:"string",description:"Contact first name."},lastName:{type:"string",description:"Contact last name."},customAttributes:{type:"object",description:"Custom attributes used by merge tags and blocks.",additionalProperties:!0}},required:["email"]},variables:{type:"object",description:"Extra merge variables layered over the contact's attributes. Values are HTML-escaped; content can prefix a tag with 'html.' ({{html.subscriber.body_html}}) to render a trusted, sanitized HTML value unescaped, and this tool previews that exactly as a send would.",additionalProperties:!0},locale:{type:"string",description:"Force a localization locale instead of deriving it from the contact."},variantId:{type:"string",description:"Render a specific A/B test variant of the campaign or sequence step."},tracking:{type:"boolean",description:"Apply the company's auto-UTM link decoration as a real send would. Defaults to false so the preview shows the author's clean URLs."}},required:[]}}];var O9={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},R3={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},attributePath:{type:["string","null"],description:"Subscriber attribute path required for attribute_change goals."},attributeCondition:{type:["string","null"],enum:["changed","changed_to","changed_from_to",null],description:"How the subscriber attribute must change."},attributeValue:{type:["string","null"],description:"Target value for changed_to or changed_from_to."},attributePreviousValue:{type:["string","null"],description:"Previous value required for changed_from_to."},eventPropertyName:{type:["string","null"],description:"Optional event property whose numeric value is tracked."},eventPropertyLabel:{type:["string","null"],description:"Display label for the tracked event property."},attributionWindowHours:{type:"integer",minimum:1,maximum:720,description:"Attribution window in whole hours."},isActive:{type:"boolean",description:"Whether conversion tracking is active for this goal. Defaults to true when creating."}},S3=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:O9,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event or subscriber-attribute conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...O9,...R3},required:["sequenceId","name"],additionalProperties:!1}},{name:"update_sequence_goal",description:"Update a persisted sequence conversion goal, including its signal, attribution window, or active state.",inputSchema:{type:"object",properties:{...O9,goalId:{type:"string",description:"Sequence goal ID."},...R3},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...O9,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var VQ={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},C3=[{name:"get_sequence_inbound_webhook",description:"Read the usable URL, mapping, sample payload, and setup status for a sequence inbound webhook.",inputSchema:{type:"object",properties:VQ,required:["sequenceId"],additionalProperties:!1}},{name:"configure_sequence_inbound_webhook",description:"Create or update the secret endpoint attached to a sequence inbound_webhook trigger. On first setup, omitted mapping/sample inputs apply the selected catalog or custom integration defaults; on later calls, omitted inputs keep the saved values, so a captured sample survives mapping-only updates. Use clearFieldMapping to return to pending setup and clearSamplePayload to drop the saved sample.",inputSchema:{type:"object",properties:{...VQ,fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},samplePayload:{type:"object",description:"Representative raw webhook payload for mapping setup.",additionalProperties:!0},clearFieldMapping:{type:"boolean",description:"Set true to clear the saved mapping and return the endpoint to pending_setup."},clearSamplePayload:{type:"boolean",description:"Set true to clear the saved sample payload."}},required:["sequenceId"],additionalProperties:!1}},{name:"rotate_sequence_inbound_webhook_secret",description:"Rotate the inbound webhook secret and return a new URL. The previous URL stops working immediately.",inputSchema:{type:"object",properties:VQ,required:["sequenceId"],additionalProperties:!1}}];var k3=[{name:"list_sequences",description:"List all email sequences (automations). Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list sequences for. If not provided, uses the currently selected company."},status:{type:"string",enum:["draft","active","paused","archived"],description:"Optional dashboard status filter."},search:{type:"string",description:"Case-insensitive search across sequence name and description."},labels:{type:"array",items:{type:"string"},description:"Return sequences assigned any of these dashboard label names."},limit:{type:"number",description:"Page size from 1 to 100. When limit and offset are both omitted, every sequence is returned."},offset:{type:"number",description:"Zero-based result offset."}}}},{name:"get_sequence",description:"Get sequence details, editable step content, and graph topology. Read effectiveStatus (draft, live, enrollment_paused, paused, archived) to know whether a sequence is running: status alone reads `active` even when new enrollments are paused, and the legacy triggerConfig.active flag is not used by the runtime. Each sequence.nodes item includes id, nodeType, current config, updatedAt, and updateHints with its editable/managed fields and ready-to-return expectedUpdatedAt token for update_sequence_node/update_sequence_nodes. The response also includes sequence.edges and graphRevision for safe edit_sequence_graph calls, plus sequence.emails with each email step's nodeId, linked emailId, subject, previewText, emailPreset (the per-email Style > Format for native blocks, including emails with supported custom HTML blocks; null when the entire email is standalone raw HTML), and blocks.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"],additionalProperties:!1}},{name:"list_sequence_enrollments",description:"List the individual contacts currently enrolled in a sequence, with the node each one is sitting on. Use this when get_sequence_stats gives you enrollmentCounts and you need the actual subscribers behind a number, such as everyone waiting at one step. Filter by currentNodeId (take the ID from get_sequence_stats enrollmentCounts.byCurrentNode or get_sequence nodes), status, subscriberId, or email, and page with limit/offset to export the full list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be listed."},currentNodeId:{type:"array",items:{type:"string"},description:"Only return enrollments currently sitting on these sequence node IDs."},status:{type:"array",items:{type:"string",enum:["active","waiting","completed","failed","cancelled"]},description:"Enrollment statuses to include. Defaults to active and waiting, which is every contact still moving through the sequence."},subscriberId:{type:"array",items:{type:"string"},description:"Only return enrollments for these subscriber IDs. Useful for checking where specific contacts stand."},email:{type:"string",description:"Only return enrollments for this exact email address (case-insensitive)."},sort:{type:"string",enum:["enrolled_at_desc","enrolled_at_asc","wait_until_asc","wait_until_desc"],description:"Result order. Defaults to enrolled_at_desc (most recently enrolled first). Use wait_until_asc to see who resumes next."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved email step in a sequence. Call get_sequence first and pass the target email step's nodeId. Accepts 1-10 reviewer email addresses and returns one durable emailSendId per recipient for get_email_send delivery inspection. The sequence is not enabled and no subscribers are enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID containing the saved email step."},nodeId:{type:"string",description:"Email step nodeId from get_sequence. The node must belong to sequenceId."},recipients:{type:"array",minItems:1,maxItems:10,items:{type:"string",format:"email"},description:"One to ten internal reviewer email addresses. Duplicate addresses are sent only once."}},required:["sequenceId","nodeId","recipients"],additionalProperties:!1}},{name:"create_sequence",description:"Create and persist a disabled draft email sequence, follow-up series, drip campaign, nurture flow, or automation workflow. For natural-language content, provide goal and emailCount. Use explicit steps for finished caller-supplied content, exact workflows, or migrations. Configure trigger plus its relevant field, such as listId, tagName, segmentId, or eventName. Supports email and SMS steps, delays and date waits, actions that dynamically create a provider discount/code (later emails print it with {{discount.code}}), subscriber updates, event filters, enrollment rules, sending windows, and stop conditions. The saved draft appears in list_sequences. Never call enable_sequence unless the user explicitly asks to activate it.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the sequence in. If not provided, uses the currently selected company."},fromEmail:{type:"string",description:"From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Existing sender profile ID (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName. To keep this profile under a different display name, set fromName on the email steps instead, where it is a per-step override."},replyTo:{type:"string",description:"Reply-To address for all emails in this sequence. A reply profile is created when needed."},replyToName:{type:"string",description:t1},replyProfileId:{type:"string",description:"Existing reply profile ID (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},name:{type:"string",description:"Sequence name (e.g., 'User Onboarding', 'Welcome Series')"},description:{type:"string",description:"Optional sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses blind-copied on every email in the sequence (max 10)."},labels:{type:"array",items:{type:"string"},description:"Dashboard label names to assign. Missing labels are created."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Trigger type: contact_added, tag_added, segment_entered, event_received, inbound_webhook, inactivity, or frequency. Defaults to contact_added for a blank dashboard-compatible draft."},listId:{type:"string",description:"List ID to trigger on (for contact_added trigger). If not provided, triggers on any list."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger)"},segmentId:{type:"string",description:"Segment ID to trigger on (required for segment_entered trigger). Use list_segments first to choose a saved segment."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered triggers, cancel active enrollments when the contact leaves the segment."},eventName:{type:"string",description:"Event name to trigger on (required for event_received, inbound_webhook, inactivity, and frequency triggers)"},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook, for example cal-com."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Custom inbound webhook integration descriptor with name, setupInstructions, samplePayload, and fieldMapping.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",additionalProperties:!0},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"]}}},required:["name","setupInstructions","samplePayload","fieldMapping"]},propertyFilters:{type:"array",description:"Optional filters for event_received or inbound_webhook triggers. The sequence starts only when all filters match. Max 10.",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the event properties, e.g. 'lineItems[].providerProductId' or 'plan'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"],description:"Comparison operator. one_of matches when the property equals any entry of the value array."},value:{type:["string","number","boolean","array"],items:{type:["string","number"]},maxItems:50,description:"Value to compare against. Required for every operator except exists/not_exists. For one_of, pass an array of strings or numbers (max 50 values); all other operators take a single value."}},required:["path","operator"]}},inactiveDays:{type:"number",description:"Number of days of inactivity (required for inactivity trigger, must be >= 1)"},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"When to start counting inactivity for subscribers who never had the event. Defaults to sequence_created_at."},minCount:{type:"number",description:"Minimum event count (required for frequency trigger, must be >= 1)"},timeWindowDays:{type:"number",description:"Time window in days for frequency trigger (required for frequency trigger, must be >= 1)"},emailCount:{type:"number",description:"Number of emails in the sequence (default: 5, max: 10)"},durationDays:{type:"number",description:"Total duration in days used to space AI-generated sequence emails. Only applies when using goal-based AI generation."},emailStyle:{type:"string",enum:["visual","plain"],description:"Style for AI-generated emails: 'visual' (designed, with heroes/imagery/rich sections) or 'plain' (personal, text-first notes with a single button). Only applies to goal-based AI generation. Defaults to the company's saved preference when omitted."},goal:{type:"string",description:"What this sequence should accomplish for AI generation. Be specific to the app's actual features and user journey. Avoid generic goals that don't match the app's business model."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Sequence re-entry mode. Defaults to 'unlimited', which re-enrolls a subscriber every time the trigger fires again - for a tag_added drip that means re-applying the tag sends the whole series a second time, so set 'one_time' unless repeat runs are wanted. Exception: ecommerce.back_in_stock and ecommerce.replenishment_due triggers default to 'matching_field' so each product is notified separately; leave those alone unless the user asks otherwise. Use 'matching_field' only for event_received triggers when duplicate active runs should be blocked per event field value. Changeable later with update_sequence."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Leave omitted for Shopify back-in-stock/replenishment product-variant defaults."},sendingWindow:J9,stopCondition:{type:"object",description:"Optional explicit auto-stop condition, re-evaluated before every step including the first one. Use { type: 'has_tag', value: 'customer' } to end the sequence when a subscriber gets a tag, { type: 'entered_segment', value: 'segment_123' } when they enter a segment, { type: 'added_to_list', value: 'list_123' } when they join a list, { type: 'field_changed', value: 'plan' } when a subscriber field changes, { type: 'event_received', value: 'onboarding.completed' } when an event is tracked, or { type: 'none', value: null } for no auto-stop. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. event_received only counts events received after enrollment - the enrolling event and earlier history never satisfy the stop. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching. For type 'event_received': { mode: 'event_property_filter', propertyFilters: [{ path: 'quota_used', operator: 'greater_than', value: 1 }] } stops only when an event received after enrollment matches every filter (operators: exists, not_exists, equals, not_equals, one_of, contains, greater_than, less_than), or { mode: 'event_property', rules: [{ entryFieldPath: 'orderId', eventFieldPath: 'orderId' }] } stops only when the stop event's field equals the same field on the enrolling event. For type 'field_changed': { mode: 'field_value', operator: 'equals', value: 'pro' } stops only when the field changes to a matching value. event_received stops only match events received after enrollment, so a stop on the trigger's own event name is safe when combined with propertyFilters.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value"]},propertyFilters:{type:"array",description:"event_property_filter mode: filters the stop event must all match; same shape as trigger propertyFilters.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Comparison value (string, number, or boolean; array for one_of). Omit for exists/not_exists."}},required:["path","operator"]}},rules:{type:"array",description:"event_property mode: entry-vs-stop-event field equality rules.",items:{type:"object",properties:{entryFieldPath:{type:"string"},eventFieldPath:{type:"string"}},required:["entryFieldPath","eventFieldPath"]}},operator:{type:"string",enum:["equals","not_equals","greater_than","less_than","contains","not_contains"],description:"field_value mode comparison operator."},value:{type:"string",description:"field_value mode comparison value."}},additionalProperties:!0}},required:["type"]},steps:{type:"array",description:"Explicit sequence steps. Omit type for email steps, use type: 'sms' for SMS, type: 'create_discount' for a dynamic discount, or type: 'update_subscriber' with nodeType: 'action_update_attributes' and config to copy trigger-event values such as {{event.plan}} into subscriber data.",items:{type:"object",properties:{type:{type:"string",enum:["email","sms","create_discount","discount","update_subscriber"],description:"Step type. Omit or use 'email' for email content. Use 'sms' to send a text message, 'create_discount' to generate a code, or 'update_subscriber' to copy trigger data into the subscriber."},nodeType:{type:"string",enum:["action_email","action_sms","action_create_discount","action_update_attributes"],description:"Internal step type. Use action_update_attributes with config for Update Subscriber steps."},config:I6,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:Z6,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${U0}`},isTransactional:{type:"boolean",description:"Send this email as transactional and omit the marketing unsubscribe footer."},ccEmails:{type:"array",items:{type:"string"},description:"Addresses CC'd on this email step."},bccEmails:{type:"array",items:{type:"string"},description:"Addresses BCC'd on this email step in addition to sequence BCC."},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string",description:"Filename shown in the recipient's email client. Event merge tags are supported, for example file-{{event.order_id}}.pdf."},path:{type:"string",description:"Public HTTPS URL or event-backed URL template such as {{event.file_url}}; resolved per enrollment and fetched at send time."}},required:["filename","path"]},description:"URL-backed file attachments for this email step (max 10, 7MB total per email). Paths may use {{event.*}} values from the event that enrolled the subscriber; the resolved public URL is validated and fetched at send time."},...T4,text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},delay:V6,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:K6,waitUntilWeekday:P6,name:{type:"string",description:"Email template name for email steps."},discount:{type:"object",description:`Discount configuration for create_discount steps. Prefer this nested shape for new integrations; legacy top-level discount fields are still accepted.${Q9}`,properties:{label:{type:"string",description:"Builder label for the discount step."},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. Defaults to 'stripe' when omitted."},discountType:{type:"string",enum:["percent","amount"],description:"Discount type."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Stripe-only. Restrict each generated promotion code to the matched subscriber's Stripe customer."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."},name:{type:"string",description:"Optional display name for each dynamically generated provider discount."}}},label:{type:"string",description:"Legacy top-level discount label. Prefer discount.label."},provider:{type:"string",enum:["stripe","shopify"],description:"Legacy top-level discount provider. Prefer discount.provider. Supports 'stripe' and 'shopify'."},discountType:{type:"string",enum:["percent","amount"],description:"Legacy top-level discount type. Prefer discount.discountType."},percentOff:{type:"number",description:"Percent discount from 1 to 100. Required when discountType is percent."},amountOff:{type:"number",description:"Fixed amount discount in the smallest currency unit, for example 500 for $5. Required when discountType is amount."},currency:{type:"string",description:"ISO currency for amount discounts. Defaults to usd."},duration:{type:"string",enum:["once","forever","repeating"],description:"Discount duration. Defaults to once."},durationInMonths:{type:"number",description:"Required for repeating discounts."},appliesToAllPlans:{type:"boolean",description:"Whether the discount applies to all plans. Defaults to true."},planIds:{type:"array",description:"Provider product IDs when appliesToAllPlans is false. Stripe uses IDs like prod_abc123; Shopify accepts numeric product IDs or gid://shopify/Product/... IDs.",items:{type:"string"}},codePrefix:{type:"string",description:"Optional prefix for generated dynamic codes. The final code also includes a subscriber/token suffix."},maxRedemptions:{type:"number",description:"Maximum redemptions for each generated code. Use 1 for subscriber-specific codes."},lockToSubscriber:{type:"boolean",description:"Legacy top-level Stripe-only flag. Prefer discount.lockToSubscriber."},expiresAt:{type:"string",description:"Optional future expiration date or ISO timestamp."},expiresInHours:{type:"number",description:"Optional relative expiration in hours, resolved when each subscriber's code is created (e.g., 48 for a 48-hour window per subscriber). Takes precedence over expiresAt."}}}}},required:["name"]}}];var v3=[{name:"update_sequence",description:"Update an existing sequence: both its settings and its steps. Sequence-level settings live directly on this tool - name, description, labels, trigger (with its trigger-specific field), enrollmentMode plus enrollmentFieldPath, enrollmentPaused, userCancellable, stopCondition, sendingWindow, bccEmails, and the sender/reply identity. This is the only way to change enrollmentMode after create_sequence, so use it to move a tag- or event-triggered sequence off the default 'unlimited' re-entry to 'one_time' or 'matching_field'. To target a specific existing step, use IDs returned by get_sequence. The emails/steps arrays edit email steps, smsSteps edits SMS steps, and subscriberUpdateSteps replaces the config of action_update_attributes steps. To insert new linear steps, use insertSteps with an afterNodeId from get_sequence; omit afterNodeId only to append to an unambiguous linear tail. Deleting a step immediately moves parked recipients to its unique surviving successor, or completes them when no successor remains; inspect migratedRecipientCount and completedRecipientCount in the returned sequence. For active sequences, structural changes such as insertSteps or branch require confirmStructuralChange:true after the user confirms the live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"},name:{type:"string",description:"Sequence name"},description:{type:"string",description:"Sequence description shown in the dashboard."},userCancellable:{type:"boolean",description:"Whether subscribers may cancel their own active enrollment."},labels:{type:"array",items:{type:"string"},description:"Replace dashboard labels by name. Missing labels are created; [] clears labels."},trigger:{type:"string",enum:["contact_added","tag_added","segment_entered","event_received","inbound_webhook","inactivity","frequency"],description:"Atomically replace the existing dashboard trigger. Include the fields required by the new trigger type. Active sequences also require confirmLiveChange:true."},listId:{type:"string",description:"List ID for a contact_added trigger replacement."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},segmentId:{type:"string",description:"Saved segment ID required for a segment_entered trigger replacement."},stopOnSegmentExit:{type:"boolean",description:"For segment_entered, stop active enrollments when the subscriber leaves the segment."},eventName:{type:"string",description:"Event name required for event_received, inbound_webhook, inactivity, and frequency trigger replacements."},propertyFilters:{type:"array",description:"Optional event-property filters for event_received or inbound_webhook.",items:{type:"object",properties:{path:{type:"string"},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Scalar comparison value, or an array for one_of."}},required:["path","operator"],additionalProperties:!1}},integrationSlug:{type:"string",description:"Catalog integration slug for inbound_webhook."},integrationEventKey:{type:"string",description:"Catalog integration event key for inbound_webhook."},customIntegration:{type:"object",description:"Typed custom inbound webhook descriptor used instead of a catalog integration.",properties:{name:{type:"string"},setupInstructions:{type:"string"},samplePayload:{type:"object",additionalProperties:!0},fieldMapping:{type:"object",properties:{email:{type:"string"},firstName:{type:"string"},lastName:{type:"string"},properties:{type:"object",additionalProperties:{type:"string"}}},required:["email"],additionalProperties:!1},docsUrl:{type:"string"},suggestedProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},path:{type:"string"},description:{type:"string"}},required:["name","path","description"],additionalProperties:!1}}},required:["name","setupInstructions","samplePayload","fieldMapping"],additionalProperties:!1},inactiveDays:{type:"number",description:"Days without event activity required for an inactivity trigger."},inactivityBaseline:{type:"string",enum:["sequence_created_at","subscriber_created_at"],description:"Baseline for subscribers who have never produced the inactivity event."},minCount:{type:"number",description:"Minimum event count for a frequency trigger."},timeWindowDays:{type:"number",description:"Frequency trigger lookback window in days."},fromEmail:{type:"string",description:"Set the From address for all emails in this sequence. Its domain must be configured and verified."},fromName:{type:"string",description:o1},senderProfileId:{type:"string",description:"Set an existing sender profile (see list_sender_profiles). It already supplies both the From address and display name, so send it on its own and omit fromEmail and fromName. To keep this profile under a different display name, set fromName on the email steps instead, where it is a per-step override."},replyTo:{type:"string",description:"Set the Reply-To address for all emails in this sequence."},replyToName:{type:"string",description:t1},replyProfileId:{type:"string",description:"Set an existing reply profile (see list_sender_profiles). It already supplies both the Reply-To address and display name, so send it on its own and omit replyTo and replyToName."},enrollmentPaused:{type:"boolean",description:"Set true to stop new enrollments for an active sequence while current recipients continue. Set false to resume new enrollments. The sequence must already be active."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence. Required for insertSteps or branch when the sequence is active; not needed for content-only email edits."},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms replacing the trigger of an active sequence. Required with trigger when the sequence is active."},enrollmentMode:{type:"string",enum:["unlimited","one_time","matching_field"],description:"Updated sequence re-entry mode. Use this to move an existing sequence off the default 'unlimited', which re-enrolls a subscriber every time the trigger fires again. 'matching_field' is only valid for event-based sequence triggers."},enrollmentFieldPath:{type:"string",description:"Scalar dot-path event property used by enrollmentMode='matching_field', such as 'order.id' or 'product.providerVariantId'. Array traversal with [] is not supported; use propertyFilters for array matching. Omit to leave unchanged. Use clearEnrollmentFieldPath to clear it."},clearEnrollmentFieldPath:{type:"boolean",description:"Set true to clear enrollmentFieldPath without sending a nullable schema value."},sendingWindow:J9,clearSendingWindow:{type:"boolean",description:"Set true to remove the sequence sending window. Do not provide this together with sendingWindow."},bccEmails:{type:"array",items:{type:"string"},description:"Email addresses that receive a blind copy of every email this sequence sends, such as a customer support inbox (max 10). Omit to leave unchanged. Use clearBccEmails to remove them."},clearBccEmails:{type:"boolean",description:"Set true to remove the sequence BCC addresses. Do not provide this together with bccEmails."},stopCondition:{type:"object",description:"Update the sequence auto-stop condition, which is re-evaluated before every step including the first one. Example: { type: 'has_tag', value: 'customer' } ends the sequence when the subscriber has that tag. Use { type: 'entered_segment', value: 'segment_123' } to stop when they enter a segment, { type: 'field_changed', value: 'plan' } to stop when a subscriber field changes, { type: 'added_to_list', value: 'list_123' } to stop when they join a list, or { type: 'none', value: null } to clear it. The negative forms are audience guards rather than lifecycle stops: { type: 'does_not_have_tag', value: 'allowlist' } and { type: 'removed_from_list', value: 'list_123' } cancel the run before any step sends unless the subscriber carries that tag or list membership. That is how you restrict a live event or segment trigger to a chosen set of contacts without editing the graph, for example for a first pass on a production trigger or a phased rollout. Guarded-out contacts still enroll and are then cancelled at the trigger node, so they appear as cancellations there rather than in the active or waiting enrollment counts. Clearing the guard does not retry them: nothing re-enrolls them, so they only receive the sequence if the trigger fires for them again, which one-shot triggers never do, and on the one_time enrollment mode a repeated trigger is ignored too because enrollment is blocked by the existence of any earlier run rather than by its outcome. Guard a duplicate sequence and leave the real one ungated, or enroll the missed contacts afterwards with enroll_subscribers_in_sequence, which skips the one_time check.",properties:{type:{type:"string",enum:["none","has_tag","does_not_have_tag","added_to_list","removed_from_list","entered_segment","field_changed","event_received"],description:"Stop condition type. has_tag, added_to_list, entered_segment, field_changed, and event_received stop the run once the thing happens. event_received only counts events received after enrollment - the enrolling event and earlier history never satisfy the stop. does_not_have_tag and removed_from_list stop the run whenever the subscriber lacks that tag or list membership, so they act as a required-tag or required-list allowlist for everyone the trigger enrolls."},value:{type:["string","null"],description:"Tag name, list ID, segment ID, field path, or event name for the stop condition. For the does_not_have_tag and removed_from_list guards this is the tag or list a subscriber must have to keep receiving the sequence."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching, three shapes keyed by mode. (1) For type 'event_received', { mode: 'event_property_filter', propertyFilters: [{ path: 'quota_used', operator: 'greater_than', value: 1 }] } stops only when an event received AFTER enrollment matches every filter (operators: exists, not_exists, equals, not_equals, one_of, contains, greater_than, less_than - same shape as trigger propertyFilters). Use this when a later occurrence must satisfy specific criteria, e.g. enroll on quota_used=1 and stop when quota_used is greater than 1. Without propertyFilters, a same-name event stop fires on any later occurrence. (2) For type 'event_received', { mode: 'event_property', rules: [{ entryFieldPath: 'orderId', eventFieldPath: 'orderId' }] } stops only when the stop event's field equals the same field captured on the enrolling event (requires an event-based trigger). (3) For type 'field_changed', { mode: 'field_value', operator: 'equals', value: 'pro' } stops only when the field changes to a matching value (operators: equals, not_equals, greater_than, less_than, contains, not_contains). Pass null to clear. Note: event_received stops only match events received after enrollment; the enrolling event itself never satisfies the stop.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value"],description:"Which matching shape the config uses. Defaults to event_property_filter when omitted and propertyFilters is present."},propertyFilters:{type:"array",description:"event_property_filter mode: filters a stop event must all match, e.g. [{ path: 'quota_used', operator: 'greater_than', value: 1 }].",items:{type:"object",properties:{path:{type:"string",description:"Dot-path into the stop event's properties, e.g. 'quota_used' or 'order.total'."},operator:{type:"string",enum:["exists","not_exists","equals","not_equals","one_of","contains","greater_than","less_than"]},value:{description:"Comparison value (string, number, or boolean; array of values for one_of). Omit for exists/not_exists."}},required:["path","operator"]}},rules:{type:"array",description:"event_property mode: entry-vs-stop-event field equality rules, e.g. [{ entryFieldPath: 'orderId', eventFieldPath: 'orderId' }].",items:{type:"object",properties:{entryFieldPath:{type:"string"},eventFieldPath:{type:"string"}},required:["entryFieldPath","eventFieldPath"]}},operator:{type:"string",enum:["equals","not_equals","greater_than","less_than","contains","not_contains"],description:"field_value mode comparison operator."},value:{type:"string",description:"field_value mode comparison value."}},additionalProperties:!0}},required:["type"]},branch:{type:"object",description:"Insert an if/else branch into an existing sequence. Use get_sequence first to choose afterNodeId and existing target nodes. Each conditional path can provide new steps, targetNodeId, or both; the else path uses elseSteps and/or elseTargetNodeId. A target may be the completion node. Empty paths require allowEmptyPaths:true. Conditions support tag presence/absence, lists, saved segments, events, clicked links, and field comparisons. Use activityScope for event_received and link_clicked checks.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert the branch after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails."},label:{type:"string",description:"Optional branch node label."},splitMode:JQ,randomPercentages:wQ,branches:{type:"array",description:XQ,items:GQ},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path. Not valid on a random split.",items:R4},elseTargetNodeId:{type:"string",description:"Optional existing node to route the else path to. Use a node ID from get_sequence, including the completion node. If elseSteps are also provided, they run before this target."},allowEmptyPaths:{type:"boolean",description:"Set true only when intentionally creating UI placeholders. A path with targetNodeId is already explicit and does not need this flag."}},required:["afterNodeId","branches"]},insertSteps:{type:"object",description:"Insert one or more new linear steps into an existing sequence. Use get_sequence first, then pass afterNodeId to insert after a specific node. If afterNodeId is omitted, the steps are appended only when the sequence has exactly one linear tail. Inserted email steps require subject plus blocks or html.",properties:{afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},steps:{type:"array",description:"New steps to insert. Supports emails, delays, create_discount actions, webhooks, and other supported sequence path node types.",items:R4}},required:["steps"]},emails:{type:"array",description:"Updated existing sequence emails. If you omit emailId/nodeId, items are matched by existing step order. This field does not create new steps; use insertSteps for insertion and include delay on inserted email steps when a timer is needed.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${U0}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${U0}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company 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. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${O1}${G9}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (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. Pass [] to remove all attachments."},...T4}}},steps:{type:"array",description:"Alias for emails. Supports the same fields and matching rules, and only edits existing email steps. Use insertSteps to create new steps.",items:{type:"object",properties:{emailId:{type:"string",description:"Optional target linked email template ID for a step. Use the emailId returned in get_sequence.sequence.emails."},nodeId:{type:"string",description:"Optional target action_email node ID for a step. Use the nodeId returned in get_sequence.sequence.emails."},name:{type:"string",description:"Updated step/template name"},subject:{type:"string",description:"Updated email subject"},previewText:{type:"string",description:"Updated preview text"},html:{type:"string",description:`Updated HTML content for imported provider markup. ${U0}`},htmlContent:{type:"string",description:`Alias for html. ${U0}`},emailPreset:{type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails that contain supported custom HTML blocks. Minimal removes the company logo and uses the simple footer; branded restores the branded chrome. Does not change the company 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. Not supported when the entire email is standalone raw HTML and must not be combined with html/htmlContent."},blocks:{type:"array",description:`${O1}${G9}`,items:{type:"object"}},isTransactional:{type:"boolean"},ccEmails:{type:"array",items:{type:"string"}},bccEmails:{type:"array",items:{type:"string"}},attachments:{type:"array",items:{type:"object",properties:{filename:{type:"string"},path:{type:"string"}},required:["filename","path"]},description:"URL-backed file attachments for this email step (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. Pass [] to remove all attachments."},...T4}}},smsSteps:{type:"array",description:"Content updates for existing SMS steps, targeted by nodeId (an action_sms node from get_sequence.sequence.nodes). Content-only edits - use insertSteps to create new SMS steps.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_sms node ID. Required."},text:{type:"string",description:"Replacement plain-text message body. Merge tags like {{FIRST_NAME}} work. Provide text or blocks, not both."},blocks:{type:"array",items:{type:"object"},description:"Replacement SMS content blocks (text + image subset)."},imageUrls:{type:"array",items:{type:"string"},description:"Up to 2 publicly reachable MMS image URLs. Only valid together with text."},label:{type:"string",description:"Updated display label for the step."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"Updated behavior when the contact can't receive SMS."}},required:["nodeId"]}},subscriberUpdateSteps:{type:"array",description:"Full config replacements for existing Update Subscriber steps, targeted by action_update_attributes nodeId.",items:{type:"object",properties:{nodeId:{type:"string",description:"Target action_update_attributes node ID."},config:I6},required:["nodeId","config"]}}},required:["sequenceId"]}},{name:"update_sequence_node",description:"Patch one existing sequence node in place. Call get_sequence first, select sequence.nodes[].id, inspect nodeType/config, and pass that node's updatedAt as expectedUpdatedAt. This supports every stored sequence node type, including delays, email/SMS content, actions, conditions, branches without topology changes, webhooks, and trigger settings. Delay example: changes:{ delay:{ days:7 } }. For a direct text-forward email, use changes:{ emailPreset:'minimal' } on its action_email node; this changes only that linked email's Style > Format. The update is type-aware and preserves fields you omit. It cannot change nodeType, managed linked-resource IDs, or graph topology; use edit_sequence_graph for structural work. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamp; the new delay applies when recipients reach the node in the future.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},nodeId:w9.properties.nodeId,changes:i8,expectedUpdatedAt:w9.properties.expectedUpdatedAt,confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing a node in an active sequence."}},required:["sequenceId","nodeId","changes","expectedUpdatedAt"],additionalProperties:!1}},{name:"update_sequence_nodes",description:"Atomically patch multiple existing sequence nodes. Call get_sequence first and include each node's id plus its updatedAt as expectedUpdatedAt. Every patch follows update_sequence_node's type-aware rules. Either every node update commits or none do, making this the preferred tool for changes such as replacing all 5-minute delays with 7-day delays or setting several action_email nodes to changes:{ emailPreset:'minimal' } without changing the company theme. A node may appear only once. It cannot change node types or graph topology. On an active sequence, set confirmLiveChange:true only after the user confirms the live behavior change. Existing recipients already waiting keep their scheduled timestamps.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},updates:{type:"array",description:"Non-empty node patches. Each nodeId may appear only once.",items:w9},confirmLiveChange:{type:"boolean",description:"Set true only after the user explicitly confirms changing nodes in an active sequence."}},required:["sequenceId","updates"],additionalProperties:!1}},{name:"edit_sequence_graph",description:"Restructure an existing sequence graph using node IDs, edges, and graphRevision from get_sequence. move_node repositions one non-split step; duplicate_node creates an independent copy; delete_node safely splices a node and immediately moves parked recipients to its unique surviving successor (or completes them when none remains); replace_edges replaces the complete topology. The returned sequence reports migratedRecipientCount and completedRecipientCount. Always call get_sequence immediately before this tool and pass its graphRevision. Active sequences require confirmStructuralChange:true after the user confirms live-flow impact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},action:{type:"string",enum:["move_node","delete_node","duplicate_node","replace_edges"],description:"Graph operation."},graphRevision:{type:"string",description:"Exact graphRevision returned by the latest get_sequence call. The edit is rejected if the graph changed since then."},nodeId:{type:"string",description:"Existing node to move, duplicate, or delete. Unused by replace_edges."},afterNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately after this node. The target must have at most one outgoing path. Provide exactly one of afterNodeId or beforeNodeId."},beforeNodeId:{type:"string",description:"For move_node or duplicate_node, insert immediately before this node. All incoming paths converge through the moved/copied node, which is useful for placing a step below a branch. Provide exactly one of beforeNodeId or afterNodeId."},edges:{type:"array",description:"Complete replacement topology from get_sequence.sequence.edges. The returned edge array is already normalized for this input and can be reused directly. Required for replace_edges and when deleting a split node. Preserve each branch edge's condition.branchId. Do not include edges that reference a deleted node.",items:{type:"object",properties:{sourceNodeId:{type:"string"},targetNodeId:{type:"string"},condition:{type:"object",description:"Optional edge routing condition. Preserve condition.branchId on edges leaving logic_branch nodes."}},required:["sourceNodeId","targetNodeId"],additionalProperties:!1}},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."}},required:["sequenceId","action","graphRevision"],additionalProperties:!1}},{name:"insert_sequence_step",description:"Insert one dashboard-compatible typed step into an existing sequence: email, SMS, delay/date wait, discount (later emails print the generated code with {{discount.code}}), subscriber update, tag/list action, outbound webhook, AI step (later steps use the generated text with {{ai.KEY.field}}), condition gate, wait-for-event, or wired If/Else branch. Use get_sequence first and pass afterNodeId. Branch paths can target existing nodes, including completion. To nest a branch inside a branch path, end that path with the step the nested branch should follow, then call insert_sequence_step again with type 'logic_branch' and afterNodeId set to that path node - addedBranchPathNodeIds in the response lists each path's node IDs in order, and the nested paths reconnect to the shared steps that already followed it. A logic_branch with splitMode 'random' plus randomPercentages is a weighted split rather than an If/Else, so it runs a concurrent A/B test inside the flow - use it to compare two offers in the same abandoned-cart sequence instead of running duplicate sequences one after another. To A/B test the content of one existing email step and have a winner picked automatically, use create_ab_test with automationNodeId instead. For active sequences, confirm the structural change first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."},type:{type:"string",enum:["email","sms","delay","create_discount","update_subscriber","add_tag","remove_tag","add_to_list","remove_from_list","webhook","ai","condition","logic_wait_for_event","logic_branch"],description:"Dashboard step type. Defaults to email."},afterNodeId:{type:"string",description:"Existing node ID to insert after. Use a nodeId from get_sequence.sequence.nodes or get_sequence.sequence.emails. Omit only to append to an unambiguous linear tail."},confirmStructuralChange:{type:"boolean",description:"Set true only after the user explicitly confirms a structural edit to an active sequence."},name:{type:"string",description:"Optional email template and step name."},subject:{type:"string",description:"Email subject for the new step. Required for email steps; not used for SMS steps."},previewText:{type:"string",description:"Optional email preview text for the new step."},blocks:{type:"array",description:Z6,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${U0}`},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 in addition to sequence-level 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."},senderProfileId:{type:"string",description:"Email steps only: sender profile for the new 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:"Email steps only: From address for the new step. Its domain must be verified. Mutually exclusive with senderProfileId."},fromName:{type:"string",description:"Email steps only: display name override for the new step. With fromEmail, also names a newly created sender profile."},replyProfileId:{type:"string",description:"Email steps only: reply profile for the new 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. Mutually exclusive with replyTo."},replyTo:{type:"string",description:"Email steps only: Reply-To address for the new step. Mutually exclusive with replyProfileId."},replyToName:{type:"string",description:"Email steps only: Reply-To display name override for the new step. Requires replyTo; omit it when using replyProfileId, which already carries its own display name."},text:{type:"string",description:"SMS steps only: plain-text message body. Merge tags like {{FIRST_NAME}} work. Do not include opt-out text or a brand prefix - the platform adds those automatically."},imageUrls:{type:"array",items:{type:"string"},description:"SMS steps only: up to 2 publicly reachable image URLs sent as MMS media."},label:{type:"string",description:"Display label for SMS, wait-for-event, or branch steps."},ineligibleAction:{type:"string",enum:["skip","exit"],description:"SMS steps only: what happens when the contact can't receive SMS (no phone, not opted in, unsupported country). Default 'skip' continues the sequence."},config:{...I6,description:"update_subscriber only: typed subscriber profile/custom-attribute changes."},tagId:{type:"string",description:"Tag ID for tag actions or tag conditions."},tagName:{type:"string",description:"Tag name for tag actions or tag conditions; missing definitions are created."},listId:{type:"string",description:"List ID for list actions or in_list conditions."},listName:{type:"string",description:"Optional cached list display name for list actions."},url:{type:"string",description:"webhook only: destination HTTPS URL called when a subscriber reaches this step. Supports merge tags like {{email}} and {{event.order_id}}."},method:{type:"string",enum:["POST","GET","PUT","PATCH","DELETE"],description:"webhook only: HTTP method. Defaults to POST."},headers:{type:"object",description:"webhook only: optional string-valued request headers. Values support merge tags. Secret values are redacted on sequence reads.",additionalProperties:{type:"string"}},body:{type:"string",description:'webhook only: 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:"webhook / 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 ai steps. Must start with a letter; letters, numbers, underscores; max 64 chars."},onError:{type:"string",enum:["continue","exit","fail"],description:"webhook / 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."},prompt:{type:"string",description:"ai only: prompt template sent to the model, resolved per contact at execution time. Ask for the short per-contact fragments the output fields name (a sentence or two each), never a whole email - the email around them is authored separately. Supports merge tags like {{first_name}}, {{event.plan}}, and {{webhooks.KEY.data.field}}. Max 8000 chars."},outputFields:{type:"array",description:"ai only: 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. 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. Letters, numbers, underscores; must start with a letter; unique within the step."},description:{type:"string",description:"What the model should produce for this field. Max 300 chars."},maxLength:{type:"integer",minimum:1,maximum:4000,description:"Hard cap on stored characters (1-4000). Defaults to 500."},fallback:{type:"string",description:"Text used verbatim when generation fails or the model omits the field."}},required:["key"],additionalProperties:!1}},includeTags:{type:"boolean",description:"ai only: include the contact's tags in the prompt context."},includeEventProperties:{type:"boolean",description:"ai only: include the enrollment's trigger event name and properties in the prompt context."},includeRecentEvents:{type:"boolean",description:"ai only: include the contact's most recent custom events (newest first) in the prompt context."},recentEventLimit:{type:"number",description:"ai only: how many recent events to include when includeRecentEvents is true (1-50, default 10)."},includeAttributes:{type:"array",items:{type:"string"},description:"ai only: custom attribute keys to include in the prompt context (max 30). Only the listed keys are sent."},segmentId:{type:"string",description:"Segment ID for in_segment conditions."},segmentName:{type:"string",description:"Optional cached segment display name."},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 only: condition evaluated before continuing."},linkUrl:{type:"string"},activityScope:{type:"string",enum:["ever","this_sequence","previous_email"]},fieldName:{type:"string"},fieldValue:{type:"string"},delay:V6,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:K6,waitUntilWeekday:P6,eventName:{type:"string",description:"logic_wait_for_event only: event to wait for, for example email.replied."},timeoutDays:{type:"number",description:"logic_wait_for_event only: maximum wait in whole days from 1 to 365. Defaults to 7."},timeoutAction:{type:"string",enum:["continue","exit"],description:"logic_wait_for_event only: continue to the next node or exit the sequence when the timeout is reached. Defaults to continue."},discount:{type:"object",description:"create_discount only: provider discount configuration.",additionalProperties:!0},provider:{type:"string",enum:["stripe","shopify"]},discountType:{type:"string",enum:["percent","amount"]},percentOff:{type:"number"},amountOff:{type:"number"},currency:{type:"string"},duration:{type:"string",enum:["once","forever","repeating"]},durationInMonths:{type:"number"},appliesToAllPlans:{type:"boolean"},planIds:{type:"array",items:{type:"string"}},codePrefix:{type:"string"},maxRedemptions:{type:"number"},lockToSubscriber:{type:"boolean"},expiresAt:{type:"string"},expiresInHours:{type:"number"},splitMode:JQ,randomPercentages:wQ,branches:{type:"array",description:`logic_branch only: ${XQ}`,items:GQ},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path. Not valid on a random split.",items:R4},elseTargetNodeId:{type:"string",description:"logic_branch only: existing node for the else path, such as the original follow-up node or completion node."},allowEmptyPaths:{type:"boolean",description:"logic_branch only: set true only to create empty dashboard placeholders. Explicit target nodes do not require it."}},required:["sequenceId"],additionalProperties:!1}},{name:"enable_sequence",description:"Enable/activate a sequence. IMPORTANT: Only call this when the user EXPLICITLY asks to enable or activate a sequence. Never enable sequences automatically after creation - the user must review the content first.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"disable_sequence",description:"Disable/freeze a sequence. This blocks new enrollments and holds current recipients until the sequence is enabled again. To only stop new enrollments while current recipients continue, use pause_sequence_enrollments.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"duplicate_sequence",description:"Create an independent draft copy of a sequence, including its graph, email templates, and sequence A/B tests. The original is not changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to copy."},name:{type:"string",description:"Optional name for the copy. Defaults to the original name plus (Copy)."}},required:["sequenceId"]}},{name:"archive_sequence",description:"Archive a sequence and stop new enrollments. Archived sequences remain available in the dashboard's archive.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to archive."}},required:["sequenceId"]}},{name:"unarchive_sequence",description:"Restore an archived sequence as a disabled draft so it can be reviewed before activation.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Archived sequence ID to restore."}},required:["sequenceId"]}},{name:"pause_sequence_enrollments",description:"Stop new enrollments for an active sequence while current recipients continue through the sequence. This matches the dashboard 'Stop new enrollments' control and does not freeze current recipients.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"resume_sequence_enrollments",description:"Resume new enrollments for an active sequence whose enrollment gate was paused. Use enable_sequence instead for a fully disabled/frozen sequence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}},{name:"enroll_subscribers_in_sequence",description:"Manually enroll subscribers in a sequence by email address or subscriber ID. Maximum 500 total targets per call across emails and subscriberIds. Only active subscribers are enrolled: unknown emails are returned in `notFound`, while inactive, unavailable, and already actively enrolled subscribers are counted in `skipped`. By default enrollment starts at the first step after the trigger; pass targetNodeId to start at a specific step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID to enroll subscribers in."},emails:{type:"array",items:{type:"string"},description:"Email addresses of subscribers to enroll. Combined with subscriberIds, maximum 500 total targets per call."},subscriberIds:{type:"array",items:{type:"string"},description:"Subscriber IDs to enroll. Combined with emails, maximum 500 total targets per call."},targetNodeId:{type:"string",description:"Optional node ID to start enrollment at. Use a non-trigger nodeId from get_sequence. Defaults to the first step after the trigger."}},required:["sequenceId"]}},{name:"cancel_sequence_enrollments",description:"Cancel active/waiting enrollments in one sequence. Provide sequenceId and exactly one target: cancelAll to drain every active/waiting enrollment (use this to fully stop a live sequence instead of only freezing enrollment), subscriberIds for a specific batch, subscriberId for one subscriber, or fieldValues to match stored entry event properties. Every bulk target defaults to dryRun, so pass dryRun false to actually cancel. Bulk cancellation is capped per call: while the response reports remainingCount above zero, call again with the same arguments until it reaches zero.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be cancelled."},cancelAll:{type:"boolean",description:"Cancel every active/waiting enrollment in the sequence, regardless of how contacts entered it. Use this when segment-triggered enrollments expose no shared entry field value. Defaults to dryRun; pass dryRun false to apply."},subscriberId:{type:"string",description:"Subscriber ID to cancel in this sequence. Provide exactly one target."},subscriberIds:{type:"array",items:{type:"string"},description:"Up to 500 subscriber IDs to cancel in this sequence. IDs that do not resolve come back in target.notFoundSubscriberIds. Provide exactly one target."},fieldPath:{type:"string",description:"Dot-path inside the token's stored entry event properties, such as order.id or event.id. Optional when the sequence has enrollmentFieldPath configured."},fieldValues:{type:"array",items:{type:"string"},description:"Entry field values to match. Cancels all active/waiting enrollments in the sequence whose entry field value is in this list. Provide exactly one target."},dryRun:{type:"boolean",description:"When true, returns matching enrollments without cancelling them. cancelAll, subscriberIds, and fieldValues default to dryRun unless explicitly false; a single subscriberId cancels immediately."},reason:{type:"string",description:"Optional cancellation reason stored on matched enrollment tokens."}},required:["sequenceId"],additionalProperties:!1}},{name:"move_sequence_enrollments",description:"Release a bounded batch of contacts off one sequence step and onto another, keeping their existing enrollment. Use this to let the next N contacts waiting on a delay continue early instead of cancelling and re-enrolling them, which discards the enrollment's entry event properties and stop-condition snapshots. Provide sequenceId and fromNodeId; targetNodeId defaults to the source step's only next step. Defaults to dryRun, so pass dryRun false to actually move. Moved contacts become active on the target step immediately, so this sends email as soon as the worker picks them up. limit defaults to 100 and is capped at 500 per call: while remainingCount is above zero, call again to release more. Unlike enroll_subscribers_in_sequence this still works while the sequence has new enrollment paused, because the contacts are already enrolled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose enrollments should be moved."},fromNodeId:{type:"string",description:"Node ID the contacts are currently sitting on, such as the delay step they are waiting at. Get it from list_sequence_enrollments (currentNodeId) or get_sequence."},targetNodeId:{type:"string",description:"Node ID to move them onto. Defaults to the source step's next step, and is required when that step branches or is terminal. Cannot be the trigger node."},limit:{type:"number",description:"Maximum enrollments to move in this call. Defaults to 100, maximum 500."},sort:{type:"string",enum:["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"],description:"Which enrollments to take first. Defaults to wait_until_asc, meaning the contacts that have been waiting longest for their next step."},subscriberIds:{type:"array",items:{type:"string"},description:"Optional narrowing filter: only move these subscribers, up to 500. Omit to take whichever enrollments the sort selects."},dailyLimit:{type:"number",description:"Guardrail. Refuses to move more than this many enrollments onto targetNodeId in a rolling 24 hours, counting the moves recorded by earlier calls. The response reports movedInWindow and dailyRemaining so a paced release can resume tomorrow."},tags:{type:"array",items:{type:"string"},description:"Tag names applied to the moved contacts so the released wave stays identifiable. The tags must already exist (create_tag). Requires the subscribers:tag scope. Applying them never enrolls contacts in tag_added sequences."},reason:{type:"string",description:"Note stored on every moved enrollment and returned by list_sequence_enrollments as moveReason."},dryRun:{type:"boolean",description:"When true (the default), reports which enrollments would move without moving them. Pass false to apply."}},required:["sequenceId","fromNodeId"],additionalProperties:!1}},{name:"realign_sequence_enrollments",description:"Pull waiting enrollments forward to the start of the sequence's sending window on the day they are already scheduled for. Use this after changing sendingWindow (or a wait-until-weekday step) on a live sequence: node and sequence updates deliberately keep existing wait timestamps, so contacts already parked on an email-bound delay keep resuming at whatever minute their delay landed on, and a narrowed window silently defers them to the NEXT allowed day. Non-email actions are never advanced by the sequence sending window. Realignment never cancels, re-enrolls, or reschedules onto a different local day, and never pushes a contact later - a wait only ever moves earlier within the day it already has, and never earlier than now. Defaults to dryRun. Passing dryRun false queues a background apply and returns jobId; call get_sequence_enrollment_realignment until it completes. Each completed job is capped: when result.hasMore is true, queue another apply with result.nextCursor as cursor.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID whose waiting enrollments should realign."},nodeIds:{type:"array",items:{type:"string"},description:"Optional step IDs to limit realignment to. Use nodeIds from get_sequence, or currentNodeId values from list_sequence_enrollments. Defaults to every step."},subscriberIds:{type:"array",items:{type:"string"},description:"Optional subscriber IDs to limit realignment to (maximum 500). Defaults to every waiting contact."},cursor:{type:"string",description:"Opaque continuation cursor. When a response has hasMore true, pass its nextCursor here to continue after the enrollments already scanned."},dryRun:{type:"boolean",description:"When true (the default), reports the new wait times without writing them. Pass false to apply."}},required:["sequenceId"],additionalProperties:!1}},{name:"get_sequence_enrollment_realignment",description:"Check a queued sequence enrollment realignment. Call this with the jobId returned by realign_sequence_enrollments after applying with dryRun false. When status is completed, result contains the realignment counts, sample, and any nextCursor needed for another bounded apply call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID used when the realignment was queued."},jobId:{type:"string",description:"Realignment job ID returned by realign_sequence_enrollments."}},required:["sequenceId","jobId"],additionalProperties:!1}},{name:"delete_sequence",description:"Delete a sequence",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID"}},required:["sequenceId"]}}];var LM={type:"object",properties:{email:{type:"string",description:"Subscriber email address. Optional when the record has a phone - such rows import as phone-only (SMS) contacts."},externalId:{type:"string",description:"Customer-owned subscriber ID"},firstName:{type:"string"},lastName:{type:"string"},phone:{type:"string",description:"Phone number. National-format values use the batch defaultPhoneCountry."},status:{type:"string",enum:["active","unsubscribed","bounced"]},tags:{type:"array",items:{type:"string"}},customAttributes:{type:"object",description:"CRM fields and other custom attributes. Values may be strings, numbers, booleans, arrays of those scalar values, or null.",additionalProperties:!0},createdAt:{type:"string",description:"Original signup date (ISO 8601) from the source platform. Set this when migrating so date-relative segments are correct immediately rather than treating every imported contact as having joined today. An existing contact's date only ever moves earlier."}},required:[],additionalProperties:!1},_3=[{name:"add_subscriber",description:"Add one subscriber. Status is only applied when creating a new contact; use update_subscriber to change an existing contact's status. For multiple contacts or CRM records, use create_subscriber_import instead of looping this tool. For an email-only batch going into one list, add_subscribers_to_list is also available.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to add subscriber to. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Optional when phone is provided - a contact created with only a phone becomes a phone-only (SMS) contact."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide this with email when creating, or instead of email for an existing subscriber."},phone:{type:"string",description:"Phone number in E.164 or national format, stored as a native profile field. With no email, creates or matches a phone-only (SMS) contact."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number. Never inferred from phone presence."},firstName:{type:"string",description:"Subscriber first name, stored as a native profile field."},lastName:{type:"string",description:"Subscriber last name, stored as a native profile field."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Use firstName/lastName for names instead of attributes."},tags:{type:"array",items:{type:"string"},description:"Tags to apply to the subscriber"},listIds:{type:"array",items:{type:"string"},description:"List IDs to add subscriber to"},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"Initial subscriber status: active, unsubscribed, or bounced. Defaults to active and does not change an existing contact; use update_subscriber for existing contacts."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Consent mode: confirmed creates active immediately when consent is verified, double_opt_in sends a confirmation email before activation, and default obeys company double opt-in settings."},createdAt:{type:"string",description:"Original signup date (ISO 8601) when importing a contact from another platform. Preserves their real history so date-relative segments like 'added in the last 30 days' are correct immediately instead of treating every imported contact as brand new. An existing contact's date only ever moves earlier. Supplying this also stops welcome sequences from firing, since it describes the past rather than a signup happening now."}},required:[]}},{name:"create_subscriber_import",description:"Queue one CRM-grade subscriber import with up to 5,000 full contact records. Supports names, external IDs, phones, statuses, tags, lists, and custom attributes. Prefer this over repeated add_subscriber calls. Returns an import ID for get_subscriber_import. Use optInMode='confirmed' only when the contacts already gave verified email consent.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},subscribers:{type:"array",minItems:1,maxItems:5000,items:LM,description:"Full subscriber records to import in one batch."},duplicateStrategy:{type:"string",enum:["skip","merge","overwrite"],description:"How existing contacts are handled. Defaults to skip. Merge fills missing fields; overwrite replaces public fields without reactivating unsubscribed contacts."},fileName:{type:"string",description:"Optional source label shown in import history, such as copper-export.csv."},listIds:{type:"array",items:{type:"string"},description:"Lists to add every successfully imported active subscriber to."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll imported contacts. Defaults to false and requires automations:trigger."},defaultPhoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used for national-format phone numbers, such as SG or US."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for every imported phone number."},optInMode:{type:"string",enum:["default","confirmed","double_opt_in"],description:"Email consent mode. Default follows workspace double opt-in settings. Confirmed creates active contacts immediately and must only be used for verified consent. Double_opt_in may send confirmation email and requires automations:trigger."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},importId:{type:"string",description:"Import ID or batch ID returned by create_subscriber_import."}},required:["importId"]}},{name:"update_subscriber",description:"Update an existing subscriber's profile, phone, status, attributes, or tags. Names and phones are native profile fields - set them here rather than as custom attributes. Setting status to unsubscribed suppresses the contact from all marketing, deactivates list memberships, and cancels active sequence enrollments while preserving the record and suppression history.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},firstName:{type:"string",description:"New first name, stored as a native profile field. Pass an empty string to clear it."},lastName:{type:"string",description:"New last name, stored as a native profile field. Pass an empty string to clear it."},phone:{type:"string",description:"New phone number in E.164 or national format, stored as a native profile field. Pass an empty string to clear it, which is rejected for a phone-only (SMS) contact that has no email. Changing the number resets SMS consent unless smsConsent is sent in the same call."},phoneCountry:{type:"string",description:"ISO 3166-1 alpha-2 country used to read a national-format phone number, such as IT or US. Defaults to US. Only send it together with phone; the stored country always comes from the parsed number."},smsConsent:{type:"boolean",description:"Set true only when express written SMS marketing consent was verified for this phone number; false unsubscribes them from SMS. Omitting this leaves consent unchanged unless phone changes, which resets consent because it belonged to the old number. Consent is never inferred from phone presence."},status:{type:"string",enum:["active","unsubscribed","bounced"],description:"New global subscriber status. Use unsubscribed for compliance-grade suppression without deleting the record. Use active only when the contact has valid consent to be resubscribed."},attributes:{type:"object",description:"Custom attributes to update. Use firstName/lastName for names instead of attributes."},addTags:{type:"array",items:{type:"string"},description:"Tags to add"},removeTags:{type:"array",items:{type:"string"},description:"Tags to remove"}},required:[]}},{name:"remove_subscriber",description:"Unsubscribe a subscriber while preserving the record and suppression history. Only permanently deletes when hardDelete is true.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},hardDelete:{type:"boolean",description:"If true, permanently deletes the subscriber and suppression history. Defaults to false, which globally unsubscribes the contact, deactivates list memberships, and cancels active sequence enrollments."}},required:[]}},{name:"get_subscriber",description:"Get the full subscriber profile, including tags, notes, list memberships, sequence enrollments, email stats, and recent activity. For commerce customers, customAttributes include nightly predictive analytics: predictedLtv (next-12-month spend), churnRisk (percent), expectedNextOrderAt, avgDaysBetweenOrders, and predictionConfidence.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},includeMachineEngagement:h0},required:[]}},{name:"list_subscriber_notes",description:"List internal notes for a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."}},required:[]}},{name:"add_subscriber_note",description:"Add an internal note to a subscriber. Provide email or externalId to identify the subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},body:{type:"string",description:"Internal note body, up to 5000 characters."}},required:["body"]}},{name:"delete_subscriber_note",description:"Delete one internal subscriber note by note ID.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},noteId:{type:"string",description:"Subscriber note ID to delete."}},required:["noteId"]}},{name:"trigger_subscriber_event",description:"Emit a custom event for one subscriber, exactly as an integration or the public API would. This is the supported way to exercise event triggers, matching-field idempotency, branch conditions, and stop conditions end to end without waiting for real traffic. The event is recorded, sync rules apply, and matching event_received sequences enroll. Creates the subscriber if they do not exist. Use trigger_subscriber_events for several events on the same contact.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},event:{type:"string",description:"Event name, such as saas.purchase or invoice.paid. The event definition is created if it does not exist."},properties:{type:"object",description:"Event properties. Include the sequence's matching field (for example order.id or invoice.id) when testing idempotency or cancellation by field value.",additionalProperties:!0},firstName:{type:"string",description:"First name applied to the subscriber profile."},lastName:{type:"string",description:"Last name applied to the subscriber profile."},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). Omit for live events. If this is more than an hour in the past the event is recorded as history: it is stored with its real timestamp and counts for segments and the timeline, but no sequences enroll, no sync rules apply, no waiting steps resume, and no webhooks fire. A historical event also moves the contact's signup date back to when it occurred (never later), so imported contacts do not read as added today. Use this when backfilling from another platform - never to fake a live event, since the side effects you are testing will not run."},eventId:{type:"string",description:"Your own id for this event, used as an idempotency key on both paths. For a live event, re-sending an id this contact already has for this event name writes nothing, runs no side effects, and returns the existing event with duplicate: true. For a historical event, the response remains historical: true and reports the skipped row in duplicates instead. Live deduplication is best-effort for calls sent within about a second of each other, so a producer that needs a strict guarantee should also keep its own ledger."}},required:["event"]}},{name:"trigger_subscriber_events",description:"Emit several custom events for one subscriber in order. Events are processed independently and sequentially, so a partial failure can still leave earlier events recorded.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Subscriber email address. Provide email or externalId to identify the subscriber."},externalId:{type:"string",description:"Customer-owned subscriber ID. Provide email or externalId to identify the subscriber."},events:{type:"array",minItems:1,maxItems:500,items:{type:"object",properties:{name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:"string",description:"When the event actually happened (ISO 8601). When every event in the batch is more than an hour old the batch is imported as history in one idempotent write, with no sequences, sync rules, waiting steps or webhooks; the contact's signup date also moves back to the earliest event in the batch (never later)."},eventId:{type:"string",description:"Your own id for this event, making a re-run idempotent on both the live and historical paths."}},required:["name"],additionalProperties:!1},description:"Events to trigger, in order, for this subscriber."},firstName:{type:"string"},lastName:{type:"string"},attributes:{type:"object",description:"Custom attributes to set on the subscriber.",additionalProperties:!0}},required:["events"]}},{name:"bulk_add_subscriber_tags",description:"Add tags to up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Built for reconciling historical or derived tags: subscribers that do not exist are reported in notFound instead of being created, and tag automations do NOT run unless triggerAutomations is true. Needs the subscribers:tag scope; a tag name that does not exist yet also needs tags:write. The agent_safe key preset includes both. Use add_subscriber or update_subscriber for single-contact changes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to add to every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to tag. Combine with externalIds/subscriberIds as needed; at least one identifier list is required."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to tag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to tag."},triggerAutomations:{type:"boolean",description:"Whether tag_added sequences may enroll these contacts. Defaults to false, which is what backfills want. Requires the automations:trigger scope."}},required:["tags"]}},{name:"bulk_remove_subscriber_tags",description:"Remove tags from up to 500 existing subscribers in one call, identified by emails, externalIds, or subscriberIds. Subscribers that do not exist are reported in notFound. Needs the subscribers:tag scope; the broader subscribers:write scope also satisfies it. Use this to roll back or reconcile a derived-tag backfill.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tags:{type:"array",minItems:1,items:{type:"string"},description:"Tag names to remove from every matched subscriber."},emails:{type:"array",items:{type:"string"},description:"Subscriber emails to untag."},externalIds:{type:"array",items:{type:"string"},description:"Customer-owned subscriber IDs to untag."},subscriberIds:{type:"array",items:{type:"string"},description:"Sequenzy subscriber IDs to untag."}},required:["tags"]}},{name:"search_subscribers",description:"Search subscribers by free-text query, tags, list, segment, custom attribute, or opt-out date. Each subscriber carries unsubscribedAt, the date the contact opted out - use it rather than updatedAt, which any later tag or attribute write overwrites. If you omit limit, the tool fetches all pages and returns every match in one call - that is the fastest way to enumerate an audience. To walk a large audience in chunks instead, pass limit and then follow pagination.nextCursor (or pagination.nextOffset) until pagination.hasMore is false. Default searches are newest first; searches with attribute use stable subscriber-ID ascending order.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},query:{type:"string",description:"Search query. A whole email address is matched exactly against the contact's email or external ID; anything shorter is a substring search across email, external ID, name, and tags. Prefer a whole address when you know it - it is an indexed lookup, while a partial term has to examine the entire audience."},tags:{type:"array",items:{type:"string"},description:"Filter by tags"},list:{type:"string",description:"Filter by subscriber list ID or exact list name. Prefer listId when known."},listId:{type:"string",description:"Filter by subscriber list ID."},listName:{type:"string",description:"Filter by exact subscriber list name when the list ID is not known."},segmentId:{type:"string",description:"Filter by segment ID"},status:{type:"string",description:"Filter by subscriber status: active, unsubscribed, or bounced."},unsubscribedAfter:{type:"string",description:"Only return contacts whose opt-out is on or after this ISO 8601 date/datetime. Bare dates use UTC midnight; datetimes must include Z or an explicit offset. Contacts with no opt-out date are excluded: active contacts, and contacts imported as already unsubscribed."},unsubscribedBefore:{type:"string",description:"Only return contacts whose recorded opt-out is on or before this ISO 8601 date/datetime. Bare dates use UTC midnight; datetimes must include Z or an explicit offset. Combine with unsubscribedAfter to audit a window of opt-outs."},attribute:{type:"string",description:'Filter by custom attribute name, e.g. "plan". Pair with attributeValue and attributeOperator. The wire form "name:value" is also accepted. Cannot be combined with segmentId - use a saved segment for compound attribute filters.'},attributeValue:{type:"string",description:"Value the custom attribute is compared against. Omit only when attributeOperator is is_not_empty."},attributeOperator:{type:"string",enum:[...X9],description:"How to compare the custom attribute. Defaults to is. Use is_not_empty to match every subscriber that has the attribute set to any value. For is_not, not_contains, or is_empty, create a segment and pass segmentId instead."},limit:{type:"number",minimum:1,description:"Maximum results to return. If omitted, the tool returns all matches across pages."},offset:{type:"number",minimum:0,maximum:999999,description:"Number of matches to skip before returning results, up to 999999. Use with limit to page through a large audience; follow pagination.nextOffset from the previous response, then switch to nextCursor for deeper pagination."},page:{type:"number",description:"1-based page number, an alternative to offset. Requires limit, which defines the page size. Cannot be combined with offset."},cursor:{type:"string",description:"pagination.nextCursor from the previous response. The cheapest way to walk a large audience in chunks, because the server does not re-scan the rows already returned. Cannot be combined with offset or page."}}}}];var x3={companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Exact recipient email address to inspect or clean up."},region:{type:"string",description:"Optional AWS SES region such as us-east-1. Omit to check every SES region currently used by the company."}},h3=[{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards or the regional Amazon SES account-level suppression list. This exact-address lookup never exposes other recipients from the shared SES account.",inputSchema:{type:"object",properties:x3,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove stale bounce suppression for an exact recipient associated with the company. Clears matching Amazon SES bounce entries and Sequenzy's local bounce block, then reactivates bounced company subscribers. Complaint and unsubscribe protections are never removed.",inputSchema:{type:"object",properties:x3,required:["email"],additionalProperties:!1}}];var y3=[{name:"list_tags",description:"List all tags in the account",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list tags for. If not provided, uses the currently selected company."}}}},{name:"create_tag",description:"Create a new tag definition. The name is normalized to lowercase with hyphens (e.g. 'VIP Customer' becomes 'vip-customer'). Color defaults to gray.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Tag name. Normalized to lowercase with hyphens."},color:{type:"string",enum:[...j6],description:"Tag color. Defaults to gray."}},required:["name"]}},{name:"update_tag",description:"Update a tag's color. System tags cannot be updated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."},color:{type:"string",enum:[...j6],description:"New tag color."}},required:["tagId","color"]}},{name:"delete_tag",description:"Permanently delete a tag and remove it from all subscribers. This cannot be undone. System tags and tags used by sequences cannot be deleted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},tagId:{type:"string",description:"Tag ID. Use list_tags to find tag IDs."}},required:["tagId"]}},{name:"list_lists",description:"List all subscriber lists",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list lists for. If not provided, uses the currently selected company."}}}},{name:"create_list",description:"Create a new subscriber list",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the list in. If not provided, uses the currently selected company."},name:{type:"string",description:"List name"},description:{type:"string",description:"List description"}},required:["name"]}},{name:"update_list",description:"Update a subscriber list's name, description, or privacy. Only the provided fields are changed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to update."},name:{type:"string",description:"New list name."},description:{type:["string","null"],description:"New list description. Pass null to clear it."},isPrivate:{type:"boolean",description:"Whether the list is private."}},required:["listId"]}},{name:"delete_list",description:"Permanently delete a subscriber list and remove all of its memberships. Subscribers themselves are kept. This cannot be undone.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to delete."}},required:["listId"]}},{name:"add_subscribers_to_list",description:"Bulk add existing or new subscribers to a subscriber list from an email array. Existing subscribers are added to the list without requiring a per-subscriber update call.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to add subscribers to."},emails:{type:"array",items:{type:"string"},description:"Email addresses to add to the list. Maximum 500 per call."},duplicateStrategy:{type:"string",description:"Duplicate strategy for existing subscribers: skip, merge, or overwrite. Defaults to skip."},enrollInSequences:{type:"boolean",description:"Whether newly created subscribers should enroll in matching sequences. Defaults to false."},optInMode:{type:"string",description:"Consent mode for newly created subscribers: default, confirmed, or double_opt_in. Defaults to default."}},required:["listId","emails"]}},{name:"remove_subscribers_from_list",description:"Remove subscribers from a list by email address. Maximum 500 emails per call. Subscribers stay in the account; only the list membership is removed. Returns the removed count plus a notFound array of emails that did not match a subscriber.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},listId:{type:"string",description:"Subscriber list ID to remove subscribers from."},emails:{type:"array",items:{type:"string"},description:"Email addresses to remove from the list. Maximum 500 per call."}},required:["listId","emails"]}},{name:"list_segments",description:"List all segments",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to list segments for. If not provided, uses the currently selected company."}}}},{name:"create_segment",description:'Create a new segment from explicit filter rules. Use `filters` plus `filterJoinOperator` for flat legacy rules, or `root` for nested AND/OR groups such as `{ "kind": "group", "joinOperator": "and", "children": [{ "kind": "filter", "field": "attribute", "operator": "gte", "value": "mrr:50" }, { "kind": "group", "joinOperator": "or", "children": [{ "kind": "filter", "field": "tag", "operator": "contains", "value": "vip" }, { "kind": "filter", "field": "event", "operator": "is_not", "value": "saas.purchase:30d" }] }] }`. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign-specific engagement filters.',inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID to create the segment in. If not provided, uses the currently selected company."},name:{type:"string",description:"Segment name"},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:d8,minItems:1,description:'Array of segment filters. Example custom attribute empty check: [{"id":"filter-1","field":"attribute","operator":"is_empty","value":"last_logged_in:"}]. Example Stripe purchase filter: [{"id":"filter-1","field":"stripeProduct","operator":"is","value":"prod_123"}]. Example threshold filter: [{"id":"filter-1","field":"stripeProduct","operator":"at_least","value":"prod_123:3"}]. Example commerce product purchase filter (value is provider:productId since product ids are provider-scoped): [{"id":"filter-1","field":"commerceProduct","operator":"is","value":"api:prod-starter-kit"}]. Example repeat-buyer filter: [{"id":"filter-1","field":"commerceProduct","operator":"at_least","value":"shopify:42:2"}]. Example commerce collection filter (anyone who bought any product in the collection; value is a collection id or handle): [{"id":"filter-1","field":"commerceCollection","operator":"is","value":"skincare"}]. Example trial cancellation filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:is_canceled"}]. Example trial end filter: [{"id":"filter-1","field":"stripeTrialProduct","operator":"is","value":"prod_123:end_at:2026-05-26"}]. Example campaign-specific engagement combo: [{"id":"filter-1","field":"emailBounced","operator":"is","value":"campaign:cmp_abc"},{"id":"filter-2","field":"emailBounced","operator":"is_not","value":"campaign:cmp_xyz"}]. Combine them with `filterJoinOperator: "or"` to match any filter.'},root:{...o8,description:"Nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["name"]}},{name:"update_segment",description:"Update a segment's name and/or filter rules. Use the same `filters` plus `filterJoinOperator` or nested `root` shapes as create_segment; providing `filters` or `root` replaces the segment's existing rules.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to update."},name:{type:"string",description:"New segment name."},filterJoinOperator:{type:"string",enum:["and","or"],description:'How top-level filters combine. Use `"and"` to require every filter or `"or"` to match any filter.'},filters:{type:"array",items:d8,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...o8,description:"Replacement nested filter root. Mutually exclusive with `filters` and `filterJoinOperator`."}},required:["segmentId"]}},{name:"delete_segment",description:"Permanently delete a segment. This cannot be undone. Subscribers are not affected.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID to delete."}},required:["segmentId"]}},{name:"get_segment_count",description:"Get the number of subscribers in a segment",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},segmentId:{type:"string",description:"Segment ID"}},required:["segmentId"]}}];var f3=[{name:"list_team_members",description:"List team members for the company, including the owner, members with their roles, and pending or expired invitations.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"invite_team_member",description:"Invite a team member by email with role admin, viewer, or restricted. Existing Sequenzy users are added to the team immediately; others receive an email invitation. Billing access (canManageBilling) can only be granted by the company owner and is not available for restricted members.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},email:{type:"string",description:"Email address of the person to invite."},role:{type:"string",enum:["admin","viewer","restricted"],description:"Team role. Admins can manage the workspace; viewers have read-only access; restricted members can open direct campaign links only."},canManageBilling:{type:"boolean",description:"Whether the member can manage billing. Only the company owner can grant billing access. Defaults to false."}},required:["email","role"]}},{name:"cancel_team_invitation",description:"Cancel a pending team invitation. Invitations that have already been accepted cannot be cancelled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},invitationId:{type:"string",description:"Invitation ID to cancel. Use list_team_members to find pending invitations."}},required:["invitationId"]}}];var u3=[{name:"list_templates",description:"List the company's email bodies newest first, including per-locale localization sync status and each body's `emailPreset` Style > Format (branded or minimal; null for standalone raw HTML). Results include standalone templates plus the bodies behind campaigns and transactional emails. Returns 50 per call by default (100 max); page with offset while pagination.hasMore is true, and read pagination.total for the full count. You can also pass a campaign's emailId to get_template to fetch one body directly. Bodies are kept when their campaign or transactional email is deleted.",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."},limit:{type:"number",description:"Templates per page, 1-100. Defaults to 50."},offset:{type:"number",description:"Templates to skip before returning results. Add pagination.count to the current offset to fetch the next page while pagination.hasMore is true."}}}},{name:"get_template",description:"Get a template's details, content, and all localized variants with sync status. `emailPreset` reports the per-email Style > Format (branded or minimal; null when the whole email is standalone raw HTML) the same way get_sequence does per step.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"create_template",description:"Create a new email template. For net-new email content requested in natural language, use `prompt`; do not write HTML or construct blocks yourself. Use `blocks` only for finished caller-supplied Sequenzy content and `html` only for supplied or explicitly requested preserved HTML.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line. Optional with `prompt`."},previewText:{type:["string","null"],description:"Optional preview text override."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},prompt:{type:"string",description:"Natural-language request for Sequenzy to generate branded native template blocks."},style:{type:"string",description:"Generation style; valid only with `prompt`."},tone:{type:"string",description:"Generation tone; valid only with `prompt`."},labels:{type:"array",description:"Optional label names to assign. Missing labels are created automatically.",items:{type:"string"}}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` is required, and only those update fields are accepted.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"},name:{type:"string",description:"Template name"},subject:{type:"string",description:"Email subject line"},previewText:{type:["string","null"],description:"Inbox preview text. Send null to clear the existing preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. Use this for imported provider templates. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}},labels:{type:"array",description:"Replacement label names. Send an empty array to clear labels. Missing labels are created automatically.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"set_template_localization",description:"Create or replace one caller-supplied localized variant of a template. The locale must be enabled for the company and cannot be its primary locale. Provide exactly one of `html` or `blocks`.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locale:{type:"string",description:"Enabled non-primary locale code such as es, fr, or pt-BR."},subject:{type:"string",description:"Localized email subject line."},previewText:{type:["string","null"],description:"Optional localized inbox preview text."},html:{type:"string",description:`Localized email HTML. Mutually exclusive with \`blocks\`. ${U0}`},blocks:{type:"array",description:x0,items:{type:"object"}}},required:["templateId","locale","subject"],additionalProperties:!1}},{name:"sync_template_localizations",description:"Queue AI translation for selected template locales. Omit `locales` to sync every enabled non-primary locale. This works even when automatic on-save localization is disabled.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID, transactional email ID, or slug."},locales:{type:"array",description:"Optional enabled non-primary locale codes to sync. Omit to sync all enabled non-primary locales.",items:{type:"string"}}},required:["templateId"],additionalProperties:!1}},{name:"delete_template",description:"Delete a template",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Template ID"}},required:["templateId"]}},{name:"share_template",description:"Create (or fetch) the public view-in-browser link for an individual email - a transactional email, a sequence email, or a standalone template. Accepts an email/template ID or a transactional email's ID or slug; for a sequence email, pass the step's emailId from get_sequence. The hosted page renders an anonymized copy - sample contact, inert unsubscribe link, no open/click tracking - so the URL is safe to forward to anyone. Idempotent: if a link is already active, the same URL is returned with created=false rather than rotating it, so previously shared copies keep working. get_template reports the current link as shareUrl (null when none). Revoke with unshare_template. Campaigns have their own campaign-level link that follows the A/B winning variant - use share_campaign for those.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Email/template ID, or a transactional email's ID or slug."}},required:["templateId"],additionalProperties:!1}},{name:"unshare_template",description:"Revoke the email's public view-in-browser link. The shared URL returns 404 immediately, and sharing again later mints a different URL - previously distributed copies stay dead. Returns revoked=false if no link was active.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},templateId:{type:"string",description:"Email/template ID, or a transactional email's ID or slug."}},required:["templateId"],additionalProperties:!1}}];var c3=[{name:"list_transactional_emails",description:"List transactional email templates with subjects, delivery metrics, API slugs, and dashboard URLs. Each item also carries `emailPreset`, the per-email Style > Format (branded or minimal, null for a standalone raw HTML email), so a chrome drift check across templates does not need one get_transactional_email call each. Search by name, slug, or email title; filter active state; and sort by sends, opens, open rate, clicks, or CTR.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},search:{type:"string",description:"Case-insensitive search across template name, API slug, and linked email subject/title."},status:{type:"string",description:"Template status: all, active, or disabled."},sort:{type:"string",description:"Sort field: date, sends, opens, open-rate, clicks, or ctr. Defaults to date."},order:{type:"string",description:"Sort order: asc or desc. Defaults to desc."},includeMachineEngagement:{type:"boolean",description:"Include bot, scanner, and privacy-proxy engagement in open and click metrics. Defaults to false."}},additionalProperties:!1}},{name:"get_transactional_email",description:"Get a transactional email by ID or slug, including subject, preview text, blocks, variables, and linked dashboard URLs. `emailPreset` reports the per-email Style > Format the same way get_sequence does per step (branded or minimal; null when the whole email is standalone raw HTML), so it can be compared against sequence steps and campaigns without rendering them - minimal suppresses the company logo at render time.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"]}},{name:"create_transactional_email",description:"Create a saved transactional email template with an API slug. For net-new natural-language content use `prompt`; do not author HTML or blocks. `blocks` are finished caller-supplied Sequenzy content and `html` is preserved/imported markup.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Transactional email name."},slug:{type:"string",description:"Optional API slug used when sending by slug, for example `password-reset`. If omitted, Sequenzy generates one from the name."},subject:{type:"string",description:"Email subject line. Optional when `prompt` is provided because the generated subject will be used."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${U0}`},blocks:{type:"array",description:`${x0} Mutually exclusive with \`html\`.`,items:{type:"object"}},prompt:{type:"string",description:"Generate transactional email blocks from a prompt. Generated blocks include the company's branding (logo and a footer without an unsubscribe link). Mutually exclusive with `html` and `blocks`."},style:{type:"string",description:"Prompt generation style: minimal, branded, promotional. Only used with `prompt`."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},enabled:{type:"boolean",description:"Whether this transactional email can be sent immediately. Prompt-created templates default to false; explicit HTML/blocks retain the compatibility default of true."}},required:["name"],additionalProperties:!1}},{name:"update_transactional_email",description:"Update a transactional email by ID or slug. At least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` is required. Use `html` or `blocks` to replace the linked email body.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."},name:{type:"string",description:"Transactional email name."},enabled:{type:"boolean",description:"Whether this transactional email can be sent."},subject:{type:"string",description:"Email subject line."},previewText:{type:["string","null"],description:"Email preview text."},html:{type:"string",description:`Email HTML content. Mutually exclusive with \`blocks\`. ${U0}`},blocks:{type:"array",description:`${O1} Mutually exclusive with \`html\`.`,items:{type:"object"}}},required:["idOrSlug"],additionalProperties:!1}},{name:"delete_transactional_email",description:"Permanently delete a saved transactional email template by ID or slug. Use this to retire an obsolete template: the slug stops sending and becomes free to reuse. Already-sent deliveries and their stats are kept, so history and analytics survive the delete. The linked email content stays as a reusable template and comes back as `deleted.emailId`; pass that to `delete_template` to remove the content too. To stop sends without losing the template, call `update_transactional_email` with `enabled` set to false instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},idOrSlug:{type:"string",description:"Transactional email ID or API slug, for example `welcome-email`."}},required:["idOrSlug"],additionalProperties:!1}},{name:"send_email",description:"Queue one email using either a saved transactional email API slug (`templateId`) or direct `subject` and `html` content. The default delivery policy is transactional. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit variables take precedence. Set `emailType` to `marketing` to add subscriber suppression, a marketing footer, and RFC 8058 one-click unsubscribe. Company Reply-To defaults are inherited when no override is provided, and `{{viewInBrowserUrl}}` is replaced with a hosted copy URL. Attach up to 10 files with Base64 `content` or a public `path`; `contentId` embeds a CID image referenced by the HTML. Use `trackingSettings` with `clickTracking` or `openTracking` set to `false` to disable click-link rewriting or the open-tracking pixel for this send only; these opt-out fields cannot enable tracking the account has disabled. Returns a durable emailSendId and the accepted emailType; pass the ID to get_email_send for delivery status and failure details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line. Required with `html` when `templateId` is omitted."},html:{type:"string",description:"Direct-send HTML body. Required with `subject` when `templateId` is omitted; the MCP server maps this to the transactional API `body` field. Use `{{viewInBrowserUrl}}` for a hosted copy link generated at send time."},templateId:{type:"string",description:"Saved transactional email API slug, for example `welcome-email`. The field name is retained for MCP compatibility and is mapped to the transactional API `slug` field."},variables:{type:"object",description:"Variables for template personalization. Nested objects and arrays are supported for repeat blocks, for example { items: [...] }. When the recipient matches a subscriber, saved first and last names fill omitted name variables; explicit values, including blanks, take precedence. Variables are HTML-escaped; a template can prefix a tag with 'html.' ({{html.prerenderedHtml}}) to insert a trusted, sanitized HTML value unescaped."},subscriberExternalId:{type:"string",description:"Customer-owned subscriber ID for attaching analytics, localization, and saved-name personalization on single-recipient sends. Maximum length: 255 characters."},emailType:{type:"string",description:"Delivery policy: `transactional` (default) or `marketing`. Marketing mode supports exactly one recipient and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. When omitted, the saved template or company default is used."},attachments:{type:"array",maxItems:10,description:"Files to attach (7MB total). Each item needs `filename` and exactly one of Base64 `content` or public HTTP(S) `path`. Set `contentId` to embed it as a CID image referenced from HTML, and optionally set `contentType` to override MIME detection.",items:{type:"object",properties:{filename:{type:"string"},content:{type:"string"},path:{type:"string"},contentId:{type:"string"},contentType:{type:"string"}},required:["filename"],additionalProperties:!1}},trackingSettings:{type:"object",description:"Per-send tracking opt-outs. Each field defaults to `true`, meaning the account tracking settings apply; set a field to `false` to disable that tracking for this send only. These fields cannot enable tracking the account has disabled.",properties:{clickTracking:{type:"boolean",description:"Set to `false` to skip click-link rewriting for this send only, which helps when tracking redirects break universal or deep links."},openTracking:{type:"boolean",description:"Set to `false` to skip the open-tracking pixel for this send only."}},additionalProperties:!1}},required:["to"],additionalProperties:!1}}];var m3=[{name:"list_webhooks",description:"List outbound webhook endpoints and their subscribed event types.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"create_webhook",description:"Create an outbound webhook endpoint. IMPORTANT: the response includes a signingSecret that is returned only once - show it to the user immediately so they can store it and verify webhook signatures. If events is omitted, a default set of event types is subscribed.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},name:{type:"string",description:"Webhook endpoint name."},url:{type:"string",description:"HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...M6]},description:"Event types to subscribe to. If omitted, a default set is used."}},required:["name","url"]}},{name:"update_webhook",description:"Update an outbound webhook endpoint's name, URL, subscribed events, or status (enabled/disabled). Providing events replaces the existing event list.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},name:{type:"string",description:"New webhook endpoint name."},url:{type:"string",description:"New HTTPS URL that will receive webhook events."},events:{type:"array",items:{type:"string",enum:[...M6]},description:"Replacement event type subscriptions."},status:{type:"string",enum:["enabled","disabled"],description:"Enable or disable deliveries to this endpoint."}},required:["webhookId"]}},{name:"delete_webhook",description:"Permanently delete an outbound webhook endpoint along with its delivery history. This cannot be undone. To keep the endpoint but stop deliveries, use update_webhook with status disabled instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to delete."}},required:["webhookId"]}},{name:"test_webhook",description:"Send a test event to an outbound webhook endpoint to verify it is reachable and signatures can be validated.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID to test."}},required:["webhookId"]}},{name:"list_webhook_deliveries",description:"List recent delivery attempts for an outbound webhook endpoint, including status and response codes.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},limit:{type:"number",description:"Maximum number of deliveries to return, from 1 to 100. Defaults to 20."}},required:["webhookId"]}},{name:"replay_webhook_delivery",description:"Replay a previous webhook delivery, re-sending the same event payload to the endpoint.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},webhookId:{type:"string",description:"Webhook endpoint ID."},deliveryId:{type:"string",description:"Delivery ID to replay. Use list_webhook_deliveries to find delivery IDs."}},required:["webhookId","deliveryId"]}}];var Z9=[...F3,...q3,...K3,..._3,...h3,...E3,...y3,...B3,...u3,...O3,...Z3,...D3,...A3,...T3,...V3,...N3,...I3,...j3,...k3,...v3,...S3,...C3,...c3,...L3,...f3,...M3,...m3,...U3,...P3];async function l3(W,$){let Q;switch(W){case"get_account":{let G=await D("GET","/api/v1/account"),X=j1();Q={...G,selectedCompanyId:X??G.currentCompanyId};break}case"select_company":{let G=$.companyId,X=await D("GET","/api/v1/account"),J=X.companies?.find((w)=>w.id===G);if(!J)throw Error(`Company not found. Available companies: ${X.companies?.map((w)=>`${w.name} (${w.id})`).join(", ")??"none"}`);v4(G),Q={success:!0,message:`Switched to company: ${J.name}`,companyId:J.id,companyName:J.name};break}case"get_app_urls":{let G=await B9($);Q={...A1({companyId:G,campaignId:B($,"campaignId"),landingPageId:B($,"landingPageId"),sequenceId:B($,"sequenceId"),emailId:B($,"emailId")??B($,"templateId"),transactionalId:B($,"transactionalId"),emailSendId:B($,"emailSendId"),domainId:B($,"domainId"),status:B($,"status"),settingsTab:B($,"settingsTab")}),...G===void 0&&{note:"No company ID is selected. Call get_account, select_company, or pass companyId to get concrete dashboard URLs."}};break}case"create_company":{let G=await D("POST","/api/v1/companies",{name:$.name,domain:$.domain});if(!G.success)throw Error("Failed to create company");let X=G.company.id,J=6,w=0,Y=G.company.status;while(Y==="processing"&&w<J){await new Promise((z)=>setTimeout(z,20000)),w++;let H=await D("GET",`/api/v1/companies/${X}`);if(H.success)Y=H.company.status}v4(X);let b=await D("GET",`/api/v1/companies/${X}`);Q={success:!0,company:b.company,message:Y==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${b.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let G=$.companyId;Q=await D("GET",`/api/v1/companies/${G}`);break}case"update_company":{let G=await T6("update_company",$),X=jH($);Q=await D("PATCH",`/api/v1/companies/${G}`,X);break}case"get_sync_rules":{let G=$.companyId;Q=await D("GET","/api/v1/sync-rules",void 0,G);break}case"update_sync_rules":{let G=$.companyId;if($.syncRules!==null&&!Array.isArray($.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");Q=await D("PUT","/api/v1/sync-rules",{syncRules:$.syncRules},G);break}case"get_shopify_automation_settings":{let G=$.companyId;Q=await D("GET","/api/v1/shopify/automation-settings",void 0,G);break}case"update_shopify_automation_settings":{let G=$.companyId,X={};if($.browseAbandonment!==void 0)X.browseAbandonment=$.browseAbandonment;if($.cartAbandonment!==void 0)X.cartAbandonment=$.cartAbandonment;if($.priceDrop!==void 0)X.priceDrop=$.priceDrop;if(Object.keys(X).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");Q=await D("PUT","/api/v1/shopify/automation-settings",X,G);break}case"create_api_key":{let G=$.companyId,X={};if(typeof $.name==="string")X.name=$.name;if(typeof $.preset==="string")X.preset=$.preset;if(Array.isArray($.scopes))X.scopes=$.scopes;Q=await D("POST","/api/v1/api-keys",X,G);break}case"request_api_key_handoff":{let G=await T6(W,$),X={};if(typeof $.name==="string")X.name=$.name;if(typeof $.preset==="string")X.preset=$.preset;if(Array.isArray($.scopes))X.scopes=$.scopes;if(typeof $.replaceApiKeyId==="string")X.replaceApiKeyId=$.replaceApiKeyId;Q=await D("POST","/api/v1/api-key-handoff",X,G);break}case"list_api_keys":{let G=await T6(W,$);Q=await D("GET","/api/v1/api-keys",void 0,G);break}case"update_api_key":{let G=await T6(W,$),X={};if(typeof $.name==="string")X.name=$.name;if(typeof $.preset==="string")X.preset=$.preset;if(Array.isArray($.scopes))X.scopes=$.scopes;if(Object.keys(X).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");Q=await D("PATCH",`/api/v1/api-keys/${encodeURIComponent(String($.apiKeyId))}`,X,G);break}case"revoke_api_key":case"delete_api_key":{let G=await T6(W,$);Q=await D("DELETE",`/api/v1/api-keys/${encodeURIComponent(String($.apiKeyId))}`,void 0,G);break}case"list_websites":{let G=$.companyId;Q=await D("GET","/api/v1/websites",void 0,G);break}case"add_sending_domain":case"add_website":{let G=$.companyId;Q=await D("POST","/api/v1/websites",{domain:$.domain},G);break}case"check_website":{let G=$.companyId;Q=await D("GET",`/api/v1/websites/${encodeURIComponent(String($.domain))}`,void 0,G);break}case"verify_sending_domain":{let G=$.companyId;Q=await D("POST",`/api/v1/websites/${encodeURIComponent(String($.domain))}/verify`,void 0,G);break}case"list_integrations":{let G=$.companyId,X=new URLSearchParams;if($.includeInactive===!0)X.set("includeInactive","true");let J=X.toString();Q=await D("GET",`/api/v1/integrations${J?`?${J}`:""}`,void 0,G);break}case"list_sender_profiles":{let G=$.companyId;Q=await D("GET","/api/v1/sender-profiles",void 0,G);break}case"update_sender_profile":{let{companyId:G,profileId:X}=$,J=$.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(X)}`:`/api/v1/sender-profiles/${encodeURIComponent(X)}`;Q=await D("PATCH",J,{name:$.name},G);break}case"get_sending_status":{let G=$.companyId;Q=await D("GET","/api/v1/sending-status",void 0,G);break}case"resume_sending":{let G=$.companyId;Q=await D("POST","/api/v1/sending-status/resume",{listSanitizationConfirmed:$.listSanitizationConfirmed===!0},G);break}case"get_tracking_settings":{let G=$.companyId;Q=await D("GET","/api/v1/tracking-settings",void 0,G);break}case"update_tracking_settings":{let G=$.companyId,X=MH($);Q=await D("PATCH","/api/v1/tracking-settings",X,G);break}case"get_notification_preferences":{let G=$.companyId;Q=await D("GET","/api/v1/notification-preferences",void 0,G);break}case"update_notification_preferences":{let G=$.companyId;Q=await D("PATCH","/api/v1/notification-preferences",{notificationPreferences:$.notificationPreferences},G);break}case"get_integration_guide":Q=await D("POST","/api/v1/integration-guide",$);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function g3(W,$){let Q;switch(W){case"generate_email":{let G=$.companyId;Q=await D("POST","/api/v1/generate/email",$,G);break}case"generate_subject_lines":{let G=$.companyId;Q=await D("POST","/api/v1/generate/subjects",$,G);break}case"generate_sms":{let G=$.companyId;Q=await D("POST","/api/v1/generate/sms",$,G);break}case"get_sms_settings":{let G=$.companyId;Q=await D("GET","/api/v1/sms/settings",void 0,G);break}case"update_sms_number_label":{let G=$.companyId,X=A("update_sms_number_label",$,"numberId");if($.label!==void 0&&typeof $.label!=="string")throw Error("update_sms_number_label `label` must be a string; pass an empty string to clear it.");if($.brandPrefix!==void 0&&typeof $.brandPrefix!=="string")throw Error("update_sms_number_label `brandPrefix` must be a string; pass an empty string to clear it.");if($.label===void 0&&$.brandPrefix===void 0)throw Error("update_sms_number_label requires `label` and/or `brandPrefix`.");Q=await D("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(X)}`,{...typeof $.label==="string"?{label:$.label.trim()||null}:{},...typeof $.brandPrefix==="string"?{brandPrefix:$.brandPrefix.trim()||null}:{}},G);break}case"send_test_sms":{let G=$.companyId,X={to:A("send_test_sms",$,"to")};for(let J of["text","imageUrls","blocks"])if($[J]!==void 0)X[J]=$[J];Q=await D("POST","/api/v1/sms/test",X,G);break}case"submit_feedback":{let G=$.companyId,X={message:A("submit_feedback",$,"message"),source:"mcp"};for(let J of["category","context","userIntent","toolCalls","expected","actual","resourceIds"])if($[J]!==void 0)X[J]=$[J];Q=await D("POST","/api/v1/feedback",X,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function p3(W,$){let Q;switch(W){case"list_transactional_emails":{let G=$.companyId,X=new URLSearchParams,J=B($,"search"),w=u("list_transactional_emails",$,"status",["all","active","disabled"]),Y=u("list_transactional_emails",$,"sort",["date","sends","opens","open-rate","clicks","ctr"]),b=u("list_transactional_emails",$,"order",["asc","desc"]);if(J)X.set("search",J);if(w)X.set("status",w);if(Y)X.set("sort",Y);if(b)X.set("order",b);if($.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let H=X.toString();Q=await D("GET",`/api/v1/transactional${H?`?${H}`:""}`,void 0,G);break}case"get_transactional_email":{let G=$.companyId;Q=await D("GET",`/api/v1/transactional/${$.idOrSlug}`,void 0,G);break}case"create_transactional_email":{let G=$.companyId,X=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),J=Object.keys($).filter((Y)=>!X.has(Y));if(J.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((Y)=>`\`${Y}\``).join(", ")}.`);iH($);let w=Object.fromEntries(Object.entries($).filter(([Y])=>Y!=="companyId"));Q=await D("POST","/api/v1/transactional",w,G);break}case"update_transactional_email":{let G=$.companyId,X=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),J=Object.keys($).filter((Y)=>!X.has(Y));if(J.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((Y)=>`\`${Y}\``).join(", ")}.`);if(y0("update_transactional_email",$),$.name===void 0&&$.enabled===void 0&&$.subject===void 0&&$.previewText===void 0&&$.html===void 0&&$.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let w=Object.fromEntries(Object.entries($).filter(([Y])=>Y!=="companyId"&&Y!=="idOrSlug"));Q=await D("PATCH",`/api/v1/transactional/${$.idOrSlug}`,w,G);break}case"delete_transactional_email":{let G=$.companyId,X=A("delete_transactional_email",$,"idOrSlug");Q=await D("DELETE",`/api/v1/transactional/${encodeURIComponent(X)}`,void 0,G);break}case"send_email":{let G=$.companyId,X=A("send_email",$,"to"),J=$.templateId===void 0?void 0:A("send_email",$,"templateId"),w=$.subject===void 0?void 0:A("send_email",$,"subject"),Y=$.html===void 0?void 0:A("send_email",$,"html"),b=$.emailType===void 0?void 0:A("send_email",$,"emailType"),H=$.replyTo===void 0?void 0:A("send_email",$,"replyTo"),z;if($.attachments!==void 0){if(!Array.isArray($.attachments)||$.attachments.length>10)throw Error("`attachments` must be an array with at most 10 items when calling `send_email`.");z=$.attachments.map((L,Z)=>{if(typeof L!=="object"||L===null||Array.isArray(L))throw Error(`\`attachments[${Z}]\` must be an object when calling \`send_email\`.`);let P=L,q=new Set(["filename","content","path","contentId","contentType"]);if(Object.keys(P).some((_)=>!q.has(_)))throw Error(`\`attachments[${Z}]\` contains an unsupported field when calling \`send_email\`.`);let M={};for(let _ of q){let k=P[_];if(k===void 0)continue;if(typeof k!=="string")throw Error(`\`attachments[${Z}].${_}\` must be a string when calling \`send_email\`.`);M[_]=k}if(!M.filename)throw Error(`\`attachments[${Z}].filename\` is required when calling \`send_email\`.`);let S=M.content!==void 0,C=M.path!==void 0;if(S===C)throw Error(`\`attachments[${Z}]\` must provide exactly one of \`content\` or \`path\` when calling \`send_email\`.`);return M})}if(b!==void 0&&b!=="marketing"&&b!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(J!==void 0&&(w!==void 0||Y!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(J===void 0&&(w===void 0||Y===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");let F;if($.trackingSettings!==void 0){if(typeof $.trackingSettings!=="object"||$.trackingSettings===null||Array.isArray($.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let L=$.trackingSettings;F={};for(let Z of["clickTracking","openTracking"]){let P=L[Z];if(P===void 0)continue;if(typeof P!=="boolean")throw Error(`\`trackingSettings.${Z}\` must be a boolean when calling \`send_email\`.`);F[Z]=P}}let U=Object.fromEntries(Object.entries({to:X,slug:J,subject:w,body:Y,variables:$.variables,subscriberExternalId:$.subscriberExternalId,emailType:b,replyTo:H,attachments:z,trackingSettings:F}).filter(([,L])=>L!==void 0));Q=await D("POST","/api/v1/transactional/send",U,G);break}case"get_stats":{let G=$.companyId,X=$.period??"7d",J=new URLSearchParams({period:String(X)}),w=$.emailType===void 0?void 0:A("get_stats",$,"emailType");if(w!==void 0&&!["campaign","transactional","sequence"].includes(w))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(w)J.set("emailType",w);if($.includeMachineEngagement===!0)J.set("includeMachineEngagement","true");Q=await D("GET",`/api/v1/metrics?${J.toString()}`,void 0,G);break}case"get_campaign_stats":{let G=$.companyId,X=new URLSearchParams;if(typeof $.period==="string")X.set("period",$.period);if(typeof $.start==="string")X.set("start",$.start);if(typeof $.end==="string")X.set("end",$.end);if($.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let J=X.toString();Q=await D("GET",`/api/v1/metrics/campaigns/${$.campaignId}${J?`?${J}`:""}`,void 0,G);break}case"list_poll_responses":{let G=$.companyId,X=A("list_poll_responses",$,"campaignId"),J=new URLSearchParams,w=B($,"blockId");if(w)J.set("blockId",w);for(let b of["page","limit"])if($[b]!==void 0)J.set(b,String($[b]));let Y=J.toString();Q=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(X)}/poll-responses${Y?`?${Y}`:""}`,void 0,G);break}case"get_transactional_stats":{let G=$.companyId,X=A("get_transactional_stats",$,"idOrSlug"),J=new URLSearchParams;for(let Y of["period","start","end"])if(typeof $[Y]==="string"&&$[Y].trim())J.set(Y,$[Y].trim());if($.includeMachineEngagement===!0)J.set("includeMachineEngagement","true");let w=J.toString();Q=await D("GET",`/api/v1/metrics/transactional/${encodeURIComponent(X)}${w?`?${w}`:""}`,void 0,G);break}case"get_sequence_stats":{let G=$.companyId,X=new URLSearchParams;for(let w of["period","start","end"])if(typeof $[w]==="string"&&$[w].trim())X.set(w,$[w].trim());if($.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let J=X.toString();Q=await D("GET",`/api/v1/metrics/sequences/${$.sequenceId}${J?`?${J}`:""}`,void 0,G);break}case"list_campaign_events":{let G=$.companyId,X=A("list_campaign_events",$,"campaignId"),w=UQ("list_campaign_events",$).toString();Q=await D("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(X)}/events${w?`?${w}`:""}`,void 0,G);break}case"list_sequence_events":{let G=$.companyId,X=A("list_sequence_events",$,"sequenceId"),J=UQ("list_sequence_events",$),w=B($,"automationNodeId");if(w)J.set("automationNodeId",w);let Y=J.toString();Q=await D("GET",`/api/v1/metrics/sequences/${encodeURIComponent(X)}/events${Y?`?${Y}`:""}`,void 0,G);break}case"list_email_metrics":{let G=$.companyId,X=new URLSearchParams,J=u("list_email_metrics",$,"emailType",["campaign","sequence"]);if(J)X.set("emailType",J);let w=y8("list_email_metrics",$,"sequenceId"),Y=y8("list_email_metrics",$,"campaignId"),b=G0("list_email_metrics",$,"step",1,1000);if(Y.length>0&&(w.length>0||b))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(J==="campaign"&&(w.length>0||b!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(J==="sequence"&&Y.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(w.length>0)X.set("sequenceId",w.join(","));if(Y.length>0)X.set("campaignId",Y.join(","));if(b!==void 0)X.set("step",String(b));let H=u("list_email_metrics",$,"period",["1h","24h","7d","30d","90d"]);if(H)X.set("period",H);for(let P of["start","end"]){let q=B($,P);if(q)X.set(P,q)}let z=u("list_email_metrics",$,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(z)X.set("sort",z);let F=u("list_email_metrics",$,"order",["asc","desc"]);if(F)X.set("order",F);let U=G0("list_email_metrics",$,"page",1,1e6);if(U!==void 0)X.set("page",String(U));let L=G0("list_email_metrics",$,"limit",1,500);if(L!==void 0)X.set("limit",String(L));if($.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");let Z=X.toString();Q=await D("GET",`/api/v1/metrics/emails${Z?`?${Z}`:""}`,void 0,G);break}case"get_subscriber_activity":{let G=$.companyId,X=W1("get_subscriber_activity",$),J=await S4(X,G,{includeMachineEngagement:$.includeMachineEngagement===!0});Q={success:J.success,email:J.subscriber.email,emailStats:J.subscriber.emailStats??null,activity:J.subscriber.activity??[],sequenceEnrollments:J.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function i3(W,$){let Q;switch(W){case"list_tags":{let G=$.companyId;Q=await D("GET","/api/v1/tags",void 0,G);break}case"create_tag":{let G=$.companyId,X=A("create_tag",$,"name"),J=u("create_tag",$,"color",j6);Q=await D("POST","/api/v1/tags",{name:X,...J!==void 0&&{color:J}},G);break}case"update_tag":{let G=$.companyId,X=A("update_tag",$,"tagId"),J=C4("update_tag",$,"color",j6);Q=await D("PATCH",`/api/v1/tags/${encodeURIComponent(X)}`,{color:J},G);break}case"delete_tag":{let G=$.companyId,X=A("delete_tag",$,"tagId");Q=await D("DELETE",`/api/v1/tags/${encodeURIComponent(X)}`,void 0,G);break}case"list_lists":{let G=$.companyId;Q=await D("GET","/api/v1/lists",void 0,G);break}case"create_list":{let G=$.companyId;Q=await D("POST","/api/v1/lists",$,G);break}case"update_list":{let G=$.companyId,X=A("update_list",$,"listId");if($.name===void 0&&$.description===void 0&&$.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if($.name!==void 0&&B($,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if($.description!==void 0&&$.description!==null&&typeof $.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if($.isPrivate!==void 0&&typeof $.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");Q=await D("PATCH",`/api/v1/lists/${encodeURIComponent(X)}`,{...$.name!==void 0&&{name:B($,"name")},...$.description!==void 0&&{description:$.description},...$.isPrivate!==void 0&&{isPrivate:$.isPrivate}},G);break}case"delete_list":{let G=$.companyId,X=A("delete_list",$,"listId");Q=await D("DELETE",`/api/v1/lists/${encodeURIComponent(X)}`,void 0,G);break}case"add_subscribers_to_list":{let G=$.companyId,X=A("add_subscribers_to_list",$,"listId"),J=BQ("add_subscribers_to_list",$),w=u("add_subscribers_to_list",$,"duplicateStrategy",["skip","merge","overwrite"])??"skip",Y=u("add_subscribers_to_list",$,"optInMode",["default","confirmed","double_opt_in"])??"default";Q=await D("POST",`/api/v1/lists/${encodeURIComponent(X)}/subscribers`,{emails:J,duplicateStrategy:w,enrollInSequences:$.enrollInSequences===!0,optInMode:Y},G);break}case"remove_subscribers_from_list":{let G=$.companyId,X=A("remove_subscribers_from_list",$,"listId"),J=BQ("remove_subscribers_from_list",$);Q=await D("POST",`/api/v1/lists/${encodeURIComponent(X)}/subscribers/remove`,{emails:J},G);break}case"list_segments":{let G=$.companyId;Q=await D("GET","/api/v1/segments",void 0,G);break}case"create_segment":{PH($);let G=$.companyId;Q=await D("POST","/api/v1/segments",{...$,...$.filters!==void 0?{filters:Y9($.filters)}:{},...$.root!==void 0?{root:b9($.root)}:{}},G);break}case"update_segment":{VH($);let G=$.companyId,X=A("update_segment",$,"segmentId"),J=B($,"name"),w=u("update_segment",$,"filterJoinOperator",["and","or"]);Q=await D("PATCH",`/api/v1/segments/${encodeURIComponent(X)}`,{...J!==void 0&&{name:J},...w!==void 0&&{filterJoinOperator:w},...$.filters!==void 0?{filters:Y9($.filters)}:{},...$.root!==void 0?{root:b9($.root)}:{}},G);break}case"delete_segment":{let G=$.companyId,X=A("delete_segment",$,"segmentId");Q=await D("DELETE",`/api/v1/segments/${encodeURIComponent(X)}`,void 0,G);break}case"get_segment_count":{let G=$.companyId;Q=await D("GET",`/api/v1/segments/${$.segmentId}/count`,void 0,G);break}case"list_audience_syncs":{let G=$.companyId;Q=await D("GET","/api/v1/audience-syncs",void 0,G);break}case"list_ad_accounts":{let G=$.companyId;Q=await D("GET","/api/v1/ad-accounts",void 0,G);break}case"create_audience_sync":{let G=$.companyId,X=B($,"segmentId"),J=B($,"predefinedSegmentId");if(X&&J)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!X&&!J)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");Q=await D("POST","/api/v1/audience-syncs",{segmentId:X,predefinedSegmentId:J,adAccountId:A("create_audience_sync",$,"adAccountId"),audienceName:A("create_audience_sync",$,"audienceName"),...$.frequency!==void 0?{frequency:$.frequency}:{}},G);break}case"update_audience_sync":{let G=$.companyId,X=A("update_audience_sync",$,"syncId");Q=await D("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(X)}`,{...$.frequency!==void 0?{frequency:$.frequency}:{},...$.isActive!==void 0?{isActive:$.isActive}:{}},G);break}case"delete_audience_sync":{let G=$.companyId,X=A("delete_audience_sync",$,"syncId");Q=await D("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(X)}`,void 0,G);break}case"sync_audience_now":{let G=$.companyId,X=A("sync_audience_now",$,"syncId");Q=await D("POST",`/api/v1/audience-syncs/${encodeURIComponent(X)}/sync`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function n3(W,$){let Q;switch(W){case"list_templates":{let G=$.companyId,X=new URLSearchParams,J=B($,"label");if(J)X.set("label",J);let w=G0("list_templates",$,"limit",1,100);if(w!==void 0)X.set("limit",String(w));let Y=G0("list_templates",$,"offset",0,1e6);if(Y!==void 0)X.set("offset",String(Y));Q=await D("GET",`/api/v1/templates${X.size>0?`?${X}`:""}`,void 0,G);break}case"get_template":{let G=$.companyId;Q=await D("GET",`/api/v1/templates/${$.templateId}`,void 0,G);break}case"create_template":{let G=$.companyId;lH($);let X=Object.fromEntries(Object.entries($).filter(([J])=>J!=="companyId"));Q=await D("POST","/api/v1/templates",X,G);break}case"update_template":{let G=$.companyId,X=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),J=Object.keys($).filter((w)=>!X.has(w));if(J.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);if(y0("update_template",$),Z1("update_template",$),$.name===void 0&&$.subject===void 0&&$.previewText===void 0&&$.html===void 0&&$.blocks===void 0&&$.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");Q=await D("PUT",`/api/v1/templates/${$.templateId}`,$,G);break}case"set_template_localization":{let G=$.companyId,X=A("set_template_localization",$,"templateId"),J=A("set_template_localization",$,"locale"),w=A("set_template_localization",$,"subject"),Y=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),b=Object.keys($).filter((z)=>!Y.has(z));if(b.length>0)throw Error(`\`set_template_localization\` received unsupported field${b.length===1?"":"s"}: ${b.map((z)=>`\`${z}\``).join(", ")}.`);y0("set_template_localization",$,{requireContent:!0});let H={subject:w};if($.previewText!==void 0)H.previewText=$.previewText;if($.html!==void 0)H.html=$.html;if($.blocks!==void 0)H.blocks=$.blocks;Q=await D("PUT",`/api/v1/templates/${encodeURIComponent(X)}/localizations/${encodeURIComponent(J)}`,H,G);break}case"sync_template_localizations":{let G=$.companyId,X=A("sync_template_localizations",$,"templateId"),J=new Set(["companyId","templateId","locales"]),w=Object.keys($).filter((b)=>!J.has(b));if(w.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${w.length===1?"":"s"}: ${w.map((b)=>`\`${b}\``).join(", ")}.`);let Y;if($.locales!==void 0){if(!Array.isArray($.locales)||$.locales.length===0||$.locales.some((b)=>typeof b!=="string"||b.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");Y=$.locales.map((b)=>b.trim())}Q=await D("POST",`/api/v1/templates/${encodeURIComponent(X)}/localizations/sync`,Y===void 0?{}:{locales:Y},G);break}case"delete_template":{let G=$.companyId;Q=await D("DELETE",`/api/v1/templates/${$.templateId}`,void 0,G);break}case"share_template":{let G=$.companyId,X=A("share_template",$,"templateId");Q=await D("POST",`/api/v1/templates/${encodeURIComponent(X)}/share-link`,void 0,G);break}case"unshare_template":{let G=$.companyId,X=A("unshare_template",$,"templateId");Q=await D("DELETE",`/api/v1/templates/${encodeURIComponent(X)}/share-link`,void 0,G);break}case"list_ab_tests":{let G=$.companyId,X=new URLSearchParams,J=B($,"sequenceId");if(J)X.set("sequenceId",J);Q=await D("GET",`/api/v1/ab-tests${X.size>0?`?${X}`:""}`,void 0,G);break}case"get_ab_test":{let G=$.companyId;Q=await D("GET",`/api/v1/ab-tests/${$.abTestId}`,void 0,G);break}case"get_ab_test_stats":{let G=$.companyId,X=new URLSearchParams,J=B($,"period"),w=B($,"start"),Y=B($,"end");if(J)X.set("period",J);if(w)X.set("start",w);if(Y)X.set("end",Y);if($.includeMachineEngagement===!0)X.set("includeMachineEngagement","true");Q=await D("GET",`/api/v1/ab-tests/${$.abTestId}/stats${X.size>0?`?${X}`:""}`,void 0,G);break}case"restart_ab_test":{let G=$.companyId,X=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),J=Object.keys($).filter((H)=>!X.has(H));if(J.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${J.length===1?"":"s"}: ${J.map((H)=>`\`${H}\``).join(", ")}.`);let w=B($,"testType");if(w!==void 0&&w!=="subject"&&w!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let Y=$.winnerThreshold===void 0?void 0:Number($.winnerThreshold);if(Y!==void 0&&(!Number.isInteger(Y)||Y<10||Y>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let b=$.variantCount===void 0?void 0:Number($.variantCount);if(b!==void 0&&(!Number.isInteger(b)||b<2||b>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");Q=await D("POST",`/api/v1/ab-tests/${$.abTestId}/restart`,{sourceVariantId:B($,"sourceVariantId"),testType:w,winnerThreshold:Y,variantCount:b},G);break}case"update_ab_test_variant":{let G=$.companyId,X=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),J=Object.keys($).filter((w)=>!X.has(w));if(J.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);if(y0("update_ab_test_variant",$),$.confirmLiveChange!==void 0&&typeof $.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if($.subject===void 0&&$.previewText===void 0&&$.html===void 0&&$.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");Q=await D("PATCH",`/api/v1/ab-tests/${$.abTestId}/variants/${$.variantId}`,$,G);break}case"update_ab_test":{let G=$.companyId,X=A("update_ab_test",$,"abTestId"),J=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),w=Object.keys($).filter((L)=>!J.has(L));if(w.length>0)throw Error(`\`update_ab_test\` received unsupported field${w.length===1?"":"s"}: ${w.map((L)=>`\`${L}\``).join(", ")}.`);if($.confirmLiveChange!==void 0&&typeof $.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let Y=B($,"name"),b=G0("update_ab_test",$,"testPercentage",5,50),H=G0("update_ab_test",$,"testDurationMinutes",15,1440),z=u("update_ab_test",$,"winnerCriteria",["open_rate","click_rate"]),F=u("update_ab_test",$,"testType",["subject","content"]),U=G0("update_ab_test",$,"winnerThreshold",10,1000);if(Y===void 0&&b===void 0&&H===void 0&&z===void 0&&F===void 0&&U===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");Q=await D("PATCH",`/api/v1/ab-tests/${encodeURIComponent(X)}`,{...Y!==void 0&&{name:Y},...b!==void 0&&{testPercentage:b},...H!==void 0&&{testDurationMinutes:H},...z!==void 0&&{winnerCriteria:z},...F!==void 0&&{testType:F},...U!==void 0&&{winnerThreshold:U},...$.confirmLiveChange===!0&&{confirmLiveChange:!0}},G);break}case"create_ab_test":{let G=$.companyId,X=B($,"campaignId"),J=B($,"automationNodeId");if($.confirmLiveChange!==void 0&&typeof $.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(X)===Boolean(J))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let w=B($,"name"),Y=G0("create_ab_test",$,"testPercentage",5,50),b=G0("create_ab_test",$,"testDurationMinutes",15,1440),H=u("create_ab_test",$,"winnerCriteria",["open_rate","click_rate"]),z=u("create_ab_test",$,"testType",["subject","content"]),F=G0("create_ab_test",$,"winnerThreshold",10,1000);if($.variants!==void 0){if(!Array.isArray($.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");$.variants.forEach((L,Z)=>{if(!h(L)||typeof L.subject!=="string"||L.subject.trim()==="")throw Error(`\`variants\` item ${Z+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(L.blocks!==void 0&&!Array.isArray(L.blocks))throw Error(`\`variants\` item ${Z+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let U=Array.isArray($.variants)?$.variants:void 0;if(J!==void 0&&(!U||U.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(U&&U.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");Q=await D("POST","/api/v1/ab-tests",{...X!==void 0&&{campaignId:X},...J!==void 0&&{automationNodeId:J},...$.confirmLiveChange===!0&&{confirmLiveChange:!0},...w!==void 0&&{name:w},...Y!==void 0&&{testPercentage:Y},...b!==void 0&&{testDurationMinutes:b},...H!==void 0&&{winnerCriteria:H},...z!==void 0&&{testType:z},...F!==void 0&&{winnerThreshold:F},...$.variants!==void 0&&{variants:$.variants}},G);break}case"add_ab_test_variant":{let G=$.companyId,X=A("add_ab_test_variant",$,"abTestId"),J=A("add_ab_test_variant",$,"subject"),w=B($,"previewText");if($.blocks!==void 0&&!Array.isArray($.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if($.confirmLiveChange!==void 0&&typeof $.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");Q=await D("POST",`/api/v1/ab-tests/${encodeURIComponent(X)}/variants`,{subject:J,...w!==void 0&&{previewText:w},...$.blocks!==void 0&&{blocks:$.blocks},...$.confirmLiveChange===!0&&{confirmLiveChange:!0}},G);break}case"delete_ab_test_variant":{let G=$.companyId,X=A("delete_ab_test_variant",$,"abTestId"),J=A("delete_ab_test_variant",$,"variantId");if($.confirmLiveChange!==void 0&&typeof $.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");Q=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(X)}/variants/${encodeURIComponent(J)}${$.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,G);break}case"delete_ab_test":{let G=$.companyId,X=A("delete_ab_test",$,"abTestId");Q=await D("DELETE",`/api/v1/ab-tests/${encodeURIComponent(X)}`,void 0,G);break}case"list_campaigns":{let G=$.companyId,X=new URLSearchParams;if($.status)X.set("status",String($.status));let J=B($,"label");if(J)X.set("label",J);for(let w of["limit","offset"])if($[w]!==void 0)X.set(w,String($[w]));Q=await D("GET",`/api/v1/campaigns?${X}`,void 0,G);break}case"get_campaign":{let G=$.companyId;Q=await D("GET",`/api/v1/campaigns/${$.campaignId}`,void 0,G);break}case"get_campaign_audience":{let G=$.companyId;Q=await D("GET",`/api/v1/campaigns/${encodeURIComponent(String($.campaignId))}/audience`,void 0,G);break}case"get_email_send":{let G=$.companyId;Q=await D("GET",`/api/v1/email-sends/${encodeURIComponent(String($.emailSendId))}`,void 0,G);break}case"list_email_sends":{let G=$.companyId,X=new URLSearchParams,J=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let q of J){let M=B($,q);if(M)X.set(q,M)}let w=u("list_email_sends",$,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),Y=u("list_email_sends",$,"emailType",["campaign","transactional","sequence"]),b=u("list_email_sends",$,"bounceType",["Permanent","Transient"]),H=u("list_email_sends",$,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),z=u("list_email_sends",$,"sortOrder",["asc","desc"]),F=G0("list_email_sends",$,"days",1,14),U=G0("list_email_sends",$,"page",1,Number.MAX_SAFE_INTEGER),L=G0("list_email_sends",$,"limit",1,100),Z=[["status",w],["emailType",Y],["bounceType",b],["sortField",H],["sortOrder",z],["days",F],["page",U],["limit",L]];for(let[q,M]of Z)if(M!==void 0)X.set(q,String(M));let P=X.toString();Q=await D("GET",`/api/v1/email-sends${P?`?${P}`:""}`,void 0,G);break}case"create_campaign":{let G=$.companyId;mH($),q6("create_campaign",$);let X=Object.fromEntries(Object.entries($).filter(([J])=>J!=="companyId"));Q=await D("POST","/api/v1/campaigns",X,G);break}case"update_campaign":{let G=$.companyId,X=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","listIds","labels"]),J=Object.keys($).filter((w)=>!X.has(w));if(J.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, and label update fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);if(y0("update_campaign",$),Z1("update_campaign",$),q6("update_campaign",$,{replyFirst:!0}),[$.segmentId,$.listIds,$.targetLists].filter((w)=>w!==void 0).length>1)throw Error("Provide at most one of `segmentId`, `listIds`, or `targetLists` when calling `update_campaign`.");if($.name===void 0&&$.subject===void 0&&$.trackingCode===void 0&&$.html===void 0&&$.blocks===void 0&&$.fromEmail===void 0&&$.senderProfileId===void 0&&$.replyTo===void 0&&$.replyProfileId===void 0&&$.ccEmails===void 0&&$.bccEmails===void 0&&$.campaignData===void 0&&$.computedLists===void 0&&$.targetLists===void 0&&$.segmentId===void 0&&$.listIds===void 0&&$.labels===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, or label field when calling `update_campaign`.");Q=await D("PUT",`/api/v1/campaigns/${$.campaignId}`,$,G);break}case"schedule_campaign":{let G=$.companyId,X=new Set(["companyId","campaignId","scheduledAt","targetLists","listIds","sendTimeOptimization","spreadOverHours","recurringInterval"]),J=Object.keys($).filter((w)=>!X.has(w));if(J.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`listIds\`, \`sendTimeOptimization\`, \`spreadOverHours\`, and \`recurringInterval\`. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);gH($),Q=await D("POST",`/api/v1/campaigns/${$.campaignId}/schedule`,{scheduledAt:$.scheduledAt,...$.targetLists!==void 0&&{targetLists:$.targetLists},...$.listIds!==void 0&&{listIds:$.listIds},...$.sendTimeOptimization!==void 0&&{sendTimeOptimization:$.sendTimeOptimization},...$.spreadOverHours!==void 0&&{spreadOverHours:$.spreadOverHours},...$.recurringInterval!==void 0&&{recurringInterval:$.recurringInterval}},G);break}case"send_test_email":{let G=$.companyId;Q=await D("POST",`/api/v1/campaigns/${$.campaignId}/test`,{to:$.to},G);break}case"cancel_campaign":{let G=$.companyId,X=A("cancel_campaign",$,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/cancel`,void 0,G);break}case"share_campaign":{let G=$.companyId,X=A("share_campaign",$,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/share-link`,void 0,G);break}case"unshare_campaign":{let G=$.companyId,X=A("unshare_campaign",$,"campaignId");Q=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(X)}/share-link`,void 0,G);break}case"unschedule_campaign":{let G=$.companyId,X=A("unschedule_campaign",$,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/unschedule`,void 0,G);break}case"pause_campaign":{let G=$.companyId,X=A("pause_campaign",$,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/pause`,void 0,G);break}case"resume_campaign":{let G=$.companyId,X=A("resume_campaign",$,"campaignId"),J=G0("resume_campaign",$,"spreadOverHours",1,72);Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/resume`,{...J!==void 0&&{spreadOverHours:J}},G);break}case"delete_campaign":{let G=$.companyId,X=A("delete_campaign",$,"campaignId");Q=await D("DELETE",`/api/v1/campaigns/${encodeURIComponent(X)}`,void 0,G);break}case"duplicate_campaign":{let G=$.companyId,X=A("duplicate_campaign",$,"campaignId"),J=u("duplicate_campaign",$,"mode",["campaign","ab_test","variant"]),w=B($,"variantId");if(J==="variant"&&w===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/duplicate`,{...J!==void 0&&{mode:J},...w!==void 0&&{variantId:w}},G);break}case"resend_campaign_to_non_openers":{let G=$.companyId,X=A("resend_campaign_to_non_openers",$,"campaignId");Q=await D("POST",`/api/v1/campaigns/${encodeURIComponent(X)}/resend-to-non-openers`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function d3(W,$){if(W!=="get_email_block_schema")return{handled:!1,result:void 0};let Q=B($,"blockType");if(Q!==void 0)return{handled:!0,result:await D("GET",`/api/v1/email-blocks/${encodeURIComponent(Q)}`)};let G=$.creatableOnly===!0?"/api/v1/email-blocks?creatableOnly=true":"/api/v1/email-blocks";return{handled:!0,result:await D("GET",G)}}function jQ(W,$){let Q=$.blocks;if(!Array.isArray(Q))throw Error(`\`blocks\` must be an array of block objects when calling \`${W}\`.`);return Q}var BM=new Set(["list_email_components","get_email_component","get_default_email_component","set_default_email_component","create_email_component","update_email_component","delete_email_component"]);async function o3(W,$){if(!BM.has(W))return{handled:!1,result:void 0};let Q=B($,"companyId");if(W==="list_email_components"){let J=new URLSearchParams,w=B($,"type");if(w)J.set("type",w);if($.defaultsOnly===!0)J.set("defaultsOnly","true");return{handled:!0,result:await D("GET",`/api/v1/email-components${J.size>0?`?${J}`:""}`,void 0,Q)}}if(W==="get_email_component"){let J=A(W,$,"componentId");return{handled:!0,result:await D("GET",`/api/v1/email-components/${encodeURIComponent(J)}`,void 0,Q)}}if(W==="get_default_email_component"){let J=A(W,$,"slot");return{handled:!0,result:await D("GET",`/api/v1/email-components/defaults/${encodeURIComponent(J)}`,void 0,Q)}}if(W==="set_default_email_component"){let J=A(W,$,"slot"),Y={blocks:jQ(W,$)},b=B($,"name"),H=B($,"description");if(b!==void 0)Y.name=b;if(H!==void 0)Y.description=H;return{handled:!0,result:await D("PUT",`/api/v1/email-components/defaults/${encodeURIComponent(J)}`,Y,Q)}}if(W==="create_email_component"){let J={name:A(W,$,"name"),blocks:jQ(W,$)},w=B($,"description"),Y=B($,"componentType");if(w!==void 0)J.description=w;if(Y!==void 0)J.componentType=Y;return{handled:!0,result:await D("POST","/api/v1/email-components",J,Q)}}if(W==="update_email_component"){let J=A(W,$,"componentId"),w={},Y=B($,"name"),b=B($,"description"),H=B($,"componentType");if(Y!==void 0)w.name=Y;if(b!==void 0)w.description=b;if(H!==void 0)w.componentType=H;if($.blocks!==void 0)w.blocks=jQ(W,$);return{handled:!0,result:await D("PATCH",`/api/v1/email-components/${encodeURIComponent(J)}`,w,Q)}}let G=A(W,$,"componentId");return{handled:!0,result:await D("DELETE",`/api/v1/email-components/${encodeURIComponent(G)}`,void 0,Q)}}async function t3(W,$){if(W!=="get_event_schema")return{handled:!1,result:void 0};let Q=new URLSearchParams,G=B($,"eventName");if(G)Q.set("eventName",G);let X=B($,"provider");if(X)Q.set("provider",X);let J=Q.toString();return{handled:!0,result:await D("GET",`/api/v1/events/schemas${J?`?${J}`:""}`,void 0,B($,"companyId"))}}async function r3(W,$){let Q;switch(W){case"list_forms":{let G=$.companyId;Q=await D("GET","/api/v1/forms",void 0,G);break}case"create_form":{let G=$.companyId,X=A("create_form",$,"name"),J=Array.isArray($.listIds)?$.listIds.filter((b)=>typeof b==="string").map((b)=>b.trim()).filter(Boolean):[];if(J.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let w=u("create_form",$,"duplicateStrategy",["skip","merge","overwrite"]),Y={name:X,listIds:J};for(let b of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if($[b]!==void 0)Y[b]=$[b];if(w!==void 0)Y.duplicateStrategy=w;Q=await D("POST","/api/v1/forms",Y,G);break}case"update_form":{let G=$.companyId,X=A("update_form",$,"formId"),J=u("update_form",$,"duplicateStrategy",["skip","merge","overwrite"]),w={};for(let Y of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if($[Y]!==void 0)w[Y]=$[Y];if(J!==void 0)w.duplicateStrategy=J;if(Object.keys(w).length===0)throw Error("Provide at least one field to change when calling `update_form`.");Q=await D("PATCH",`/api/v1/forms/${encodeURIComponent(X)}`,w,G);break}case"get_form_embed":{let G=$.companyId,X=A("get_form_embed",$,"formId");Q=await D("GET",`/api/v1/forms/embed/${encodeURIComponent(X)}`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function K9(W,$,Q,G,X){let J=W[$];if(J===void 0)return;if(typeof J!=="number"||!Number.isFinite(J)||J<Q||J>G||X&&!Number.isInteger(J))throw Error(`\`${$}\` must be a ${X?"integer":"number"} between ${Q} and ${G} when calling \`upload_image_asset\`.`);return J}async function s3(W,$){if(W!=="upload_image_asset")return{handled:!1,result:void 0};let Q=B($,"filePath"),G=B($,"imageBase64");if(Q===void 0===(G===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let X=B($,"filename");if(G!==void 0&&X===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let J=K9($,"sourceWidth",1,20000,!0),w=K9($,"sourceHeight",1,20000,!0);if(J===void 0!==(w===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let Y=K9($,"displayWidthPercent",1,100,!1)??100,b=K9($,"cropHeight",1,2000,!0),H=B($,"objectFit");if(H!==void 0&&H!=="cover"&&H!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(H!==void 0&&b===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let z=B($,"align");if(z!==void 0&&!["left","center","right"].includes(z))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let F=typeof $.altText==="string"?$.altText.trim():void 0;if(F!==void 0&&F.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let U=await J3({companyId:B($,"companyId"),filePath:Q,imageBase64:G,filename:X,contentType:B($,"contentType"),altText:F,sourceWidth:J,sourceHeight:w}),L={type:"image",src:U.url,alt:U.altText??"",width:Y,widthType:"percent",...b!==void 0&&{height:b,objectFit:H??"cover"},...z!==void 0&&{align:z}};return{handled:!0,result:{success:!0,asset:U,imageBlock:L,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}async function a3(W,$){let Q=$.companyId,G;switch(W){case"connect_integration":{let X=A("connect_integration",$,"provider"),J=A("connect_integration",$,"webhookSecret");G=await D("POST","/api/v1/integrations/connect",{provider:X,webhookSecret:J,...typeof $.apiKey==="string"&&$.apiKey?{apiKey:$.apiKey}:{},...typeof $.providerAccountId==="string"&&$.providerAccountId?{providerAccountId:$.providerAccountId}:{},...$.settings!==void 0?{settings:$.settings}:{},...$.historyImport!==void 0?{historyImport:$.historyImport}:{}},Q);break}case"get_integration":{let X=A("get_integration",$,"integrationId");G=await D("GET",`/api/v1/integrations/${encodeURIComponent(X)}`,void 0,Q);break}case"list_integration_capabilities":{let X=new URLSearchParams;if(typeof $.provider==="string"&&$.provider)X.set("provider",$.provider);if(typeof $.category==="string"&&$.category)X.set("category",$.category);let J=X.toString();G=await D("GET",`/api/v1/integrations/catalog${J?`?${J}`:""}`,void 0,Q);break}case"list_integration_activity":{let X=new URLSearchParams;if(typeof $.integrationId==="string"&&$.integrationId)X.set("integrationId",$.integrationId);if(typeof $.provider==="string"&&$.provider)X.set("provider",$.provider);if(typeof $.status==="string"&&$.status)X.set("status",$.status);if(typeof $.limit==="number")X.set("limit",String($.limit));let J=X.toString();G=await D("GET",`/api/v1/integrations/activity${J?`?${J}`:""}`,void 0,Q);break}case"set_integration_sync_enabled":{let X=A("set_integration_sync_enabled",$,"integrationId");if(typeof $.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");G=await D("PATCH",`/api/v1/integrations/${encodeURIComponent(X)}`,{syncEnabled:$.syncEnabled},Q);break}case"get_integration_pixel":{let X=A("get_integration_pixel",$,"integrationId");G=await D("GET",`/api/v1/integrations/${encodeURIComponent(X)}/pixel`,void 0,Q);break}case"activate_integration_pixel":{let X=A("activate_integration_pixel",$,"integrationId");G=await D("POST",`/api/v1/integrations/${encodeURIComponent(X)}/pixel`,void 0,Q);break}case"sync_integration":{let X=A("sync_integration",$,"integrationId");G=await D("POST",`/api/v1/integrations/${encodeURIComponent(X)}/sync`,void 0,Q);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:G}}async function e3(W,$){let Q;switch(W){case"list_landing_pages":{let G=$.companyId;Q=await D("GET","/api/v1/landing-pages",void 0,G);break}case"get_landing_page":{let G=$.companyId;Q=await D("GET",`/api/v1/landing-pages/${$.landingPageId}`,void 0,G);break}case"create_landing_page":{let G=$.companyId,X=new Set(["companyId","name","slug","template","content"]),J=Object.keys($).filter((w)=>!X.has(w));if(J.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${J.length===1?"":"s"}: ${J.map((w)=>`\`${w}\``).join(", ")}.`);Q=await D("POST","/api/v1/landing-pages",{...$.name!==void 0&&{name:$.name},...$.slug!==void 0&&{slug:$.slug},...$.template!==void 0&&{template:$.template},...$.content!==void 0&&{content:$.content}},G);break}case"update_landing_page":{let G=$.companyId,X=U9("update_landing_page",$,{requireUpdate:!0});Q=await D("PUT",`/api/v1/landing-pages/${$.landingPageId}`,X,G);break}case"publish_landing_page":{let G=$.companyId,X=U9("publish_landing_page",$,{requireUpdate:!1});Q=await D("POST",`/api/v1/landing-pages/${$.landingPageId}/publish`,X,G);break}case"unpublish_landing_page":{let G=$.companyId,X=U9("unpublish_landing_page",$,{requireUpdate:!1});Q=await D("POST",`/api/v1/landing-pages/${$.landingPageId}/unpublish`,X,G);break}case"duplicate_landing_page":{let G=$.companyId;Q=await D("POST",`/api/v1/landing-pages/${$.landingPageId}/duplicate`,{...$.name!==void 0&&{name:$.name},...$.slug!==void 0&&{slug:$.slug}},G);break}case"delete_landing_page":{let G=$.companyId;Q=await D("DELETE",`/api/v1/landing-pages/${$.landingPageId}`,void 0,G);break}case"connect_landing_page_domain":{let G=$.companyId;Q=await D("POST","/api/v1/landing-pages/domain",{domain:$.domain},G);break}case"update_landing_page_domain_settings":{let G=$.companyId,X=pH($);Q=await D("PUT","/api/v1/landing-pages/domain",X,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}var Wz=["listIds","tagIds","headline","description","buttonText","successMessage","redirectUrl","presentation","placement","trigger","targeting","schedule","frequency","visual","theme","blocks"];async function $z(W,$){let Q;switch(W){case"list_popups":{let G=$.companyId,X=$.includeContent===!0;Q=await D("GET",X?"/api/v1/popups?includeContent=true":"/api/v1/popups",void 0,G);break}case"get_popup":{let G=$.companyId,X=A("get_popup",$,"popupId");Q=await D("GET",`/api/v1/popups/${encodeURIComponent(X)}`,void 0,G);break}case"create_popup":{let G=$.companyId,X=A("create_popup",$,"name"),J=u("create_popup",$,"duplicateStrategy",["skip","merge","overwrite"]),w=u("create_popup",$,"status",["draft","published"]),Y=$.template,b={name:X};for(let H of Wz)if($[H]!==void 0)b[H]=$[H];if(J!==void 0)b.duplicateStrategy=J;if(w!==void 0)b.status=w;if(Y!==void 0)b.template=Y;Q=await D("POST","/api/v1/popups",b,G);break}case"update_popup":{let G=$.companyId,X=A("update_popup",$,"popupId"),J=u("update_popup",$,"duplicateStrategy",["skip","merge","overwrite"]),w=u("update_popup",$,"status",["draft","published"]),Y={};if($.name!==void 0)Y.name=$.name;for(let b of Wz)if($[b]!==void 0)Y[b]=$[b];if(J!==void 0)Y.duplicateStrategy=J;if(w!==void 0)Y.status=w;if(Object.keys(Y).length===0)throw Error("Provide at least one field to change when calling `update_popup`.");Q=await D("PATCH",`/api/v1/popups/${encodeURIComponent(X)}`,Y,G);break}case"get_popup_embed":{let G=$.companyId,X=A("get_popup_embed",$,"popupId");Q=await D("GET",`/api/v1/popups/embed/${encodeURIComponent(X)}`,void 0,G);break}case"duplicate_popup":{let G=$.companyId,X=A("duplicate_popup",$,"popupId"),J={};if($.name!==void 0)J.name=$.name;Q=await D("POST",`/api/v1/popups/${encodeURIComponent(X)}/duplicate`,J,G);break}case"delete_popup":{let G=$.companyId,X=A("delete_popup",$,"popupId");Q=await D("DELETE",`/api/v1/popups/${encodeURIComponent(X)}`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function Qz(W,$){let Q;switch(W){case"list_products":{let G=$.companyId,X=new URLSearchParams;if(typeof $.provider==="string"&&$.provider.trim())X.set("provider",$.provider.trim());if(typeof $.search==="string"&&$.search.trim())X.set("search",$.search.trim());let J=G0("list_products",$,"limit",1,100);if(J!==void 0)X.set("limit",String(J));let w=G0("list_products",$,"offset",0,Number.MAX_SAFE_INTEGER);if(w!==void 0)X.set("offset",String(w));let Y=X.size>0?`?${X.toString()}`:"";Q=await D("GET",`/api/v1/products${Y}`,void 0,G);break}case"upsert_products":{let G=$.companyId;if(!Array.isArray($.products)||$.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");Q=await D("POST","/api/v1/products",{products:$.products},G);break}case"delete_product":{let G=$.companyId,X=A("delete_product",$,"productId");Q=await D("DELETE",`/api/v1/products/${encodeURIComponent(X)}`,void 0,G);break}case"attach_product_file":{let G=$.companyId,X=A("attach_product_file",$,"productId"),J=B($,"url"),w=B($,"filePath");if(J===void 0===(w===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let Y;if(w!==void 0){let b=await eH(w,G);Y={url:b.url,source:"upload",fileName:B($,"fileName")??b.fileName,fileSizeBytes:b.fileSizeBytes,mimeType:b.mimeType}}else{Y={url:J};let b=B($,"fileName");if(b)Y.fileName=b}Q=await D("PUT",`/api/v1/products/${encodeURIComponent(X)}/delivery`,Y,G);break}case"remove_product_file":{let G=$.companyId,X=A("remove_product_file",$,"productId");Q=await D("DELETE",`/api/v1/products/${encodeURIComponent(X)}/delivery`,void 0,G);break}case"sync_products":{let G=$.companyId,X=new URLSearchParams;if(typeof $.integrationId==="string"&&$.integrationId)X.set("integrationId",$.integrationId);let J=X.toString();Q=await D("POST",`/api/v1/products/sync${J?`?${J}`:""}`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function AM(W){let $=B(W,"campaignId"),Q=B(W,"sequenceId"),G=B(W,"templateId"),X=[$,Q,G].filter((J)=>J!==void 0);if(X.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(X.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if($!==void 0)return`/api/v1/campaigns/${encodeURIComponent($)}/render`;if(Q!==void 0){let J=A("render_email",W,"nodeId");return`/api/v1/sequences/${encodeURIComponent(Q)}/nodes/${encodeURIComponent(J)}/render`}return`/api/v1/templates/${encodeURIComponent(G)}/render`}var OM=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function Gz(W,$){if(W!=="render_email")return{handled:!1,result:void 0};let Q=AM($),G={};for(let J of OM)if($[J]!==void 0)G[J]=$[J];return{handled:!0,result:await D("POST",Q,G,B($,"companyId"))}}var Xz=80,Jz=10;function ZM(W){if(!Array.isArray(W.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(W.recipients.length>Jz)throw Error(`\`recipients\` must include no more than ${Jz} email addresses when calling \`send_sequence_test_email\`.`);if(W.recipients.find((X)=>typeof X!=="string"||X.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let Q=Array.from(new Set(W.recipients.map((X)=>typeof X==="string"?X.trim().toLowerCase():""))).filter(Boolean);if(Q.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let G=Q.find((X)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(X));if(G)throw Error(`Invalid test recipient email address: \`${G}\`.`);return Q}function KM(W){let $=W.trim().replace(/\s+/g," ");if($.length<=Xz)return $;return`${$.slice(0,Xz-3).trimEnd()}...`}async function MQ(W,$){let Q;switch(W){case"generate_sequence":{let G=A("generate_sequence",$,"goal"),X=typeof $.name==="string"&&$.name.trim().length>0?$.name.trim():void 0,w=(await MQ("create_sequence",{...$,goal:G,name:X??KM(G),trigger:"contact_added",durationDays:$.durationDays??14})).result;return{handled:!0,result:typeof w==="object"&&w!==null?{...w,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:w}}case"list_sequences":{let G=$.companyId,X=new URLSearchParams;for(let w of["status","search","limit","offset"])if($[w]!==void 0)X.set(w,String($[w]));if(Array.isArray($.labels)&&$.labels.length>0)X.set("labels",$.labels.join(","));let J=X.size>0?`?${X.toString()}`:"";Q=await D("GET",`/api/v1/sequences${J}`,void 0,G);break}case"get_sequence":{let G=$.companyId;Q=await D("GET",`/api/v1/sequences/${$.sequenceId}`,void 0,G);break}case"list_sequence_enrollments":{let G=$.companyId,X=A(W,$,"sequenceId"),J=new URLSearchParams;for(let Y of["currentNodeId","status","subscriberId"]){let b=$[Y];if(Array.isArray(b)){if(b.length>0)J.set(Y,b.join(","))}else if(b!==void 0)J.set(Y,String(b))}for(let Y of["email","sort","limit","offset"])if($[Y]!==void 0)J.set(Y,String($[Y]));let w=J.size>0?`?${J.toString()}`:"";Q=await D("GET",`/api/v1/sequences/${encodeURIComponent(X)}/enrollments${w}`,void 0,G);break}case"send_sequence_test_email":{let G=$.companyId,X=A(W,$,"sequenceId"),J=A(W,$,"nodeId"),w=ZM($);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(X)}/nodes/${encodeURIComponent(J)}/test`,{recipients:w},G);break}case"create_sequence":{let G=$.companyId;Z1("create_sequence",$),q6("create_sequence",$,{hasEmailSteps:!0});let X=Array.isArray($.steps),J=$.goal===void 0&&$.steps===void 0,w=await D("POST","/api/v1/sequences",$,G);if(!w.success){Q=w;break}let Y=w.sequence.id;if(X||J){let U=await D("GET",`/api/v1/sequences/${Y}`,void 0,G);if(U.success)Q={...w,success:!0,sequence:U.sequence,message:`Sequence "${U.sequence.name}" created ${J?"as a blank draft":"with explicit steps"}. Review it before enabling.${w.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else Q=U;break}let b=7,H=0,z="pending";while(z!=="complete"&&H<b){let U=await D("GET",`/api/v1/sequences/${Y}`,void 0,G);if(U.success)z=U.sequence.enrichmentStatus;if(H++,z!=="complete"&&H<b)await new Promise((L)=>setTimeout(L,20000))}let F=await D("GET",`/api/v1/sequences/${Y}`,void 0,G);if(F.success)Q={...w,success:!0,sequence:F.sequence,message:F.sequence.enrichmentStatus==="complete"?`Sequence "${F.sequence.name}" created with ${F.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${w.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${F.sequence.name}" created. Email enrichment is still in progress (${F.sequence.enrichedCount}/${F.sequence.emailCount} emails generated). You can check status with get_sequence.${w.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else Q=F;break}case"update_sequence":{let G=$.companyId,X=IH($);Q=await D("PUT",`/api/v1/sequences/${$.sequenceId}`,X,G);break}case"update_sequence_node":{let G=$.companyId,X=A("update_sequence_node",$,"sequenceId"),J=_H($);Q=await D("PUT",`/api/v1/sequences/${X}`,J,G);break}case"update_sequence_nodes":{let G=$.companyId,X=A("update_sequence_nodes",$,"sequenceId"),J=xH($);Q=await D("PUT",`/api/v1/sequences/${X}`,J,G);break}case"edit_sequence_graph":{let G=$.companyId,X=hH($);Q=await D("PUT",`/api/v1/sequences/${$.sequenceId}`,X,G);break}case"insert_sequence_step":{let G=$.companyId,X=yH($),J=await D("PUT",`/api/v1/sequences/${$.sequenceId}`,X,G);if(typeof J==="object"&&J!==null){let w=J,Y=w.sequence;if(typeof Y==="object"&&Y!==null){let b=Y;Q={...w,...b.insertedNodeIds!==void 0?{insertedNodeIds:b.insertedNodeIds}:{},...b.insertedEmailIds!==void 0?{insertedEmailIds:b.insertedEmailIds}:{},...b.insertedEmailCount!==void 0?{insertedEmailCount:b.insertedEmailCount}:{},...b.addedBranchNodeId!==void 0?{addedBranchNodeId:b.addedBranchNodeId}:{},...b.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:b.addedBranchPathNodeIds}:{}};break}}Q=J;break}case"enable_sequence":{let G=$.companyId;Q=await D("POST",`/api/v1/sequences/${$.sequenceId}/enable`,void 0,G);break}case"disable_sequence":{let G=$.companyId;Q=await D("POST",`/api/v1/sequences/${$.sequenceId}/disable`,void 0,G);break}case"duplicate_sequence":{let G=$.companyId,X=A("duplicate_sequence",$,"sequenceId"),J=B($,"name");Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(X)}/duplicate`,J===void 0?void 0:{name:J},G);break}case"archive_sequence":case"unarchive_sequence":{let G=$.companyId,X=A(W,$,"sequenceId"),J=W==="archive_sequence"?"archive":"unarchive";Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(X)}/${J}`,void 0,G);break}case"list_sequence_goals":{let G=$.companyId,X=A(W,$,"sequenceId");Q=await D("GET",`/api/v1/sequences/${encodeURIComponent(X)}/goals`,void 0,G);break}case"create_sequence_goal":case"update_sequence_goal":{let G=$.companyId,X=A(W,$,"sequenceId");if(W==="create_sequence_goal")A(W,$,"name"),NH($);else EH($);let J=W==="update_sequence_goal"?A(W,$,"goalId"):void 0,w={...$};delete w.companyId,delete w.sequenceId,delete w.goalId,Q=await D(W==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(X)}/goals${J?`/${encodeURIComponent(J)}`:""}`,w,G);break}case"delete_sequence_goal":{let G=$.companyId,X=A(W,$,"sequenceId"),J=A(W,$,"goalId");Q=await D("DELETE",`/api/v1/sequences/${encodeURIComponent(X)}/goals/${encodeURIComponent(J)}`,void 0,G);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let G=$.companyId,X=A(W,$,"sequenceId");if($.clearFieldMapping===!0&&$.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if($.clearSamplePayload===!0&&$.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let J=W==="configure_sequence_inbound_webhook",w=W==="rotate_sequence_inbound_webhook_secret",Y=J?{...$.clearFieldMapping===!0?{fieldMapping:null}:$.fieldMapping!==void 0?{fieldMapping:$.fieldMapping}:{},...$.clearSamplePayload===!0?{samplePayload:null}:$.samplePayload!==void 0?{samplePayload:$.samplePayload}:{}}:void 0;Q=await D(w?"POST":J?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(X)}/inbound-webhook${w?"/rotate-secret":""}`,Y,G);break}case"pause_sequence_enrollments":{let G=$.companyId;Q=await D("POST",`/api/v1/sequences/${$.sequenceId}/pause-enrollments`,void 0,G);break}case"resume_sequence_enrollments":{let G=$.companyId;Q=await D("POST",`/api/v1/sequences/${$.sequenceId}/resume-enrollments`,void 0,G);break}case"enroll_subscribers_in_sequence":{let G=$.companyId,X=A("enroll_subscribers_in_sequence",$,"sequenceId"),J=aH($);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(X)}/enroll`,J,G);break}case"cancel_sequence_enrollments":{let G=$.companyId,X=uH($);Q=await D("POST",`/api/v1/sequences/${$.sequenceId}/enrollments/cancel`,X,G);break}case"move_sequence_enrollments":{let G=$.companyId,X=A("move_sequence_enrollments",$,"sequenceId"),J=cH($);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(X)}/enrollments/move`,J,G);break}case"realign_sequence_enrollments":{let G=$.companyId,X=A("realign_sequence_enrollments",$,"sequenceId"),J=fH($);Q=await D("POST",`/api/v1/sequences/${encodeURIComponent(X)}/enrollments/realign-sending-window`,J,G);break}case"get_sequence_enrollment_realignment":{let G=$.companyId,X=A(W,$,"sequenceId"),J=A(W,$,"jobId");Q=await D("GET",`/api/v1/sequences/${encodeURIComponent(X)}/enrollments/realign-sending-window/jobs/${encodeURIComponent(J)}`,void 0,G);break}case"delete_sequence":{let G=$.companyId;Q=await D("DELETE",`/api/v1/sequences/${$.sequenceId}`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}function P9(W,$,Q){let G=$[Q];if(G===void 0)return;if(!Array.isArray(G))throw Error(`\`${Q}\` must be an array of strings when calling \`${W}\`.`);let X=G.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter((J)=>J.length>0);if(X.length!==G.length)throw Error(`\`${Q}\` must contain only non-empty strings when calling \`${W}\`.`);return X}function PM(W,$){let Q=P9(W,$,"tags");if(Q===void 0||Q.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${W}\`.`);let G=P9(W,$,"emails"),X=P9(W,$,"externalIds"),J=P9(W,$,"subscriberIds");if((G?.length??0)+(X?.length??0)+(J?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${W}\`.`);return{tags:Q,...G?.length?{emails:G}:{},...X?.length?{externalIds:X}:{},...J?.length?{subscriberIds:J}:{},...W==="bulk_add_subscriber_tags"&&typeof $.triggerAutomations==="boolean"?{triggerAutomations:$.triggerAutomations}:{}}}async function wz(W,$){let Q;switch(W){case"add_subscriber":{let G=$.companyId,X=typeof $.phone==="string"&&$.phone.trim()!==""?$.phone.trim():void 0,J=X?DQ($):W1("add_subscriber",$),w=u("add_subscriber",$,"status",["active","unsubscribed","bounced"]),Y=u("add_subscriber",$,"optInMode",["default","confirmed","double_opt_in"]);if(Q=await D("POST","/api/v1/subscribers",{...J,...X!==void 0&&{phone:X},...typeof $.phoneCountry==="string"&&$.phoneCountry.trim()!==""&&{phoneCountry:$.phoneCountry.trim()},...typeof $.smsConsent==="boolean"&&{smsConsent:$.smsConsent},...$.firstName!==void 0&&{firstName:$.firstName},...$.lastName!==void 0&&{lastName:$.lastName},customAttributes:$.attributes,tags:$.tags,lists:$.listIds,...w!==void 0&&{status:w},...Y!==void 0&&{optInMode:Y},...$.createdAt!==void 0&&{createdAt:$.createdAt}},G),w!==void 0&&h(Q)&&h(Q.subscriber)&&Q.subscriber.skipped===!0&&Q.subscriber.status!==w)throw Error(`Existing subscriber was not changed to status '${w}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let G=$.companyId;if(!Array.isArray($.subscribers)||$.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if($.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let w=0;w<$.subscribers.length;w+=1){let Y=$.subscribers[w],b=h(Y)&&typeof Y.email==="string"&&Y.email.trim()!=="",H=h(Y)&&typeof Y.phone==="string"&&Y.phone.trim()!=="";if(!b&&!H)throw Error(`Subscriber record ${w} must include an email or a phone number.`)}let X=u("create_subscriber_import",$,"duplicateStrategy",["skip","merge","overwrite"]),J=u("create_subscriber_import",$,"optInMode",["default","confirmed","double_opt_in"]);Q=await D("POST","/api/v1/subscribers/imports",{subscribers:$.subscribers,...X!==void 0&&{duplicateStrategy:X},...$.fileName!==void 0&&{fileName:$.fileName},...$.listIds!==void 0&&{listIds:$.listIds},...$.enrollInSequences!==void 0&&{enrollInSequences:$.enrollInSequences},...$.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:$.defaultPhoneCountry},...$.smsConsent!==void 0&&{smsConsent:$.smsConsent},...J!==void 0&&{optInMode:J}},G);break}case"get_subscriber_import":{let G=$.companyId,X=A("get_subscriber_import",$,"importId");Q=await D("GET",`/api/v1/subscribers/imports/${encodeURIComponent(X)}`,void 0,G);break}case"update_subscriber":{let G=$.companyId,X=W1("update_subscriber",$),J=u("update_subscriber",$,"status",["active","unsubscribed","bounced"]),Y=h($.attributes)||$.addTags!==void 0||$.removeTags!==void 0?await S4(X,G):null,b=Array.isArray(Y?.subscriber.tags)?Y.subscriber.tags.filter((L)=>typeof L==="string"):[],H=Array.isArray($.addTags)?$.addTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(zQ):[],z=new Set(Array.isArray($.removeTags)?$.removeTags.filter((L)=>typeof L==="string"&&L.trim()!=="").map(zQ):[]),F=b.filter((L)=>!z.has(L));for(let L of H)if(!F.includes(L))F.push(L);let U={};if(X.email&&X.externalId)U.externalId=X.externalId;if($.firstName!==void 0)U.firstName=$.firstName;if($.lastName!==void 0)U.lastName=$.lastName;if(typeof $.phone==="string"||$.phone===null)U.phone=$.phone;if(typeof $.phoneCountry==="string")U.phoneCountry=$.phoneCountry;if(typeof $.smsConsent==="boolean")U.smsConsent=$.smsConsent;if(J!==void 0)U.status=J;if(h($.attributes))U.customAttributes={...h(Y?.subscriber.customAttributes)?Y.subscriber.customAttributes:{},...$.attributes};if($.addTags||$.removeTags)U.tags=F;Q=await D("PATCH",L9(X),U,G);break}case"remove_subscriber":{let G=$.companyId,X=W1("remove_subscriber",$),J=L9(X);if($.hardDelete===!0)Q=await D("DELETE",J,void 0,G);else Q=await D("PATCH",J,{status:"unsubscribed"},G);break}case"get_subscriber":{let G=$.companyId,X=W1("get_subscriber",$);Q=await S4(X,G,{includeMachineEngagement:$.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let G=$.companyId,X=W1("list_subscriber_notes",$);Q=await D("GET",FQ(X),void 0,G);break}case"add_subscriber_note":{let G=$.companyId,X=W1("add_subscriber_note",$),J=typeof $.body==="string"?$.body.trim():void 0;if(!J)throw Error("`body` is required when calling `add_subscriber_note`.");if(J.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");Q=await D("POST",FQ(X),{body:J},G);break}case"delete_subscriber_note":{let G=$.companyId,X=typeof $.noteId==="string"?$.noteId.trim():"";if(!X)throw Error("`noteId` is required when calling `delete_subscriber_note`.");Q=await D("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(X)}`,void 0,G);break}case"trigger_subscriber_event":{let G=$.companyId,X=W1("trigger_subscriber_event",$),J=A("trigger_subscriber_event",$,"event");if($.properties!==void 0&&!h($.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");Q=await D("POST","/api/v1/subscribers/events",{...X,event:J,...$.properties!==void 0&&{properties:$.properties},...$.firstName!==void 0&&{firstName:$.firstName},...$.lastName!==void 0&&{lastName:$.lastName},...$.attributes!==void 0&&{customAttributes:$.attributes},...$.occurredAt!==void 0&&{occurredAt:$.occurredAt},...$.eventId!==void 0&&{eventId:$.eventId}},G);break}case"trigger_subscriber_events":{let G=$.companyId,X=W1("trigger_subscriber_events",$);if(!Array.isArray($.events)||$.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if($.events.length>500)throw Error("`trigger_subscriber_events` accepts at most 500 events per call. Split a larger history import into several calls.");for(let J=0;J<$.events.length;J+=1){let w=$.events[J];if(!h(w)||typeof w.name!=="string"||w.name.trim()==="")throw Error(`Event ${J} must include a non-empty \`name\` string.`)}Q=await D("POST","/api/v1/subscribers/events/bulk",{...X,events:$.events,...$.firstName!==void 0&&{firstName:$.firstName},...$.lastName!==void 0&&{lastName:$.lastName},...$.attributes!==void 0&&{customAttributes:$.attributes}},G);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let G=$.companyId,X=PM(W,$);Q=await D("POST",`/api/v1/subscribers/bulk/tags/${W==="bulk_add_subscriber_tags"?"add":"remove"}`,X,G);break}case"search_subscribers":{let G=$.companyId;Q=await tH($,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}async function Yz(W,$){if(W!=="get_recipient_suppression"&&W!=="remove_recipient_suppression")return{handled:!1,result:void 0};let Q=B($,"companyId"),G=A(W,$,"email"),X=B($,"region"),J=new URLSearchParams;if(X)J.set("region",X);let w=`/api/v1/suppressions/${encodeURIComponent(G)}${J.size>0?`?${J}`:""}`;return{handled:!0,result:await D(W==="get_recipient_suppression"?"GET":"DELETE",w,void 0,Q)}}async function bz(W,$){let Q;switch(W){case"list_team_members":{let G=$.companyId;Q=await D("GET","/api/v1/team",void 0,G);break}case"invite_team_member":{let G=$.companyId,X=A("invite_team_member",$,"email"),J=C4("invite_team_member",$,"role",["admin","viewer","restricted"]);if($.canManageBilling!==void 0&&typeof $.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");Q=await D("POST","/api/v1/team/invitations",{email:X,role:J,...$.canManageBilling!==void 0&&{canManageBilling:$.canManageBilling}},G);break}case"cancel_team_invitation":{let G=$.companyId,X=A("cancel_team_invitation",$,"invitationId");Q=await D("DELETE",`/api/v1/team/invitations/${encodeURIComponent(X)}`,void 0,G);break}case"list_conversations":{let G=$.companyId,X=new URLSearchParams,J=u("list_conversations",$,"status",["open","closed","all"]);if(J)X.set("status",J);let w=B($,"search");if(w)X.set("search",w);if($.unread!==void 0){if(typeof $.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if($.unread)X.set("unread","true")}if($.page!==void 0){if(typeof $.page!=="number"||!Number.isInteger($.page)||$.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");X.set("page",String($.page))}let Y=G0("list_conversations",$,"limit",1,100);if(Y!==void 0)X.set("limit",String(Y));Q=await D("GET",`/api/v1/conversations${X.size>0?`?${X}`:""}`,void 0,G);break}case"get_conversation":{let G=$.companyId,X=A("get_conversation",$,"conversationId");Q=await D("GET",`/api/v1/conversations/${encodeURIComponent(X)}`,void 0,G);break}case"reply_to_conversation":{let G=$.companyId,X=A("reply_to_conversation",$,"conversationId"),J=u("reply_to_conversation",$,"type",["outbound","note"])??"outbound",w=B($,"subject"),Y=B($,"bodyText"),b=B($,"bodyHtml");if(J==="outbound"&&Y===void 0&&b===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");Q=await D("POST",`/api/v1/conversations/${encodeURIComponent(X)}/messages`,{type:J,...w!==void 0&&{subject:w},...Y!==void 0&&{bodyText:Y},...b!==void 0&&{bodyHtml:b}},G);break}case"update_conversation_status":{let G=$.companyId,X=A("update_conversation_status",$,"conversationId"),J=C4("update_conversation_status",$,"status",["open","closed"]);Q=await D("POST",`/api/v1/conversations/${encodeURIComponent(X)}/status`,{status:J},G);break}case"mark_conversation_read":{let G=$.companyId,X=A("mark_conversation_read",$,"conversationId");Q=await D("POST",`/api/v1/conversations/${encodeURIComponent(X)}/read`,void 0,G);break}case"list_webhooks":{let G=$.companyId;Q=await D("GET","/api/v1/webhooks",void 0,G);break}case"create_webhook":{let G=$.companyId,X=A("create_webhook",$,"name"),J=A("create_webhook",$,"url"),w=LQ("create_webhook",$);Q=await D("POST","/api/v1/webhooks",{name:X,url:J,...w!==void 0&&{events:w}},G);break}case"update_webhook":{let G=$.companyId,X=A("update_webhook",$,"webhookId"),J=B($,"name"),w=B($,"url"),Y=LQ("update_webhook",$),b=u("update_webhook",$,"status",["enabled","disabled"]);if(J===void 0&&w===void 0&&Y===void 0&&b===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");Q=await D("PATCH",`/api/v1/webhooks/${encodeURIComponent(X)}`,{...J!==void 0&&{name:J},...w!==void 0&&{url:w},...Y!==void 0&&{events:Y},...b!==void 0&&{status:b}},G);break}case"delete_webhook":{let G=$.companyId,X=A("delete_webhook",$,"webhookId");Q=await D("DELETE",`/api/v1/webhooks/${encodeURIComponent(X)}`,void 0,G);break}case"test_webhook":{let G=$.companyId,X=A("test_webhook",$,"webhookId");Q=await D("POST",`/api/v1/webhooks/${encodeURIComponent(X)}/test`,void 0,G);break}case"list_webhook_deliveries":{let G=$.companyId,X=A("list_webhook_deliveries",$,"webhookId"),J=G0("list_webhook_deliveries",$,"limit",1,100),w=new URLSearchParams;if(J!==void 0)w.set("limit",String(J));Q=await D("GET",`/api/v1/webhooks/${encodeURIComponent(X)}/deliveries${w.size>0?`?${w}`:""}`,void 0,G);break}case"replay_webhook_delivery":{let G=$.companyId,X=A("replay_webhook_delivery",$,"webhookId"),J=A("replay_webhook_delivery",$,"deliveryId");Q=await D("POST",`/api/v1/webhooks/${encodeURIComponent(X)}/deliveries/${encodeURIComponent(J)}/replay`,void 0,G);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:Q}}var Hz=[l3,a3,t3,wz,Yz,Qz,i3,n3,d3,o3,Gz,r3,$z,e3,s3,MQ,p3,bz,g3];var VM=new Set(["create_campaign","update_campaign","create_template","update_template","set_template_localization","create_transactional_email","update_transactional_email","create_sequence","update_sequence","update_sequence_node","update_sequence_nodes","insert_sequence_step","update_ab_test_variant","create_ab_test"]);function zz(W){return typeof W==="object"&&W!==null&&!Array.isArray(W)}function qQ(W){if(Array.isArray(W))return W.some(qQ);if(!zz(W))return!1;for(let[$,Q]of Object.entries(W)){if(($==="html"||$==="htmlContent")&&typeof Q==="string"&&Q.trim().length>0)return!0;if(qQ(Q))return!0}return!1}function Dz(W,$,Q){if(!VM.has(W)||!qQ($)||!zz(Q))return Q;let G=Array.isArray(Q.warnings)?Q.warnings.filter((X)=>typeof X==="string"):[];return{...Q,warnings:[...new Set([...G,m8])]}}var V9="Ordinary searches are ordered newest-created first; attribute-filtered searches are ordered by subscriber ID ascending. Sort the returned array yourself if you need another order.",jM={search_subscribers:{filters:"Use the tags, list/listId/listName, status, and attribute arguments for single conditions, or create_segment plus segmentId for compound, OR, engagement, or event conditions.",filterJoinOperator:"The supported arguments always combine with AND. Use create_segment plus segmentId for OR logic.",sortBy:V9,sortOrder:V9,sort:V9,order:V9,attributes:'Filter on one attribute at a time with attribute: "attributeName:value".',customAttributes:'Filter on one attribute at a time with attribute: "attributeName:value".',page:"Omit limit to fetch every page automatically, or set limit to cap the result size.",offset:"Omit limit to fetch every page automatically, or set limit to cap the result size.",cursor:"Omit limit to fetch every page automatically, or set limit to cap the result size."}},Fz=null;function MM(W){return Fz??=new Map(Z9.map(($)=>{let Q=$.inputSchema.properties;return[$.name,new Set(Q&&typeof Q==="object"?Object.keys(Q):[])]})),Fz.get(W)??null}function Uz(W,$){let Q=MM(W);if(!Q)return;let G=Object.keys($??{}).filter((Y)=>!Q.has(Y));if(G.length===0)return;let X=jM[W]??{},J=[...new Set(G.flatMap((Y)=>X[Y]?[X[Y]]:[]))],w=Q.size>0?`Supported arguments: ${[...Q].map((Y)=>`\`${Y}\``).join(", ")}.`:`\`${W}\` takes no arguments.`;throw Error([`Unsupported field${G.length===1?"":"s"}: ${G.map((Y)=>`\`${Y}\``).join(", ")}.`,`\`${W}\` rejects arguments it does not support rather than ignoring them, because ignoring them would return a result that silently does not match the request.`,w,...J].join(" "))}var Lz=Z9.map(H3).map(BH);async function Bz(W,$){try{Uz(W,$);let Q,G=!1;for(let J of Hz){let w=await J(W,$);if(w.handled){Q=w.result,G=!0;break}}if(!G)throw Error(`Unknown tool: ${W}`);let X=nH(Q);if(X)throw X;return Q=Dz(W,$,Q),Q=await $3(W,$,Q),{structuredContent:z3(Q),content:[{type:"text",text:JSON.stringify(Q,null,2)}]}}catch(Q){return{isError:!0,content:[{type:"text",text:V1(Q)}]}}}async function Az(W,$,Q){let G=$.getRequestContext?.(W)??{};try{return await M9(G,Q)}finally{await $.onRequestContextUpdated?.(G,W)}}function IQ(W={}){let $=new x8({name:"sequenzy",version:HH.version},{capabilities:{tools:{},resources:{}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.","If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","IMPORTANT: whenever the user wanted to accomplish something and these tools did not expose functionality for it (missing tool, missing argument, unsupported workflow, or broken behavior), call submit_feedback describing the gap before finishing the task. When a tool call produced a wrong or unexpected result, include userIntent, toolCalls, expected, actual, and resourceIds in the submission so the team can reproduce it. The Sequenzy team reads every submission and uses it to decide what to build next."].join(`
|
|
58
|
+
`)});return $.setRequestHandler(j$,async()=>{return{tools:Lz}}),$.setRequestHandler(e6,async(Q,G)=>{let{name:X,arguments:J}=Q.params;return Az(G,W,()=>Bz(X,J??{}))}),$.setRequestHandler(B$,async()=>{return{resources:FH}}),$.setRequestHandler(O$,async(Q,G)=>{let{uri:X}=Q.params;return Az(G,W,()=>UH(X))}),$}import Zz from"node:process";class NQ{append(W){this._buffer=this._buffer?Buffer.concat([this._buffer,W]):W}readMessage(){if(!this._buffer)return null;let W=this._buffer.indexOf(`
|
|
59
|
+
`);if(W===-1)return null;let $=this._buffer.toString("utf8",0,W).replace(/\r$/,"");return this._buffer=this._buffer.subarray(W+1),qM($)}clear(){this._buffer=void 0}}function qM(W){return Zw.parse(JSON.parse(W))}function Oz(W){return JSON.stringify(W)+`
|
|
60
|
+
`}class EQ{constructor(W=Zz.stdin,$=Zz.stdout){this._stdin=W,this._stdout=$,this._readBuffer=new NQ,this._started=!1,this._ondata=(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()},this._onerror=(Q)=>{this.onerror?.(Q)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let W=this._readBuffer.readMessage();if(W===null)break;this.onmessage?.(W)}catch(W){this.onerror?.(W)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(W){return new Promise(($)=>{let Q=Oz(W);if(this._stdout.write(Q))$();else this._stdout.once("drain",$)})}}async function IM(){yQ(),kQ();let W=IQ(),$=new EQ;await W.connect($),console.error("Sequenzy MCP server running on stdio")}IM().catch((W)=>{console.error(V1(W)),process.exit(1)});export{M9 as withMcpRequestContext,v4 as setSelectedCompanyId,j1 as getSelectedCompanyId,IQ as createSequenzyMcpServer,D as apiRequest};
|